How to close a program I execute with subprocess.Popen?

jitudon at jitudon at
Fri Jul 6 07:14:45 CEST 2007

On Jun 29, 6:36 pm, revenan... at wrote:
> I'm writing a program which has to execute a command, get its output
> and show it on a treeview.
> This command runs for a very long time.
> I want to end the execution of the command when the user closes my
> application.
> Right now I'm using an object my_child of type subprocess.Popen to
> execute the command, inside a thread with an infinite loop where we
> constantly ask for its output.
> To end the program when the user closes the application, I send a
> SIGTERM to the process with pid using os.kill. But I also
> have to send a SIGTERM to + 1 because is the
> pid of /bin/sh -c which is the one which calls the command, because
> when I try to run Popen with shell=False, it sends an exception and
> says the file or directory doesn't exist.
> Anyone knows of a better way to close the command than using a
> SIGTERM? I just can't help myself thinking this is an ugly dirty hack.

As nick pointed out use process group's .
I use the  "preexec_fn" keyword argument to Popen and "os.setsid()"
call's side effect
to make process groups and then os.killpg() to send the signal to
process groups.

child = Popen( cmd , preexec_fn = os.setsid )


More information about the Python-list mailing list