我有一个小函数,用于杀死或终止子进程及其子进程。
我试图以更优雅的方式编写它,而不是重复if,否则两次。
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()
答案 0 :(得分:1)
如果目标是没有两次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()