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,则不会启动子进程。
其他问题是终止进程不会终止我的进程但不会引发异常。
有什么想法吗?
您可能希望将代码更改为以下内容:
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=False
是 subprocess.Popen()
的默认值,因此在上面的代码中被遗漏了。还有,给进程设置p
然后马上返回,好像是浪费了一行代码。可以简化为直接返回即可(如上代码所示)
我正在开发 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,则不会启动子进程。
其他问题是终止进程不会终止我的进程但不会引发异常。
有什么想法吗?
您可能希望将代码更改为以下内容:
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=False
是 subprocess.Popen()
的默认值,因此在上面的代码中被遗漏了。还有,给进程设置p
然后马上返回,好像是浪费了一行代码。可以简化为直接返回即可(如上代码所示)