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:

  • Python Examples
Vinish Kapoor
Vinish Kapoor

Vinish Kapoor is a seasoned software development professional and a fervent enthusiast of artificial intelligence (AI). His impressive career spans over 20 years, marked by a relentless pursuit of innovation and excellence in the field of information technology. As an Oracle ACE, Vinish has distinguished himself as a leading expert in Oracle technologies, a title awarded to individuals who have demonstrated their deep commitment, leadership, and expertise in the Oracle community.