I want to do something similar to the second answer here (but not quite similar): Simulate Ctrl-C keyboard interrupt in Python while working in Linux
It's much simpler and I think I'm just missing something. Say, from a python script, I just want to call 'ping' and terminate it after the 10th time. I'm trying to do it like from the link above:
p = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE)
for line in p.stdout:
print line
if re.search('10', line):
break
os.kill(p.pid, signal.SIGINT)
But it doesn't work.
And I also want the regular output of 'ping' to be displayed. How do I do this?
EDIT: It's not actually a 'ping' that I want to do. I'm just using it as an example of a command with continuous output, which in time, I would like to terminate.
More specifically, I'm running an old version of BitTorrent (v5.0.9 from the 3rd answer here: Where to find BitTorrent source code?) and I'm calling it via python script. The bittorrent-console.py is a simple terminal version, hence 'console'. It outputs multiple lines periodically. Something like:
saving: filename
file size: blah
percent done: 100.0
blah: blahblah
I'm actually calling it by:
subprocess.call(['./bittorrent-console.py', 'something.torrent'])
I want to terminate it automatically when I see it's 100.0 in 'percent done:'.
EDIT: I'm running on CentOS, Python 2.6.
10might be part of the IP addressif re.search('icmp_seq=10'.subprocess.Popenandsubprocess.calldiffer in one very important detail. The former is asynchronous, the latter is syncrhonous. In the latter case, by the time you callos.kill(), the app is already dead andos.kill()has no effect whatsoever.callthough, because there's no lag in output like when I tried the answer below. It simply has just called bittorrent-console and left it running. I don't know how to terminate it when the download's done except by Keyboard Interrupt.call, there's a way to get the process id of what I just called?