python - 选择 python popen process.kill() 或 process.terminate() 的更优雅的方法

标签 python subprocess popen kill terminate

我有一个小函数,旨在杀死或终止子进程及其子进程。

我试图以更优雅的方式编写它,而不是重复 if、else 两次。

def kill_process(cls, process, kill_type):
    process = psutil.Process(process.pid)

    for proc in process.children(recursive=True):

        if kill_type== 'terminate':

            proc.terminate()

        else:

            proc.kill()


    if kill_type== 'terminate':

        process.terminate()

    else:

        process.kill()

最佳答案

如果目标是不使用 if/else 语句两次,您可以使用辅助方法:

def kill_or_terminate(proc, kill_type):
     if kill_type == 'terminate':
            proc.terminate()
        else:
            proc.kill()

def kill_process(cls, process, kill_type):
    process = psutil.Process(process.pid)

    for proc in process.children(recursive=True):
        kill_or_terminate(proc, kill_type)

    kill_or_terminate(process, kill_type)

或者将父进程添加到子进程列表的末尾,这样所有进程都在一个可迭代中:

def kill_process(cls, process, kill_type):
    process = psutil.Process(process.pid)
    for proc in process.children(recursive=True) + [process]:
        if kill_type == 'terminate':
            proc.terminate()
        else:
            proc.kill()

关于python - 选择 python popen process.kill() 或 process.terminate() 的更优雅的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48468274/

相关文章:

python: 无法打开文件 'python DACscrap.py &' : [Errno 2] 没有这样的文件或目录...但是它有吗?

python - 将子进程输出从 Python 脚本附加到文件

Python - subprocess.Popen - ssh -t user@host 'service --status-all'

python - django unicode 转换为日语

Python smtplib 没有属性 SMTP_SSL

python - 如果存在可选参数,则不需要所有位置参数

python - 查看从 Python 调用的长时间运行的外部进程的输出

python - Python 中使用不同分隔符连接列表

python - 子流程调用中的用户输入?

python - Subprocess.Popen 在解释器、可执行脚本中的行为不同