Python subprocess reading

2019-04-14 00:44发布

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?

2条回答
狗以群分
2楼-- · 2019-04-14 01:15

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.

查看更多
唯我独甜
3楼-- · 2019-04-14 01:19

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.

查看更多
登录 后发表回答