【问题标题】:Get live value of variable from another script从另一个脚本获取变量的实时值
【发布时间】:2018-02-22 19:28:52
【问题描述】:

我有两个脚本,new.py 和 test.py。

测试.py

import time
while True:
    x = "hello"
    time.sleep(1)
    x = "world"
    time.sleep(1)

新的.py

import time
while True:
    import test    
    x = test.x

    print(x)
    time.sleep(1)

现在,据我了解,这应该在执行 new.py 时始终打印“hello”和一秒钟后的“world”。 它不打印任何东西,我该如何解决?

谢谢

【问题讨论】:

  • 对不起我之前的回答......这是完全错误的。你需要线程来做这样的事情......或者只是一个while循环。在单个线程中,您不能同时处于 2 个非嵌套的 while 循环中。

标签: python python-3.x


【解决方案1】:

我认为下面的代码可以满足您的要求。这里我模拟了两个独立运行的脚本(通过使用线程),然后展示如何使用shelve 在它们之间进行通信。请注意,可能有更好的方法可以实现您所追求的目标——但如果您绝对必须独立运行脚本,那么这对您有用。

顺便说一句,任何持久源都可以(例如数据库)。

import shelve
import time
import threading


def script1():
    while True:
        with shelve.open('my_store') as holder3:
            if holder3['flag'] is not None: break
            print('waiting')
            time.sleep(1)
    print("Done")


def script2():
    print("writing")
    with shelve.open('my_store') as holder2:
        holder2['flag'] = 1


if __name__ == "__main__":

    with shelve.open('my_store') as holder1:
        holder1['flag'] = None

    t = threading.Thread(target=script1)
    t.start()

    time.sleep(5)
    script2()

    t.join()

产量

waiting
waiting
waiting
waiting
waiting
writing
Done

【讨论】:

    【解决方案2】:

    测试.py

    import time
    def hello():
        callList = ['hello', 'world']
        for item in callList:
            print item
            time.sleep(1)
    
    hello()
    

    新的.py

    from parent import hello
    
    while True:
        hello()
    

    【讨论】:

    • 抱歉,忘记说明了。这只是一个小程序来炫耀我的问题。我在某个地方有一个程序,其中一个值可以是“这个”或“那个”,基于一些现在不重要的事情。一旦值更改为“this”,我希望其他程序执行某些操作。
    • 您能否更好地描述实际问题?
    • 基本上我有两个程序正在运行。主程序和一个包含变量“active”的小程序。 “活跃”取决于我的 RPI 上的 IR 屏障。一旦“活动”从真变为假,我想通知我的主程序。
    • 不确定如何使用实时变量将您带到那里,对不起,伙计
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2016-09-02
    • 2011-02-08
    • 2019-03-31
    • 2013-03-02
    • 1970-01-01
    相关资源
    最近更新 更多