我有一个将数据写入文本文件的函数,第二个函数从同一文本文件中提取数据并显示图形。我想在第一个函数启动后几秒钟启动第二个函数并一起运行直到两个函数完成。通过这种方式,我可以获得实时图表。我在下面编写的代码同时启动了两个函数,但第二个函数看不到任何文本文件。我需要一点延迟第二个函数来给第一个函数创建文本文件的时间。
然而,因为第二个函数(live_graph)不仅需要从文本文件中提取数据,而且还需要从第一个函数中获取一些参数(例如图的标题),我不确定这是否是正确的继续进行方式,因为看起来不可能从另一个函数获得“关键”;我得到了“未定义的密钥”。也许我必须写文件文件也参数?
from multiprocessing import Process
import time
def writing():
numentries = 0
for text in get_all(newlista, "sentence", "text"):
if text.lower().startswith( key.lower().split(None, 1)[0] ):
pass
elif len(text) > 500:
pass
elif len(text) < 80:
pass
else:
on_data(text)
numentries += 1
def live_graph():
#pull data from text.txt
time.sleep(5)
if __name__=='__main__':
p1 = Process(target = writing)
p1.start()
p2 = Process(target = live_graph)
p2.start()
答案 0 :(得分:0)
例如(来自文档):
from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
您可以在代码中使用它:
from multiprocessing import Process, Queue
import time
def writing(q):
keep_running = True
numentries = 0
key = 'something, I assume'
for text in get_all(newlista, "sentence", "text"):
# Python lets you do nice comparisons like this,
# which do what they look like. And make it more
# obvious that you only want lines of length between
# 80 and 500 characters
if 80 < len(text) < 500:
firstword = key.lower().split(None, 1)[0]
if text.lower().startswith(firstword):
# Note: it is *essential* that in `on_data(text)`
# after writing to your file you run `file.flush()`
# or close the file, otherwise the data *may* be
# buffered and hence, missing, when you go to read
# the file
on_data(text)
q.put(keep_running)
keep_running = False
q.put(keep_running)
def live_graph(q):
keep_running = True
while keep_running:
keep_running = q.get()
# do the graph updates here
if __name__=='__main__':
q = Queue()
p1 = Process(target = writing, args=(q,))
p1.start()
p2 = Process(target = live_graph, args=(q,))
p2.start()