Python 从另一个模块中定义的函数更改模块中的全局变量

Python 从另一个模块中定义的函数更改模块中的全局变量,python,global,Python,Global,我有一个模块,它有一个主函数,在标志为true时运行循环。 在循环中,有对另一个模块中定义的函数的调用,该函数检查条件,如果条件为真,则应停止主循环 代码是: main.py import other isRunning = True def shutdown(): global isRunning isRunning = False def main(): while isRunning: # some logic here othe

我有一个模块,它有一个主函数,在标志为true时运行循环。 在循环中,有对另一个模块中定义的函数的调用,该函数检查条件,如果条件为真,则应停止主循环

代码是:

main.py

import other

isRunning = True
def shutdown():
    global isRunning
    isRunning = False

def main():
    while isRunning:
        # some logic here
        other.check()

if __name__ == '__main__':
    main()
other.py

import main

def check():
    someCondition = #some logic to check the condition
    if someCondition:
        main.shutdown()
启动
main.py
文件运行代码

问题是,当在循环中调用
other.check()
时,会调用
main.shutdown()
函数,但主循环仍在运行。在主循环中,
isRunning
变量始终是
True
,但我希望在
main.shutdown()函数中设置后它会变成
False
。 为什么会这样?我错过了什么

我可以重构代码,以更智能的方式管理循环的退出,但我想知道是否有保持这种代码结构的解决方案。

尝试以下方法:

import other


def main():
    while other.run():
        # some logic here
        other.check()

if __name__ == '__main__':
    main()
其他的

import main

isRunning = True
def run():
    return isRunning

def check():
    global isRunning
    someCondition = #some logic to check the condition
    if someCondition:
        isRunning = False

如果我是你,我会使用对象和类…,全局方法和变量不是“调试和维护友好的”

问题与加载两次的
main.py
文件有关。当您将其作为脚本运行时,它首先被加载为
\uuuuu main\uuuu
。它还通过
other.py
作为其常规名称
main
导入

这两个副本彼此完全分离,并且具有单独的全局变量!当
other.check
调用
main.shutdown
以修改
isRunning
全局变量时,它只更改
main.isRunning
版本,而不更改
\u main\uuu.isRunning
。主要功能是检查
\uuuuu main\uuuu.isRunning
,它永远不会被更改


有几种方法可以解决此问题。最好是以某种方式摆脱循环导入。虽然循环导入在Python中可以正常工作,但它通常是糟糕设计的征兆。将其用于任何可能作为脚本运行的模块是一个非常糟糕的想法。

您可能需要在main()中使用一个
全局isRunning
语句。我知道这种设计很糟糕,我只是做了一些快速测试来检查一些想法,我介入了这个问题。我不知道你描述了什么,这将是非常有用的。谢谢