简体   繁体   English

在另一个文件中使用从无限循环 function 返回的变量

[英]Using variables returned from infinite loop function in another file

I know the title may sound a bit confusing but here is my struggle:我知道标题可能听起来有点混乱,但这是我的挣扎:

I have two separate files, one is only for gathering data and converting (data_.py) it and the second is main program file (main_.py).我有两个单独的文件,一个仅用于收集数据并转换(data_.py),第二个是主程序文件(main_.py)。 The core function in data_.py looks like this (it is simplified ofc): data_.py 中的核心 function 看起来像这样(它是简化的 ofc):

def some_function():
    #here some python magic happens
  while True:
    #more magic
    return var1, var2, var3

variables are updated every few seconds.变量每隔几秒更新一次。 Now Im trying to use them in main_.py, so far I have this:现在我试图在 main_.py 中使用它们,到目前为止我有这个:

import data_

var1, var2, var3 = data_.some_function()

and when I print my variables everything works, but of course they are imported only once and not updated after.当我打印我的变量时,一切正常,但当然它们只导入一次并且之后不会更新。

I've tried doing this:我试过这样做:

import data_

while True:
    var1, var2, var3 = data_.some_function()
    print(var1, var2, var3)

to update them as frequently as possible, yet they aren't updating for some reason.尽可能频繁地更新它们,但由于某种原因它们没有更新。

Is there a way to achieve this while keeping function in separate files?有没有办法实现这一点,同时将 function 保存在单独的文件中?

The functionality you are looking for is generator.您正在寻找的功能是生成器。 Below is sudo code for your case以下是您的案例的 sudo 代码

you define you function like this.你像这样定义你 function 。 you gather and convert data and when a chunk of data is ready to be processed you give that to other code calling this function.您收集并转换数据,当准备好处理一大块数据时,您将其提供给调用此 function 的其他代码。 But this is not parallel processing.但这不是并行处理。 your some_function() pauses until that data is being processed.您的 some_function() 会暂停,直到正在处理该数据。

def some_function():
    #here some python magic happens
    while True:
        #more magic
        yield var1, var2, var3

then you use this function like below.然后你使用这个 function 如下所示。 the loop continues until while loop on some_function is not finished循环继续,直到 some_function 上的 while 循环未完成

for var1,var2,var3 in some_function():
    print(var1, var2, var3)

Working Example工作示例

def some_function():
    for x1, x2 in zip(range(1000),range(0,2000,2)):
        yield x1,x2


for x1,x2 in some_function():
    print(x1,x2)

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

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