简体   繁体   中英

Importing a Function from another module

I want to import a function named ret() from a module called mainprog into another module named windw .

So I did it like this in the windw module:

from mainprog import ret

This is supposed to work right?
But there is an infinite loop in the mainprog module.
So, even without calling the function I imported, it just keeps loading forever when I try to run the windw module.

So I guess it runs the whole mainprog module when I import? I need help to avoid this.

You are doing fine, all you need to do is make the loop not execute unless you are running the code by itself What you need to do is add a

if __name__ == '__main__':
    while True: 

This will make your program work as before, but make it possible to import functions within your code

You must make sure that the file mainprog.py does not have anything besides definitions of functions, constants and a __main__ guard .

If you have anything else defined like so:

do_something()
def ret():
    ...

Be sure to convert it to:

def ret():
    ...
if __name == '__main__':
    do_something()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM