Chris
Chris

Reputation: 999

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...

Upvotes: 0

Views: 204

Answers (2)

jfs
jfs

Reputation: 414159

start is an internal command: it requires cmd.exe (that you could start using shell=True or run directly). Popen() does not wait for start command to finish and start does not wait for the PNG viewer to exit -- by the time you call proc.kill(), start might have finished already.

You could try to run PNG viewer directly instead (you don't need to provide the full path if the corresponding exe-file can be found in the standard locations).

How to terminate a python subprocess launched with shell=True has a solution for Windows too (you could try it if PNG viewer starts child processes).

Upvotes: 1

oz123
oz123

Reputation: 28858

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

Upvotes: 2

Related Questions