How to Determine Python Program Run Directly or Through Import?

  • Python
  • 1 min read

In Python, use __name__ attribute to determine a Python program runs directly or through an import. Below I am giving an example.

Python __name__ Attribute Example

Attribute __name__ always returns __main__ if a Python program is running directly else it will print the program name. To test this, create a Python program, for example, test1.py and put the following code.

if __name__ == '__main__':
    print(__name__)
    print('Python program is running directly.')
else:
    print(__name__)
    print('Python program is running through an import.')

When you run the above program the output will be:

__main__
Python program is running directly.

Now create another Python program, for example, test2.py and import the above program and see the result. The following is an example.

import test1

print('test2.py')

Output:

test1
Python program is running through an import.
test2.py

You can see in the above result, that the program name (test1) printed through the test2.py instead of __main__ because it is running through an import.

This method could be useful if you want to control a Python program to run specific code when it is running directly or through an import.

See also:

  • Python Examples