I have a python DES script that ends in a call to main(). That runs the main menu and starts the DES process. I would like to run analytics on my DES functions with another script. Whenever I do something like from DES.py import des to try to avoid having main run, it still starts anyway. How do I import the functions and keep the trailing reference to main from being called?
1 Answer
When you import a module in Python, you execute the code in that module. So if your module looks like this:
def main():
print 'Hello, world.'
main()
Then every time you import your module, it will execute the call to
main(). To prevent this from happening, you can look at the special
variable __name__, which is set to __main__ in the main program --
the thing that was directly started by the interpreter. When you
import a module, __name__ is set to something else (generally, the
name of the module). If you want to have code that is run when
directly executing your module (python mymodule.py) but is ignored
when importing your module (import mymodule), then you can check the
value of the __name__ variable:
def main():
print 'Hello, world.'
if __name__ == '__main__':
main()
The above code will execute main() when run directly, but will not
when imported.