如何让输入函数在另一个代码为 运行(使用多处理)时工作?
How do I get an input function to work whilst another code is running (using multiprocessing)?
我无法将此代码作为 运行 的输入,而另一个代码块正在 运行ning。我想知道有没有解决方法,我的代码如下
import multiprocessing
def test1():
input('hello')
def test2():
a=True
while a == True:
b = 5
if __name__ == "__main__":
p1 = multiprocessing.Process(target=test1)
p2 = multiprocessing.Process(target=test2)
p1.start()
p2.start()
p1.join()
p2.join()
当代码为 运行 时,我收到一个 EOF 错误,这显然是在输入功能中断时发生的。
这不是您的全部代码,因为它没有显示多处理。但是,问题是只有主进程可以与控制台交互。其他进程没有标准输入。如果需要,您可以使用队列与主进程通信,但通常您希望辅助进程几乎是独立的。
我会让主进程创建一个守护进程 thread
负责执行 input
并创建未充分利用的全双工 Pipe
提供两个双向通信 Connection
次。为简单起见,以下演示仅创建一个 Process
实例,该实例循环执行 input
请求回显响应,直到用户输入 'quit':
import multiprocessing
import threading
def test1(conn):
while True:
conn.send('Please enter a value: ')
s = conn.recv()
if s == 'quit':
break
print(f'You entered: "{s}"')
def inputter(conn):
while True:
# The contents of the request is the prompt to be used:
prompt = conn.recv()
conn.send(input(prompt))
if __name__ == "__main__":
conn1, conn2 = multiprocessing.Pipe(duplex=True)
t = threading.Thread(target=inputter, args=(conn1,), daemon=True)
p = multiprocessing.Process(target=test1, args=(conn2,))
t.start()
p.start()
p.join()
我无法将此代码作为 运行 的输入,而另一个代码块正在 运行ning。我想知道有没有解决方法,我的代码如下
import multiprocessing
def test1():
input('hello')
def test2():
a=True
while a == True:
b = 5
if __name__ == "__main__":
p1 = multiprocessing.Process(target=test1)
p2 = multiprocessing.Process(target=test2)
p1.start()
p2.start()
p1.join()
p2.join()
当代码为 运行 时,我收到一个 EOF 错误,这显然是在输入功能中断时发生的。
这不是您的全部代码,因为它没有显示多处理。但是,问题是只有主进程可以与控制台交互。其他进程没有标准输入。如果需要,您可以使用队列与主进程通信,但通常您希望辅助进程几乎是独立的。
我会让主进程创建一个守护进程 thread
负责执行 input
并创建未充分利用的全双工 Pipe
提供两个双向通信 Connection
次。为简单起见,以下演示仅创建一个 Process
实例,该实例循环执行 input
请求回显响应,直到用户输入 'quit':
import multiprocessing
import threading
def test1(conn):
while True:
conn.send('Please enter a value: ')
s = conn.recv()
if s == 'quit':
break
print(f'You entered: "{s}"')
def inputter(conn):
while True:
# The contents of the request is the prompt to be used:
prompt = conn.recv()
conn.send(input(prompt))
if __name__ == "__main__":
conn1, conn2 = multiprocessing.Pipe(duplex=True)
t = threading.Thread(target=inputter, args=(conn1,), daemon=True)
p = multiprocessing.Process(target=test1, args=(conn2,))
t.start()
p.start()
p.join()