我想同时运行2个进程。 1 将继续每秒打印“a”,另一个进程将要求输入,当输入为“Y”时,第一个进程将停止打印“a”。我对 Python 还很陌生,我不明白......
这是我到目前为止想到的:
from multiprocessing import Process
import time
go = True
def loop_a():
global go
while go == True:
time.sleep(1)
print("a")
def loop_b():
global go
text = input('Y/N?')
if text == 'Y':
go = False
if __name__ == '__main__':
Process(target=loop_a).start()
Process(target=loop_b).start()
这是我收到的错误消息:
Process Process-2:
Traceback (most recent call last):
File "C:\Users\Tip\AppData\Local\Programs\Python\Python36\lib\multiprocessing\process.py", line 249, in _bootstrap
self.run()
File "C:\Users\Tip\AppData\Local\Programs\Python\Python36\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "F:\ProgrammingTK\PROGproject\test.py", line 15, in loop_b
text = input('Y/N?')
EOFError: EOF when reading a line
扩展于jasonharper
的评论,因为他是正确的。
有几个问题
- The
go
变量是not进程之间共享。正如杰森建议的那样,你可以使用类似的东西Manager
in multiprocessing
为了在多个进程之间共享值。从技术上来说,go
变量将被复制到每个进程中,但不会在它们之间共享,因此一个进程中的更改不会被另一个进程看到。
- 再次,正如他提到的,你需要拉
input(..)
进入程序的主线程。另外,如果您使用的是 2.7,则需要使用raw_input(..)
.
- 另外,如果您只检查一次标志然后退出,那么您可能会遇到
BrokenPipeError
.
考虑到这一点,你可以尝试这样的事情:
from multiprocessing import Process, Manager
import time
def loop_a(go):
while True:
# run forever and print out the msg if the flag is set
time.sleep(1)
if go.value:
print("a")
if __name__ == '__main__':
# shared value flag
manager = Manager()
go_flag = manager.Value('flag', True)
# other process that is printing
Process(target=loop_a, args=(go_flag,)).start()
# normal main thread; toggle on and off the other process
while True:
text = input('Stop Y/N?')
if text == 'Y':
go_flag.value = False
print("Changed the flag {}".format(go_flag.value))
else:
go_flag.value = True
print("Changed the flag {}".format(go_flag.value))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)