Search code examples
pythonsubprocesspopen

Terminating started Popen subprocess in Python


I am on Windows and I am starting a new process using subprocess.Popen that I want to terminate at a certain point. However, the gui that I initiated is still visible. A minimal example would be starting the PNG viewer:

import subprocess
proc = subprocess.Popen(['start', 'test.png'], shell=True)
proc.kill()

After the kill() command the gui is still running and I have to close it manually.

As fas as I understood this can be solved on Linux by passing preexec_fn=os.setsid to Popen (see How to terminate a python subprocess launched with shell=True). Since the command os.setsid is specific to Linux I do not know how to realize that on Windows.

Another way would be to get rid of the shell=True, however, I don't know how to realize that because I have to pass the file name.

Any help would be greatly appreciated...


Solution

  • If you want to get rid of the shell=True you have to give the full path to the executable.

    import subprocess
    proc = subprocess.Popen('/full/path/start %s' % filename)
    proc.kill()