I'm writing a python file mylib.py
I'd like mylib.py to do something based on sys.argv
if it's being executed as a script. But if it's imported from some other script, I don't want it to do that.
How can I tell if my python file is being imported or it's a main script?
(I've seen how to do this before, but I forgot.)
Python files can act as either reusable modules, or as standalone programs. if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.
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.
if __name__ == '__main__':
# this was run as a main script
Here is the documentation on __main__
.
Usually this code is placed at the bottom of a module, and one common way to keep your code clean is to create a main()
function that does all of the work, and only call that function inside of the conditional.
if __name__ == '__main__':
# goes here only when module is being executed directly
Packages also can contain __main__
module, which is executed when you do python -m foo
(or execute zipfile containing the package).
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