The question is rather straightforward but not answered by searching. How do I determine in a python script whether this script is imported as a module or run as a script? Is there a difference at all in python?
The problem is, that I want to evaluate the command line parameters only if run as a script, but not if the module is only imported to use it in another script. (I want to be able to use one script as both library and program.) I am afraid the vanilla way would be to build the lib and a second script that uses it, but I'd like to have a second option for small tool/libs.
A script is a Python file that's intended to be run directly. When you run it, it should do something. This means that scripts will often contain code written outside the scope of any classes or functions. A module is a Python file that's intended to be imported into scripts or other modules.
Use: if "sys" not in dir(): print("sys not imported!")
Because this is just how Python works - keywords such as class and def are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be empty.
from python docs:
When you run a Python module with
python fibo.py
the code in the module will be executed, just as if you imported it, but with the
__name__
set to"__main__"
. That means that by adding this code at the end of your module:
if __name__ == '__main__': # Running as a script
you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With