[Tutor] why "ifconfig" is alway running?

lei yang yanglei.fage at gmail.com
Mon Dec 20 14:38:30 CET 2010


On Sun, Dec 19, 2010 at 9:05 PM, Sander Sweers <sander.sweers at gmail.com> wrote:
> 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

my python verison is 2.5, so has no kill or terminate attribute, so I still use
os.kill(proc.pid, signal.SIGINT) instead

>        stdout, stderr = proc.communicate() #get stdout and stderr


 and I find it will get stuck here

>        print 'Timeout: Process terminated'
>        print stdout
>        print stderr
>


More information about the Tutor mailing list