0
我正在試圖創建一個簡單的python腳本來學習如何使用多處理。我想在後臺創建一個進程,它將生成虛擬數據並將其放入隊列中,同時用戶仍然可以輸入命令。進程不會在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 - help\ns - select a profile\no - output a profile\nd -
download a profile\nd - display selected profile\nr - 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)
我很困惑,因爲is_alive調用返回false即使p.start()被調用的幾行之前。
謝謝!我對管道還是有些模糊,所以我會讀到這個話題。我試圖讓這個進程在由用戶輸入控制的循環中運行。我想要做的是讓用戶仍然可以輸入命令的過程中,不斷地生成和打印數據到屏幕上。最後我想擴展到一些連接到LabView的代碼,其中後臺進程將記錄來自傳感器的數據,並且我需要用戶仍然能夠通過前端來控制程序。 – egemnay
@egemnay,如上所述,你需要的是一個線程,而不是一個進程 - https://docs.python.org/2/library/threading.html?highlight=threading#module-threading – droravr