os.system() does not return the control of the subshell spawned by it, instead it returns only the exit code when the subshell is done executing the command. This can be verified by:
x = os.system("echo 'shankar'")
print(x)
What you need is the subprocess
library.
You can use the subprocess.Popen()
function to start a subprocess. This function returns the control of the subprocess as an object which can be manipulated to control the subprocess.
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results.
Run it:
import subprocess
proc = subprocess.Popen(['foo', 'bar', 'bar'], stdout=subprocess.PIPE, shell=True)
Hereproc
is the returned object which provides control over the spawned subprocess. You can retrieve information about the process or manipulate it with this object.
proc.pid # returns the id of process
Stop it:
proc.terminate() # terminate the process.
Popen.terminate()
is the equivalent of sending ctrl+c
(SIGTERM) to the subprocess.
You can get the output using Popen.communicate()
function.
Get output:
out, err = proc.communicate()
Note: Popen.communicate()
returns output only when the subprocess has exited successfully or has been terminated or killed.