Press "Enter" to skip to content

How to Determine Python Program Run Directly or Through Import?

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:

Vinish Kapoor

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *