python程序輸出無內(nèi)容的解決方式
問題緣由
某項目中使用python腳本方式將日志文件中的數(shù)據(jù)持續(xù)的轉(zhuǎn)換格式輸出到另一文件中以供其他日志分析應(yīng)用使用。但是當后臺運行采取重定向方式輸出到某一文件時,發(fā)現(xiàn)并沒有內(nèi)容輸出,命令如下:
python xxx.py > xxx.log &
測試發(fā)現(xiàn),當前臺直接輸出到終端時正常,使用后臺運行重定向的方式輸出到文件中時無法輸出。
解決辦法
發(fā)現(xiàn)是在程序運行時,輸出有緩存,只有當程序運行結(jié)束或者緩沖區(qū)滿后才會輸出。因為程序是一致在運行的所以不可能等待程序結(jié)束在輸出。并且要求是有實時性的所以等緩沖區(qū)滿輸出的方式也不可取。
所以采用在python運行時加上-u參數(shù),如:
python -u xxx.py > xxx.log &
-u參數(shù)的意義是不使用緩沖的方式輸入輸出
詳細如下:
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的結(jié)束標志
如下所示:
f=open('passwd.txt',’r’)print (f.read(4))f.close()
這是想要執(zhí)行的代碼
passwd.txt中的內(nèi)容
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
但是輸出的結(jié)果是
Process finished with exit code 0
后來排查發(fā)現(xiàn)原來是解釋器的問題
我之前使用的解釋器是pycharm提供的虛擬解釋器
#####如何查看解釋器
點file?>new projects
如果選擇的是2就是使用了pycharm提供的虛擬解釋器,又因為passwd.txt文件不是在虛擬環(huán)境中的所以就沒有輸出。
點擊3然后選擇你已經(jīng)下載好的解釋器即可。
以上這篇python程序輸出無內(nèi)容的解決方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析2. ASP中常用的22個FSO文件操作函數(shù)整理3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. ASP的Global.asa文件技巧用法5. php測試程序運行速度和頁面執(zhí)行速度的代碼6. html清除浮動的6種方法示例7. SharePoint Server 2019新特性介紹8. ASP中if語句、select 、while循環(huán)的使用方法9. React+umi+typeScript創(chuàng)建項目的過程10. Vue+elementUI下拉框自定義顏色選擇器方式
