[Tutor] os.waitpid non spawned pid

Martin Walsh mwalsh at groktech.org
Sat Jun 21 05:22:14 CEST 2008

John [H2O] wrote:
> Hello, I would like to write a script that would have a command line option
> of a pid# (known ahead of time). Then I want my script to wait to execute
> until the pid is finished. How do I accomplish this?
> I tried the following:
> #!/usr/bin/env python
> import os
> import sys
> def run_cmd(cmd):
>    """RUN A BASH CMD"""
>    import subprocess as sub
>    p = sub.Popen( ['/bin/bash' , '-c' , cmd ],
>                  stdout = sub.PIPE , stderr = sub.STDOUT )
>    output = p.stdout.read()
>    return output
> r=os.waitpid(sys.argv[1],0);

To approximate the behavior you're looking for, I've seen it suggested
that you can send signal number 0 to a non-child process until you get a
meaningful result. Never used this approach myself, but it might look
something like this:

import os, time
def waitncpid(pid):
    while 1:
            os.kill(pid, 0)
        except OSError:


Not sure what this would do on a windows machine. And, I suppose it is
possible that your process could end, and another start with the same
pid while sleeping between kill attempts, but this seems unlikely to me,

> cmd = 'echo "Now %s has finished " ' %r
> run_cmd(cmd)


More information about the Tutor mailing list