繁体   English   中英

Python打开并杀死子进程

[英]Python open and kill subprocess

我正在使用Widnows 7(32位),这是我的代码:

def start_mviewer_broker(broker_path, test_name):
""" The function starts the broker server"""
try:
    print("**** start_mviewer_broker ****")
    p = subprocess.Popen('start python ' + broker_path + ' ' + test_name, shell=True)
    return p
except:
    print("**** start_mviewer_broker - EXCEPTION ****")
    return 0


def kill_process(p):
""" The function kills the input running process"""
try:
    print("**** kill_process ****")
    p.terminate()
except:
    print("**** kill_process - EXCEPTION ****")
    pass

我有几个问题。 启动子进程的唯一方法是使用shell = True选项。 如果我将此选项更改为False,则不会启动子进程。

另一个问题是,kill进程不会杀死我的进程,但是不会引发异常。

任何想法?

您需要将代码更改为以下内容:

def start_mviewer_broker(broker_path, test_name):
""" The function starts the broker server"""
try:
    print("**** start_mviewer_broker ****")
    return subprocess.Popen('python ' + broker_path + ' ' + test_name) # Note changed line here
except:
    print("**** start_mviewer_broker - EXCEPTION ****")
    return 0


def kill_process(p):
""" The function kills the input running process"""
try:
    print("**** kill_process ****")
    p.terminate()
except:
    print("**** kill_process - EXCEPTION ****")
    pass

不需要您正在运行的start部分。 实际上,它不是可执行文件,而是cmd命令。 因此,它需要外壳程序才能运行。 这就是为什么它不仅仅与shell=False一起工作的原因。 但是,将其删除后,现在可以使用shell=False 然后,您将python进程作为返回的进程,而不是用于生成它的shell。 杀死python进程是您要做的,而不是shell,因此,删除start部分后,您将使kill_process()代码正常工作。

顺便说一句, shell=Falsesubprocess.Popen()的默认设置,因此在上面的代码中被忽略了。 同样,将p设置为该过程然后立即返回它似乎浪费了一行代码。 可以将其简化为直接返回它(如上面的代码所示)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM