【发布时间】:2015-01-15 15:58:39
【问题描述】:
我正在编写一个带有各种 subprocess.call 的大型 python 脚本来执行系统中可用的命令,但我遇到了一个问题,因为如果将其打印到终端或重定向到文件,输出会有所不同。
为了重现问题,这是脚本的一小部分:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import call
print "Hello at first"
call(["rsync", "-aHvz", "root@server1:/tmp/a", '.'])
print "Hello at the end"
从终端执行它以正确的顺序返回,print + rsync + print:
$ python keepconf.py
Hello at the first
receiving incremental file list
sent 12 bytes received 123 bytes 270.00 bytes/sec
total size is 55858143 speedup is 413764.02
Hello at the end
执行相同的操作,但将输出重定向到文件:
$ python keepconf.py > /tmp/output
$ cat /tmp/output
receiving incremental file list
sent 12 bytes received 123 bytes 270.00 bytes/sec
total size is 55858143 speedup is 413764.02
Hello at the first
Hello at the end
现在的顺序是 rsync + print + print。为什么会出现这种行为?
【问题讨论】:
-
在打印后使用 sys.stdout.flush() ?