Python terminal output

I want to do something similar to the second answer here (but not quite similar): Simulate a Ctrl-C keyboard interrupt in Python while working on Linux

This is much simpler, and I think I just missed something. Let's say from a python script I just want to call "ping" and terminate it after the 10th time. I am trying to do this as in 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 that will not work.

And I also want regular ping output to be displayed. How can I do it?

EDIT: This is actually not the "ping" I want to do. I just use it as an example of a continuous exit command, which I would like to complete over time.

In particular, I am launching an old version of BitTorrent (v5.0.9 from the 3rd answer here: Where can I find the source code of BitTorrent? ) M calls it through a python script. Bittorrent-console.py is a simple terminal version, so it’s a “console”. It periodically displays several lines. Sort of:

saving:       filename
file size:    blah
percent done: 100.0
blah:         blahblah

I actually call it:

subprocess.call(['./bittorrent-console.py', 'something.torrent'])

I want to finish it automatically when I see 100.0 in percent.

EDIT: I am running CentOS, Python 2.6.

+4
source share
2 answers

First, you want to use p.stdout.readline. I'm not sure why, but for line in p.stdoutit doesn't seem to be a flash. Perhaps he is buffered.

-, sys.stdout.write(line), print -. Python 3 print(line, end=""), .

, p.kill os.kill. , os.kill.

import os
import signal
import subprocess
import sys

p = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE)
while True:
    line = p.stdout.readline()

    sys.stdout.write(line)
    sys.stdout.flush()
    if '10' in line:
        break

p.kill()
+1

, , OS X:

import subprocess
import re

def get_output(cmd, until):
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    ret = []
    while True:
        line = p.stdout.readline()
        ret.append(line)
        if re.search(until, line):
            break
    p.kill()
    return ret

 print ''.join(get_output(['ping', 'google.com'], until='10'))
+2

All Articles