Chris
Chris

Reputation: 4317

In python, how do I get the same behavior as when __name__ == '__main__':

What is the best way to get this block of code to run when I import main.py rather than run it?

#main.py
if __name__ == '__main__':
    #Do something interesting. 


#Do something to have the interesting code run after importing the file. 
import main.py
main.__main__() # wrong of course. 

Upvotes: 0

Views: 265

Answers (4)

jcollado
jcollado

Reputation: 40384

You don't even need to check anything since the module code is executed when imported for the first time as part of its initialization. In particular, according to the documentation:

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module is imported somewhere.

If what you need is some code to be executed when the module is imported, but not when the module is execute, then the response from Antoine Pelisse should be the way to go (of course, you could also check if __name__ != '__main__' directly).

Upvotes: 2

Brooks Moses
Brooks Moses

Reputation: 9527

Assuming you want to do this without modifying the main.py module (so that "Cat Plus Plus"'s answer doesn't apply):

You can't directly; __name__ is read-only. (Edit: This is not actually quite true, as you can use the imp module to explicitly specify it when loading the file -- see the first answer on How to make __name__ == '__main__' when running module.)

However, you can do it indirectly, with execfile('main.py').

Upvotes: 0

Antoine Pelisse
Antoine Pelisse

Reputation: 13099

Are you looking for that ?

#main.py
if __name__ == '__main__':
    # Do something interesting when running main.py directly
    pass
else:
    # Do something when the script in imported
    pass

Upvotes: 1

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

Put that code into a function, and call it inside if.

def main():
    # ...

if __name__ == '__main__':
    main()

Or simply don't use if at all.

Upvotes: 11

Related Questions