using subprocess for non-terminating command

Jerry Hill malaclypse2 at gmail.com
Wed Jul 4 11:23:33 EDT 2007


On 7/4/07, O.R.Senthil Kumaran <orsenthil at users.sourceforge.net> wrote:
> Yes, I am aware of the ping -c option. But again even that does not help.
> try
> process = subprocess.Popen('ping -c 10 127.0.0.1', stdin=subprocess.PIPE,
> shell=True)
> process.stdout.read()  # This will hang again.

When I try that, it doesn't hang.  Instead, I get the output of the
ping command pruinted to the screen, then the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'read'

That's because you tied stdin to a pipe in your Popen call, but then
tried to read from stdout.  Try this instead:

>>> process = subprocess.Popen("ping -c 10 127.0.0.1",
stdout=subprocess.PIPE, shell=True)
>>> process.stdout.readlines()
['PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.\n', '64 bytes from
127.0.0.1: icmp_seq=1 ttl=64 time=0.049 ms\n', '64 bytes from
127.0.0.1: icmp_seq=2 ttl=64 time=0.033 ms\n', '64 bytes from
127.0.0.1: icmp_seq=3 ttl=64 time=0.040 ms\n', '64 bytes from
127.0.0.1: icmp_seq=4 ttl=64 time=0.033 ms\n', '64 bytes from
127.0.0.1: icmp_seq=5 ttl=64 time=0.033 ms\n', '64 bytes from
127.0.0.1: icmp_seq=6 ttl=64 time=0.030 ms\n', '64 bytes from
127.0.0.1: icmp_seq=7 ttl=64 time=0.032 ms\n', '64 bytes from
127.0.0.1: icmp_seq=8 ttl=64 time=0.028 ms\n', '64 bytes from
127.0.0.1: icmp_seq=9 ttl=64 time=0.030 ms\n', '64 bytes from
127.0.0.1: icmp_seq=10 ttl=64 time=0.039 ms\n', '\n', '--- 127.0.0.1
ping statistics ---\n', '10 packets transmitted, 10 received, 0%
packet loss, time 8991ms\n', 'rtt min/avg/max/mdev =
0.028/0.034/0.049/0.009 ms\n']

-- 
Jerry



More information about the Python-list mailing list