process id from os.system

Charles G Waldman cgw at fnal.gov
Fri Jul 21 19:02:41 EDT 2000


j vickroy <jvickroy at sec.noaa.gov> writes:

> How can I obtain the process id for a program launched via
> 
>   os.system (theProgram) ?
> 
> I would like to do this portability (Unix, Windows).
> 
> Presently on Unix, I'm getting the pid by parsing the output from:
> 
>   "ps -ef | grep theProgram"
> 
> but that seems messy and unreliable since "theProgram" may be truncated
> in the output from ps.

Yes, you really don't want to do "ps" (and it's not really portable
either, is it?  ps takes different flags on just about every flavor of
Unix).

I'd rather do something like:

###UNTESTED

def pid_system(cmdline):
    pid = os.fork()
    if pid:
        return pid
    else:
        os.execv("/bin/sh", ("sh", "-c", cmdline), os.environ)
        os._exit(0)


This works like "system" but returns you the PID of the child process.
The "/bin/sh" is there so you get shell command syntax in your command
line (wildcard expansion, backgrounding, I/O redirection, etc) just
like "os.system" does.  However if you don't need this, you can skip
the /bin/sh and just execv the program itself.  And you can pass in a
different dictionary for environment variables, if you like.

As far as portability to Windows: "/bin/sh" won't be there but
something like "command.com" or "cmd.exe" will, you can use that in
place of /bin/sh, or as stated above if you don't need to execute a
full-fledged command line but just a single program, you can skip the
shell entirely.



More information about the Python-list mailing list