首页 > 解决方案 > 从 Python 循环中的另一个文件访问变量

问题描述

我有一个主要读取测量值的文件。这个函数在一个 while True 循环中。在这个循环中,我想在变量通过过程时更改它。设置它没有问题。我遇到的问题是从另一个文件访问这个变量。

文件 1:

def main()
    print("obtaining token")
    obtainnewtoken()

    while True:
        print("******LOOP****** + str(i)")
        (read measurement stuff ) 
        postTrue = True
        return postTrue

文件 2:

from File1 import *

newPostTrue = main()

def codechecker():
    print(newPostTrue)

当我同时运行这两个文件时,File2 只运行 File1 的主文件。如何访问另一个文件中循环中的变量?

另外我仍然想分别运行这两个文件。此设置是临时的。

标签: pythonfunctionloopsvariables

解决方案


您可以使用称为生成器的东西,它会“生成”一个值一次,然后您可以使用 next() 函数从生成器中获取下一个值。

文件_1:

def Generator():
    i = 0
    while True:
        print("******LOOP******" + str(i))
        i += 1
        yield i

文件_2:

from File_1 import *

newPostTrue = Generator()


def codechecker():
    j = next(newPostTrue)
    while (j < 10):
        print(j)
        j = next(newPostTrue)


codechecker()

推荐阅读