[Tutor] why "ifconfig" is alway running?
Sander Sweers
sander.sweers at gmail.com
Sun Dec 19 14:05:51 CET 2010
On 19 December 2010 13:43, lei yang <yanglei.fage at gmail.com> wrote:
> Right, it gets stuck at the readline(), is there a function not get
> stuck to instead of readline().
readline() will keep reading stdout until it received a newline
character. So if there is nothing to read it will wait forever. The
solution is to wait with reading until there is actually something to
read. And it is recommended [1] to use proc.communicate() instead of
reading directly from stdout.
Also you should use proc.terminate() or proc.kill() to stop the command.
Below is a modified version of your function to show what I mean.
[1] http://docs.python.org/library/subprocess.html#subprocess.Popen.stdin
Greets
Sander
def host_run(cmd, secs=10):
print("running %s" % cmd)
timeout = datetime.timedelta(seconds=secs)
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True)
start = datetime.datetime.now()
while ( proc.poll() is None and (datetime.datetime.now() - start)
< timeout): #not timed out
print "hello,i'm here"
sleep(1)
if 0 == proc.poll():
stdout, stderr = proc.communicate() #get stdout and stderr
print("'%s' is program exited" %cmd)
print stdout
print stderr
else:
proc.terminate() #Can use proc.kill() as well
stdout, stderr = proc.communicate() #get stdout and stderr
print 'Timeout: Process terminated'
print stdout
print stderr
More information about the Tutor
mailing list