【问题标题】:share global variables between modules在模块之间共享全局变量
【发布时间】:2020-04-25 19:04:17
【问题描述】:

我有 2 个 python 模块。其中一个有一个布尔变量,该变量不断变化(根据输入)。
在第二个模块中,我根据第一个模块中布尔变量的值做一些事情。

我希望这个共享变量同时更新,但自从我第一次导入它后,它的值并没有改变。
我尝试使用全局变量,但这也不起作用!

简而言之:

module1.py:

my_boolean = True
while True:
    a = input()
    if a == 'change':
        my_boolean = not my_boolean

在module2.py中:

import module1
while True:
    print (module1.my_boolean)

#The output of print is constant and is not real-time.

共享此变量及其更新值的正确方法是什么?

【问题讨论】:

  • 你有两个 while True 循环你也有两个线程吗?因为否则你的代码将无法工作......
  • 有两个不同的模块!两种不同的过程。为什么我需要线程??!!
  • 您将 module1 导入到 module2 中,因此您有一个进程。

标签: python


【解决方案1】:

您可以使用生成器函数来执行此操作。生成器是一个特殊的函数,它不是在调用时执行,而是返回一个迭代器,该迭代器执行主体,直到遇到yield 语句。任何带有yield 语句的函数都是生成器。

module1.py:

# This function will not execute until the for loop requests a value.
def getBools():
    my_boolean = True
    while True:
        a = input()
        if a == 'change':
            my_boolean = not my_boolean
        # Pause execution and hand this value to the for loop.
        yield my_boolean

module2.py:

import module1

for b in module1.getBools():
    print(b)

【讨论】:

    【解决方案2】:

    以下工作 - 也许对你有帮助

    模块 4:

    my_boolean = True
    

    模块 1:

    import module4
    
    def change_value():
        a = input()
        if a == 'change':
            module4.my_boolean = not module4.my_boolean
    

    模块 2:

    import module4
    
    def print_current_value():
        print (module4.my_boolean)
    
    #The output of print is constant and is not real-time.
    

    模块 3:

    from module1 import change_value
    from module2 import print_current_value
    
    while True:
        print_current_value()
        change_value()
    

    运行模块 3 表明模块正在共享模块 4 的变量。

    True
    change
    False
    change
    True
    asdf
    True
    asdf
    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-03
      • 2018-02-28
      • 2012-06-10
      • 1970-01-01
      • 2010-12-13
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多