How to know if python script was run using interpreter's -m option?

I couldn't find answer after having read all the following:

Rationale: When a test script which uses relative imports is being run without -m option I could print a warning message instead of leaving user with standard traceback leading to ValueError: Attempted relative import in non-package exception. Without knowing this I can catch this exception and only suggest lack of -m option could be the reason of error.

Answers


Another observation is that __package__ is set to None when executing the script directly and to the package name when using -m (using the empty string when the module isn't included in any package, so it's still different from None).


Disclaimer: this is just an observation, I have not seen it in the docs so it is probably implementation dependent and might not be consistent across different Python versions.

I have noticed that when calling a script using a -m option a variable called __loader__ is added to the namespace, so at the top of your script you could check for existence of that variable:

if '__loader__' in globals():
    # called with -m

For some extra safety you could check to see if __loader__ is an instance of pkgutil.ImpLoader:

if '__loader__' in globals() and __loader__.__class__.__name__ == 'ImpLoader':

Need Your Help

Simulating fire with SPH particles

simulation physics modeling particles particle-system

I want to simulate fire using SPH particles. I understand the concept behind SPH but don't understand yet how to model the fire as a fluid.

jQuery delegate

jquery delegates

i am slightly confused about how jquery's Delegate Function works.

Multiple developers using single web.config with different settings

c# asp.net-mvc asp.net-mvc-3 web-config

I'm creating an ASP.Net MVC web app. There are multiple developers on the team that need to have different settings in the web.config file. These settings are for the database connection and a lo...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.