How to determine pid of process started via os.system
Question: I want to start several subprocesses with a programm, i.e. a module `foo.py`
starts several instances of `bar.py`.

Since I sometimes have to terminate the process manually, I need the process
id to perform a kill command.

Even though the whole setup is pretty “dirty”, is there a good pythonic way to
obtain a process’ `pid`, if the process is started via `os.system`?

`foo.py:`

    
    
    import os
    import time
    os.system("python bar.py \"{0}\ &".format(str(argument)))
    time.sleep(3)
    pid = ???
    os.system("kill -9 {0}".format(pid))
    

`bar.py:`

    
    
    import time
    print("bla")
    time.sleep(10) % within this time, the process should be killed
    print("blubb")
    


Answer: `os.system` return exit code. It does not provide pid of the child process.

Use [`subprocess`](http://docs.python.org/3/library/subprocess.html) module.

    
    
    import subprocess
    import time
    argument = '...'
    proc = subprocess.Popen(['python', 'bar.py', argument], shell=True)
    time.sleep(3) # <-- There's no time.wait, but time.sleep.
    pid = proc.pid # <--- access `pid` attribute to get the pid of the child process.
    

To terminate the process, you can use
[`terminate`](http://docs.python.org/3/library/subprocess.html#subprocess.Popen.terminate)
method or
[`kill`](http://docs.python.org/3/library/subprocess.html#subprocess.Popen.kill).
(No need to use external `kill` program)

    
    
    proc.terminate()
    

