python - Stop a command line command in script -
this question has answer here:
i'm writing script in want able run command line command, os.system("stuff"). if command doesn't end on own? like, in terminal have ctl+c end it. there way can run it, stop it, , grab output?
i'm sure there has don't know it, , i'm not sure if know correct terminology find (all python self-taught experimenting)
thanks!
os.system() not return control of subshell spawned it, instead returns exit code when subshell done executing command. can verified by:
x = os.system("echo 'shankar'") print(x)
what need subprocess
library. can use subprocess.popen()
function start subprocess. function returns control of subprocess object can manipulated control subprocess.
the subprocess module provides more powerful facilities spawning new processes , retrieving results.
run it:
import subprocess proc = subprocess.popen(['foo', 'bar', 'bar'], stdout=subprocess.pipe, shell=true)
hereproc
returned object provides control on spawned subprocess. can retrieve information process or manipulate object.
proc.pid # returns id of process
stop it:
proc.terminate() # terminate process.
popen.terminate()
equivalent of sending ctrl+c
(sigterm) subprocess.
you can output using popen.communicate()
function.
get output:
out, err = proc.communicate()
note: popen.communicate()
returns output when subprocess has exited or has been terminated or killed.
Comments
Post a Comment