简体   繁体   English

从另一个模块导入功能

[英]Importing a Function from another module

I want to import a function named ret() from a module called mainprog into another module named windw . 我想从一个名为mainprog的模块中导入一个名为ret()的函数到另一个名为windw模块中。

So I did it like this in the windw module: 因此,我在windw模块中这样做:

from mainprog import ret

This is supposed to work right? 这应该工作正常吗?
But there is an infinite loop in the mainprog module. 但是mainprog模块中存在无限循环。
So, even without calling the function I imported, it just keeps loading forever when I try to run the windw module. 因此,即使不调用我导入的函数,当我尝试运行windw模块时,它也将永远保持加载状态。

So I guess it runs the whole mainprog module when I import? 所以我猜它在导入时会运行整个mainprog模块吗? 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 . 您必须确保文件mainprog.py除了函数定义,常量和__main__保护之外没有其他内容。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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