[Tutor] popen()ed file object hangs on close() -- why?
Evgeny Roubinchtein
eroubinc@u.washington.edu
Wed, 28 Jul 1999 20:34:11 -0700 (PDT)
So, I have written a very simple script to filter the output of a command.
Right now it is just the ping command, but I think I can add more. The
problem is the script hangs. I realize that the ping command is
still writing data when I try to close the pipe. If I knew it's PID, I
could try killing it, but I how do I get its PID? (short of an
equivalent of 'ps ax | grep ping' ) Here is the script:
It hangs under both Linux and FreeBSD, in case that matters.
I know I am doing sthg stupid, I just wish I knew what...
Any help is greatly appreciated
---%<-----
#! /usr/local/bin/python
import re, os, string, sys
ping = '/bin/ping'
host = '127.0.0.1'
ping_re = r'\s+time=(?P<numbers>\d+\.\d*)\s+ms'
class CommandPipe:
def __init__(self, command, command_options, command_args, regexp):
self.prog = string.join((command, command_options, command_args), ' ')
self.re_obj = re.compile(regexp)
self.line = ''
def run(self):
command_pipe = os.popen(self.prog)
maxcount = 5 # this can be adjusted
for i in range(maxcount):
line = command_pipe.readline()
if not line:
break
line = string.strip(line)
m = self.re_obj.search(line)
if m:
for group in m.groups():
print group,
print # a blank line
sys.stdout.flush()
command_pipe.close() # the script hangs here
return
class PingPipe(CommandPipe):
def __init__(self, command=ping, command_options='', command_args=host,
regexp=ping_re):
CommandPipe.__init__(self, command, command_options, command_args,
regexp)
def test():
p = PingPipe()
p.run()
if __name__=='__main__':
test()
sys.exit(0)
--
Evgeny Roubinchtein, eroubinc@u.washington.edu
...................
SDD: Scratch Disk and Die