- Running the .py directly, like python manage.py
- Imported from another module, like from admin import manage.py
So how do python know whether the module is directly run as a main program or it is just a part of another module? The special variable __name__ will do the job!
Take a look at this piece of code
if __name__ == '__main__':
print 'I am run by itself'
else:
print 'I am imported as module'
So if the .py is being run as a main program, the __name__ will have value __main__ being set, otherwise, the __name__ 's value will become the module name itself. We can therefore deal with different situations depending on the program's executing behaviour.
沒有留言:
張貼留言