Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to tell if file executed as import vs. main script?

Tags:

python

import

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.)

like image 458
Jason S Avatar asked Jan 03 '12 17:01

Jason S


People also ask

What is if __ main __ in Python?

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.

What happens when you import a Python file?

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.

What is the difference between module and script in Python?

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.


2 Answers

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.

like image 189
Andrew Clark Avatar answered Oct 16 '22 11:10

Andrew Clark


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).

like image 31
Cat Plus Plus Avatar answered Oct 16 '22 09:10

Cat Plus Plus