tags:

views:

55

answers:

1

Hi,

I want to control several subprocesses of the same type from python (I am under linux). I want to:

  • Start them.
  • Stop them.
  • Ask if they are still running.

I can start a processes with with spawnl, and get the pid. Using this pid I can stop it with kill. And I am sure there is also a way to ask if it is running with the pid.

The problem is, what if the following happens: I start a process, remember the pid. The process ends without me noticing and another completely different process starts getting assigned the same pid. I attempt to kill my process, I kill a completely different one.

What is the better way to start and control processes in python? Thanks!

+5  A: 

You can use subprocess.Popen to start the other process, and save the resulting Popen object. With methods on that object, you can check if the process still alive, wait for it to finish, terminate it, kill it -- all without any risk of pid-based confusion! As a plus, this is also a more cross-platform approach, though you may not care specifically in this case.

Alex Martelli