简而言之,我试图运行一个带变量的函数(循环),比如'val',沿着另一个获取'val'用户输入的函数。用户将输入一个初始值,但随后可以更改该值,循环将不间断地运行并采用这个新值'val'。
我知道我需要使用多处理,队列和stdin,如下所示:Python user input in child process。虽然我似乎无法让进程运行。我发现每个部分的例子都有效,但是我无法让它们发挥作用。
from multiprocessing import Process, Queue
import time
import sys
import os
def reader(q):
while True:
#do some stuff
if q.empty() == False: #Code gets hung here
msg = q.get(block = False) #These few lines will change
if (msg == 10): #Not sure of syntax with this so going basic
print('Value:'+str(msg))
break
if __name__=='__main__':
q = Queue()
reader_p = Process(target=reader, args=((q),))
reader_p.daemon = True
reader_p.start()
while True:
msg = input("Enter: ")
q.put(msg)
reader_p.join()
*注意:我使用q.get() != false:
将其缩短,但又不确定语法。
当程序到达q.get()
时,问题似乎在q.get(block = False)
,然后程序停止并向我发出queue.empty
错误。
通过我的编辑,代码现在变得悬而未决。如果取出,则会出现上述错误。
Python不是我最好的语言,我不熟悉队列,所以这不是我非常了解的东西,所以我希望你能解决我的任何语法错误或者指出我是否正在使用任何不正确的函数。
编辑:有人提到线程可能是最好的选择,基于原始的措辞。但我会说我使用的实际代码使用2+循环(现在)并且需要在单个变量上运行。
Psudo Code:
process 1:
get input
infinte loop:
do something with input variable
#this is on a rasp pi and is just going to output onto display
#it needs to run on infinite loop till program is killed
precess 2:
check for new input
new input is different than last/first input?
send input to process #1