2015-12-03 53 views
3

我想從Python腳本中連續輸出一些數據到另一個程序。作爲一個例子,我將使用cat,這就是目前發生的情況:連續向另一個程序輸出一個Python腳本輸出

如果我test1.py腳本是這樣的:

print("Hello!") 
當我運行 ./test1.py | cat輸出爲 Hello!,它的工作原理是因爲劇本後立即終止

執行。

import time 

a = 0 
while True: 
    a += 1 
    print(a) 
    time.sleep(1) 

然後./test2.py | cat只是掛在那兒,因爲腳本不終止:

的問題時,我有連續寫了一個腳本,永遠不會終止像test2.py發生。

我想每秒發一個數字到cat並實時顯示它,這有可能嗎?

回答

2

設置flush=True在打印,您的輸出得到緩衝,有一個很好的條每頁Unix buffering delays output to stdout, ruins your day解釋是怎麼回事:

import time 

a = 0 
while True: 
    a += 1 
    print(a, flush=True) 
    time.sleep(1) 

如果您正在使用python2添加from __future__ import print_function

+0

這個固定我的問題,我將這個標記爲正確的答案,因爲它不需要直接使用sys.stdout,所以瞭解新的Python3特性也很好。 –

+1

@dan_s,別擔心,我添加了一篇文章的鏈接,給出了一個很好的解釋 –

0

./test2.py |尾-f

-f,--follow [= {名稱|描述符}]

 output appended data as the file grows; -f, --follow, and --follow=descriptor are equivalent 
1

需要印刷之後刷新到標準輸出。所以你的代碼將如下所示:

import sys 
import time 

a = 0 
while True: 
    a += 1 
    print(a) 
    time.sleep(1) 
    sys.stdout.flush() 

現在運行python script.py | cat將打印一個。

相關問題