我正在尝试制作一个简单的python脚本原型,以学习如何使用多处理。我想在后台有一个进程,它将生成虚拟数据并将其放入队列中,而用户仍然可以键入命令。
这是我的代码:
from multiprocessing import Process
from multiprocessing import Queue
import random
import os
global run
def waitForStart(q):
global run
print("(h for help)")
while run == 0:
response = input("Enter a command: n")
if response == "h":
print("h - helpns - select a profileno - output a profilend -
download a profilend - display selected profilenr - run selected profile")
if response == "r":
run = 1
beginInterface(q)
print("r")
def generateData(q):
data = random.randint(0,100)
q.put(data)
def beginControl(q):
print("bcontrol")
while run == 1:
generateData(q)
displayData()
adjustOutputs()
logData()
print("Finished Control")
def beginInterface(q):
global run
p.start()
print("binterface")
while run == 1:
response = input("pause? (y/n)n")
print(p.is_alive())
if response == 'y':
run = 0
def displayData():
print(q.get())
run = 0
q = Queue()
p = Process(target=beginControl , args=(q,))
waitForStart(q)
我很困惑,因为即使之前几行调用了 p.start((,is_alive调用也会返回 false。
由于您有两个进程,因此第二个进程中的run
0
并且永远不会进入循环。要在主进程和第二个进程之间进行通信,请使用管道或队列。
重要提示,如果在 Win 上不要忘记添加:
if __name__ == "__main__":
在这里看到原因。
另一件事,您永远不会将队列传递给displayData
,编辑为:
def displayData(q):
print(q.get())
另外,我认为您真正想要的是一个线程,因为此代码将使进程处于无限循环中。
这不完全是你的代码,但它传达了这个想法:
from multiprocessing import Process
from multiprocessing import Queue, Pipe
import random
import time
def waitForStart(q):
global run
print("(h for help)")
while True:
response = input("Enter a command: n")
if response == "h":
print("h - help"
"s - select a profile"
"o - output a profile"
"d - download a profile"
"d - display selected profile"
"r - run selected profile")
if response == "r":
run = 1
beginInterface()
print("r")
def generateData(q):
data = random.randint(0,100)
q.put(data)
def beginControl(q):
print("bcontrol")
while q.empty():
generateData(q)
displayData(q)
#adjustOutputs()
#logData()
print("Finished Control")
def beginInterface():
p.start()
print("binterface")
while True:
print(p.is_alive())
time.sleep(1)
q.put('DIE!')
p.join()
exit()
def displayData(q):
data = q.get()
if data != 'DIE!':
print(data)
if __name__ == "__main__":
q = Queue()
pip = Pipe()
p = Process(target=beginControl, args=(q,))
waitForStart(q)