无法在python中杀死Subprocess

时间:2017-03-30 15:18:14

标签: python multithreading python-2.7 subprocess

我试图打开一个python代码,说test_2.py从另一个python代码说test_1.py然后杀死Test_2.py执行窗口。

test_2.py包含:

def hello():
    print "Hello World"

while 1:
    hello()

在test_1.py中,我正在从语音识别中读取一些命令并在内部进行匹配。根据命令,我或者启动test_2执行或者杀死它。

我能够在新的控制台窗口中启动子进程,但是当我想终止操作时,test_1窗口关闭,terminate命令不会关闭test_2控制台窗口。我尝试过使用p.pid,p.kill,p.terminate甚至线程,但无法获得所需的结果。谁能让我知道我在这里缺少什么,以及做我想做的事情的正确方法是什么?

test_1.py代码:

import speech_recognition as sr
import threading
import os, sys, signal
from subprocess import Popen, CREATE_NEW_CONSOLE
import time
import psutil

COMMAND_Kill_1 = 'power off'
COMMAND_Kill_2 = 'switch off'

COMMAND_Start_1 = 'initialize'
COMMAND_Start_2 = 'initialise'

COMMAND_Upper_1 = 'upper case'
COMMAND_Upper_2 = 'uppercase'

def active_listen():
    global p

    recog = sr.Recognizer()

    print 'Say Command'

    with sr.Microphone() as src:
        audio = recog.listen(src)

    msg = ''

    try:
        msg = recog.recognize_google(audio)
        #print msg
    except sr.UnknownValueError:
        print "Not able to recognize the input"
    except sr.RequestError as e:
        print "Google request error"
    except:
        print "Unknown exception ocurred"
    finally:


        if ( (msg == COMMAND_Kill_1) or (msg == COMMAND_Kill_2) ):
            print msg

            Popen('taskkill /F /T /PID '+ str(p.pid))

        elif ( (msg == COMMAND_Upper_1) or (msg == COMMAND_Upper_2) ):
            print msg.upper()

        elif ( (msg == COMMAND_Start_1) or (msg == COMMAND_Start_2) ):
            print msg
            p = Popen('python test_2.py', shell=False, creationflags=CREATE_NEW_CONSOLE)
            print p.pid

        else:
            print msg

        return msg

while 1:
    active_listen()

0 个答案:

没有答案