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

More elegant way to selecting python popen process.kill() or process.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()