How to determine the pid of a process running through os.system

I want to run several subprocesses using a program, i.e. the module foo.pystarts several instances bar.py.

Since I sometimes have to interrupt a process manually, I need a process identifier to execute the kill command.

Despite the fact that the whole setup is quite "dirty", is there a good pythonic way to get the process pidif the process is started through 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")
+4
source share
3 answers

os.systemreturn exit code. It does not provide the pid of the child process.

Use the subprocessmodule.

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

, terminate kill. ( kill)

proc.terminate()
+6

, :

, fortran exe . os.forkpty, pid , pid . , , .

:

exec_cmd = 'nohup ./FPEXE & echo $! > /tmp/pid'

os.system(exec_cmd)

pids , .

+2

Instead, you can use os.forkpty()that as the result code gives pid and fd for the pseudo-terminal. Further documentation here: http://docs.python.org/2/library/os.html#os.forkpty

+1
source

All Articles