I couldn't find answer after having read all the following:
- PEP 338 Executing modules as scripts
- documentation of
runpy
standard module - description of Python interpreter's
-m
option
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.
Another observation is that
__package__
is set toNone
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 fromNone
).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:For some extra safety you could check to see if
__loader__
is an instance ofpkgutil.ImpLoader
: