-2

I've created a couple of modules that are used in a game I'm trying to write. The modules themselves work fine (as part of the main program), but hang if I run them separately. Is there a way to make them not run/load up or perhaps instantly quit unless they are imported and run by the main program?

I'm very new to programming and make a lot of mistakes, so I constantly test run the code and at times forget to switch from the "module.py" tab to my "main.py" tab. It loads up the window and hangs, leaving no choice but to force-quit it from the task bar.

sloth
  • 99,095
  • 21
  • 171
  • 219
Roman Z.
  • 3
  • 3
  • 1
    Why can't your modules work if run directly? What do they do? – jonrsharpe Aug 08 '14 at 15:28
  • 1
    Do you have the `if __name__ == '__main__` clause at the bottom of your modules? You can use that to define behavior when run directly. – Al.Sal Aug 08 '14 at 15:37
  • Possible duplicate of [_Terminate importation of module non-fatally?_](http://stackoverflow.com/questions/6217505/terminate-importation-of-module-non-fatally). – martineau Aug 08 '14 at 16:57
  • I didn't have if __name__ == '__main__ in the modules. I'll try that, thank you. – Roman Z. Aug 08 '14 at 19:08

1 Answers1

1

If you're not wanting the code in you modules.py to be run independently, why not place it inside a function which you call in main.py?

For example modules.py

def foo():
    # code goes here

and in main.py

import modules

# when code from modules.py is required
modules.foo()

or you could have

from modules import foo

# when code from modules.py is required
foo()

-Thanks to @laurencevs for pointing out I merged both options :s

FinlayL
  • 196
  • 8
  • If you import foo *from* modules then it would just be foo(), not modules.foo() – laurencevs Aug 08 '14 at 16:03
  • Updated, I was going to do something such as from modules import foo as modules if the modules names was still required, but thought against it as it would be confusing – FinlayL Aug 08 '14 at 16:06
  • Thank you I tried doing what you suggested and think I found what caused the hanging of the modules. Both were importing each other. I'll fix that and use your solution. Thank you! – Roman Z. Aug 08 '14 at 19:07