python程序輸出無內容的解決方式
問題緣由
某項目中使用python腳本方式將日志文件中的數據持續的轉換格式輸出到另一文件中以供其他日志分析應用使用。但是當后臺運行采取重定向方式輸出到某一文件時,發現并沒有內容輸出,命令如下:
python xxx.py > xxx.log &
測試發現,當前臺直接輸出到終端時正常,使用后臺運行重定向的方式輸出到文件中時無法輸出。
解決辦法
發現是在程序運行時,輸出有緩存,只有當程序運行結束或者緩沖區滿后才會輸出。因為程序是一致在運行的所以不可能等待程序結束在輸出。并且要求是有實時性的所以等緩沖區滿輸出的方式也不可取。
所以采用在python運行時加上-u參數,如:
python -u xxx.py > xxx.log &
-u參數的意義是不使用緩沖的方式輸入輸出
詳細如下:
Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators (“for line in sys.stdin”) which is not influenced by this option. To work around this, you will want to use “sys.stdin.readline()” inside a “while 1:” loop.
補充知識:python中運行代碼時沒有報錯但是也沒有輸出而且還有exit code 0的結束標志
如下所示:
f=open('passwd.txt',’r’)print (f.read(4))f.close()
這是想要執行的代碼
passwd.txt中的內容
ntp:x:38:38::/etc/ntp:/sbin/nologinapache:x:48:48:Apache:/var/www:/sbin/nologinsaslauth:x:498:76:Saslauthd user:/var/empty/saslauth:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologingdm:x:42:42::/var/lib/gdm:/sbin/nologinpulse:x:497:496:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
但是輸出的結果是
Process finished with exit code 0
后來排查發現原來是解釋器的問題
我之前使用的解釋器是pycharm提供的虛擬解釋器
#####如何查看解釋器
點file?>new projects
如果選擇的是2就是使用了pycharm提供的虛擬解釋器,又因為passwd.txt文件不是在虛擬環境中的所以就沒有輸出。
點擊3然后選擇你已經下載好的解釋器即可。
以上這篇python程序輸出無內容的解決方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
