0

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 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.