How to check if it is running package file as main file
Run __main__
Modules defines functions and classes, and often we put test code which will run the functions and classes into the same file.
The following module has a function hello and a test run for it.
# hello.py # from w ww. ja v a 2 s. co m
def hello():
print "Hello, world!"
# A test:
hello()
If you import it as a module, the test code is executed:
import hello #prints out Hello, world!
hello.hello() #prints out Hello, world! again
The first "Hello, world!" is printed by the hello function in the hello.py. The second "Hello, world!" is printed by hello.hello() in the main code.
Basically we need to tell whether a module is being
run as a program on its own, or it is being imported into another program.
To do that, you need the variable __name__
. The __name__
stores the current
running context. The __name__
is the value of __main__
when code is running
under main program context. __name__
is the value of module name when running
under module.
We can make your module's test code more well behaved by putting in an if statement.
# hello.py # from w ww .j a v a 2 s. c om
def hello():
print "Hello, world!"
def test():
hello()
if __name__ == '__main__': test()
import hello
hello.hello() #prints out Hello, world!