using subprocess for non-terminating command
kar1107 at gmail.com
Wed Jul 4 23:52:03 CEST 2007
On Jul 4, 4:38 am, Phoe6 <orsent... at gmail.com> wrote:
> Hi all,
> Consider this scenario, where in I need to use subprocess to execute a
> command like 'ping 127.0.0.1' which will have a continuous non-
> terminating output in Linux.
> # code
> >>>import subprocess
> >>>process = subprocess.Popen('ping 127.0.0.1', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> >>>print process.pid # returns pid
> >>>print process.poll() # returns None!!! this is strange.
It's expected behavior. It means the child process is still running.
> >>>print process.stdout.read()
> # This hangs at this point.
This too is expected behavior. 'ping <ip-addr>' runs forever
generating continuous output. It doesn't stop by itself.
read() reads until there is data available in the file object. Thus it
doesn't ever finish since the child never stops generating data.
If you do read(n), then it reads n bytes and returns.
> How should I handle these kind of commands (ping 127.0.0.1) with
> subprocess module. I am using subprocess, instead of os.system because
> at anypoint in time, I need access to stdout and stderr of execution.
Using subprocess is good. Just ensure your child stops data generation
at some point. For ping, you can use '-c <num>' or some other
application, you can try closing it's stdin (e.g. cat, bc, gdb)
More information about the Python-list