我有两个脚本,new.py和test.py。
Test.py
import time
while True:
x = "hello"
time.sleep(1)
x = "world"
time.sleep(1)
new.py
import time
while True:
import test
x = test.x
print(x)
time.sleep(1)
根据我的理解,这应该在执行new.py时始终打印“hello”和第二个“world”。 它没有打印任何东西,我该如何解决?
由于
答案 0 :(得分: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
答案 1 :(得分:0)
Test.py
import time
def hello():
callList = ['hello', 'world']
for item in callList:
print item
time.sleep(1)
hello()
new.py
from parent import hello
while True:
hello()