1

Folks....I have a script running in a Python program via a subprocess Popen command to create a pipe with the output from the script. It is working. However I thought I would have to use the .communicate() command to process records in the pipe from my program. I was not able to get that working, but did get it working with this code. What did I do wrong when I tried to use the .communicate command?

import subprocess
nul_f = open('/dev/null', 'w') 
try:
  tcpdmp = subprocess.Popen(['/usr/bin/sudo /usr/sbin/tcpdump -A -n -p -l -             i eth0 -s0 -w - tcp dst port 80'], 
                    stdout=subprocess.PIPE, shell=True,
                    stderr=nul_f,)
  print 'My Records'
  i=0
#  end_of_pipe = tcpdmp.communicate()
  while i<10:
    i=i+1
    line = tcpdmp.stdout.readline()
    print '\t --', i, line
except KeyboardInterrupt:
  print 'done'
tcpdmp.terminate()
tcpdmp.kill()
nul_f.close()

Thanks for any suggestions and critiques.....RDK

ps...Running Raspbian Linux on a Raspberry pi....

RDK
  • 355
  • 2
  • 7
  • 24

1 Answers1

1

.communicate() waits for the child process to end. tcpdump does not end peacefully that is why your code has except KeyboardInterrupt (to handle Ctrl+C).

Unrelated: you could replace the while loop with this:

from itertools import islice

for line in enumerate(islice(iter(tcpdump.stdout.readline, b''), 10), start=1):
    print '\t --', i, line, #NOTE: comma at the end to avoid double newlines

See also, Stop reading process output in Python without hang?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • JF....OK, thanks for the explanation, the reference and the alternate code....RDK – RDK Apr 04 '15 at 05:21