我希望有一个进程持续监控RPi输入,并将一个变量(我选择了队列(设置为True或False以反映去抖动的值。然后,另一个进程将捕获图像(从流中(。 我写了一些代码只是为了检查我可以让多处理和信令(队列(正常工作(我是一个不成熟的编码员......
线程处理一切正常,但多处理会产生奇怪的错误。特别是"多处理,EOFError:读取一行时的EOF"。代码输出:-
this computer has the following number of CPU's 6
OK, started thread on separate processor, now we monitor variable
enter something, True is the key word:
Process Process-1:
Traceback (most recent call last):
File "c:Python34libmultiprocessingprocess.py", line 254, in _bootstrap
self.run()
File "c:Python34libmultiprocessingprocess.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:UsersPeterDocumentsNetBeansProjectstest_areasrctest4.py", line 16, in Wait4InputIsTrue
ValueIs = input("enter something, True is the key word: ")
EOFError: EOF when reading a line
此模块监视"端口"(我使用键盘作为输入(:
#test4.py
from time import sleep
from multiprocessing import Lock
def Wait4InputIsTrue(TheVar, TheLock):
while True:
sleep(0.2)
TheLock.acquire()
#try:
ValueIs = input("enter something, True is the key word: ")
#except:
# ValueIs = False
if ValueIs == "True":
TheVar.put(True)
print("changed TheVar to True")
TheLock.release()
此模块监视状态,并对其执行操作:
#test5.py
if __name__ == "__main__":
from multiprocessing import Process, Queue, Lock, cpu_count
from time import sleep
from test4 import Wait4InputIsTrue
print("this computer has the following number of CPU's", cpu_count())
LockIt = Lock()
IsItTrue = Queue(maxsize = 3)
Wait4 = Process(target = Wait4InputIsTrue, args = (IsItTrue, LockIt))
Wait4.start()
print("OK, started thread on separate processor, now we monitor variable")
while True:
if IsItTrue.qsize():
sleep(0.1)
print("received input from separate thread:", IsItTrue.get())
请注意,我尝试在 test4.py 中的输入语句中添加 try: ,在这种情况下,它会无限期地打印"输入一些东西,True 是关键字:",没有 cr。
我添加了锁定以疯狂尝试修复它,没有区别
有人知道为什么会这样吗?
您的问题可以归结为更简单的脚本:
import multiprocessing as mp
import sys
def worker():
print("Got", repr(sys.stdin.read(1)))
if __name__ == "__main__":
process = mp.Process(target=worker)
process.start()
process.join()
运行时,它会产生
$ python3 i.py
Got ''
读取零字节意味着管道已关闭,input(..)
将其变成EOFError
异常。
multiprocessing
模块不允许您读取stdin
。这通常是有道理的,因为混合来自多个孩子的stdin
读者是一项有风险的工作。事实上,深入研究实现,multiprocessing/process.py
明确地将stdin
设置为devnull
:
sys.stdin.close()
sys.stdin = open(os.devnull)
如果您只是使用 stdin
进行测试,那么解决方案很简单:不要这样做!如果你真的需要用户输入,生活就要困难得多。您可以使用其他队列以及父队列中的代码来提示用户并获取输入。