我正在寫一個大的python腳本和各種subprocess.call來執行系統中可用的命令,並且我遇到了一個問題,因爲如果它輸出到終端或者是否被重定向到文件。Python腳本在終端和重定向到一個文件之間的輸出不同
爲了重現該問題,這是劇本的一小部分:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import call
print "Hello at first"
call(["rsync", "-aHvz", "[email protected]:/tmp/a", '.'])
print "Hello at the end"
從終端返回,在正確的順序,打印+ rsync的+打印執行它:
$ 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 + pri nt +打印。這是爲什麼?
並與sys.stdout.flush()後,您的打印? – 2015-01-15 16:03:07