进程不会在python中启动

时间:2017-08-11 18:01:07

标签: python queue multiprocessing

我试图将一个简单的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)

我感到困惑,因为即使先前几行调用了p.start(),is_alive调用也会返回false。

1 个答案:

答案 0 :(得分:0)

由于您有两个进程,因此第二个进程中的run0并且永远不会进入循环。要在主进程和第二个进程之间进行通信,请使用Pipe or a Queue

重要提示,如果在Win上,请不要忘记添加:

if __name__ == "__main__":

See reason here.

另一件事,你从未将队列传递给displayData,编辑为:

def displayData(q):
    print(q.get())

另外,我认为你真正想要的是一个Thread ,因为这段代码会让Process处于一个无限循环中。

这不完全是你的代码,但它传达了这个想法:

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)