Python subprocess reading

2019-04-14 01:29发布

问题:

Having this code

p = subprocess.Popen('tail -f /var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in p.stdout.readlines():
    print line,
    time.sleep(1)

The script hangs and does not write any lines even if I add something to syslog.

Why?

回答1:

readlines() will not return until there is an eof on the process, which there won't be as tail never finishes without an interrupt.

You could change your loop to:

while True:
    print(p.stdout.readline())

Unless you want an additional 1s gap between each line., there is no need for a sleep as readline will block, using minimal resources, until there is a full line available.



回答2:

You could also emulate tail -f directly in python.

Check this: tail -f in Python (Python recipe)

Or this: Emulate the "tail -f" command or Google for more examples.