【问题标题】:Python open and kill subprocessPython打开并杀死子进程
【发布时间】:2015-08-30 17:04:28
【问题描述】:

我正在开发 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 进程不会杀死我的进程,但不会引发异常。

有什么想法吗?

【问题讨论】:

  • start 不是一个可执行文件,而是一个 cmd 命令,所以在使用它时你总是必须使用shell=True。返回的进程不是python进程,而是用来生成它的shell,所以杀死它不会有你想要的效果。不要使用start
  • 好的!非常感谢您。现在,没有开始一切都按我的意愿进行。

标签: python subprocess


【解决方案1】:

您可能希望将代码更改为以下内容:

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 才能运行。这就是为什么它不能只使用shell=False。但是,删除它后,您现在可以使用shell=False。然后,您将 python 进程作为返回的进程,而不是用于生成它的 shell。杀死 python 进程是你想要做的,而不是 shell,所以在删除 start 部分后,你将让 kill_process() 代码正常工作。

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

【讨论】: