Search code examples
pythonsubprocesspopenkillterminate

More elegant way to selecting python popen process.kill() or process.terminate()


I have small function that is designed for killing or terminating subproces and its subprocesses.

I am trying to write it in a more elegant way instead of repeating if, else twice.

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()

Solution

  • If the goal is to not have the if/else statement twice, you could use a helper method:

    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)
    

    Or add the parent process to the end of the list of children, so all the processes are in a single iterable:

    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()