从 python 中杀死一个子进程,包括它的子进程 [英] Killing a subprocess including its children from python

查看:49
本文介绍了从 python 中杀死一个子进程,包括它的子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 2.5 上使用 subprocess 模块来生成一个 java 程序(准确地说是 selenium 服务器),如下所示:

I'm using the subprocess module on python 2.5 to spawn a java program (the selenium server, to be precise) as follows:

import os
import subprocess

display = 0
log_file_path = "/tmp/selenium_log.txt"
selenium_port = 4455
selenium_folder_path = "/wherever/selenium/lies"

env = os.environ
env["DISPLAY"] = ":%d.0" % display
command = ["java", 
           "-server",
           "-jar", 
           'selenium-server.jar',
           "-port %d" % selenium_port]
log = open(log_file_path, 'a')
comm = ' '.join(command)
selenium_server_process = subprocess.Popen(comm,
                                           cwd=selenium_folder_path,
                                           stdout=log,
                                           stderr=log,
                                           env=env,
                                           shell=True)

一旦自动化测试完成,这个进程就会被终止.我正在使用 os.kill 来做到这一点:

This process is supposed to get killed once the automated tests are finished. I'm using os.kill to do this:

os.killpg(selenium_server_process.pid, signal.SIGTERM)
selenium_server_process.wait()

这不起作用.原因是shell子进程为java产生了另一个进程,而我的python代码不知道该进程的pid.我试过用 os.killpg 杀死进程组,但这也杀死了首先运行此代码的 python 进程.由于其他原因,将 shell 设置为 false 从而避免 java 在 shell 环境中运行也是不可能的.

This does not work. The reason is that the shell subprocess spawns another process for java, and the pid of that process is unknown to my python code. I've tried killing the process group with os.killpg, but that kills also the python process which runs this code in the first place. Setting shell to false, thus avoiding java to run inside a shell environment, is also out of the question, due to other reasons.

如何终止 shell 和由它生成的任何其他进程?

How can I kill the shell and any other processes generated by it?

推荐答案

处理一般问题:

p=subprocess.Popen(your_command, preexec_fn=os.setsid)
os.killpg(os.getpgid(p.pid), signal.SIGTERM)

setsid 将在新会话中运行该程序,从而为其及其子进程分配一个新进程组.对它调用 os.killpg 因此也不会降低你自己的 python 进程.

setsid will run the program in a new session, thus assigning a new process group to it and its children. calling os.killpg on it thus won't bring down your own python process also.

这篇关于从 python 中杀死一个子进程,包括它的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆