python程序輸出無(wú)內(nèi)容的解決方式
問(wèn)題緣由
某項(xiàng)目中使用python腳本方式將日志文件中的數(shù)據(jù)持續(xù)的轉(zhuǎn)換格式輸出到另一文件中以供其他日志分析應(yīng)用使用。但是當(dāng)后臺(tái)運(yùn)行采取重定向方式輸出到某一文件時(shí),發(fā)現(xiàn)并沒(méi)有內(nèi)容輸出,命令如下:
python xxx.py > xxx.log &
測(cè)試發(fā)現(xiàn),當(dāng)前臺(tái)直接輸出到終端時(shí)正常,使用后臺(tái)運(yùn)行重定向的方式輸出到文件中時(shí)無(wú)法輸出。
解決辦法
發(fā)現(xiàn)是在程序運(yùn)行時(shí),輸出有緩存,只有當(dāng)程序運(yùn)行結(jié)束或者緩沖區(qū)滿后才會(huì)輸出。因?yàn)槌绦蚴且恢略谶\(yùn)行的所以不可能等待程序結(jié)束在輸出。并且要求是有實(shí)時(shí)性的所以等緩沖區(qū)滿輸出的方式也不可取。
所以采用在python運(yùn)行時(shí)加上-u參數(shù),如:
python -u xxx.py > xxx.log &
-u參數(shù)的意義是不使用緩沖的方式輸入輸出
詳細(xì)如下:
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.
補(bǔ)充知識(shí):python中運(yùn)行代碼時(shí)沒(méi)有報(bào)錯(cuò)但是也沒(méi)有輸出而且還有exit code 0的結(jié)束標(biāo)志
如下所示:
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
后來(lái)排查發(fā)現(xiàn)原來(lái)是解釋器的問(wèn)題
我之前使用的解釋器是pycharm提供的虛擬解釋器
#####如何查看解釋器
點(diǎn)file?>new projects

如果選擇的是2就是使用了pycharm提供的虛擬解釋器,又因?yàn)閜asswd.txt文件不是在虛擬環(huán)境中的所以就沒(méi)有輸出。
點(diǎn)擊3然后選擇你已經(jīng)下載好的解釋器即可。
以上這篇python程序輸出無(wú)內(nèi)容的解決方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解Android studio 動(dòng)態(tài)fragment的用法2. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題3. Android如何加載Base64編碼格式圖片4. 圖文詳解vue中proto文件的函數(shù)調(diào)用5. 基于android studio的layout的xml文件的創(chuàng)建方式6. 什么是python的自省7. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)8. Vuex localStorage的具體使用9. 使用Android studio查看Kotlin的字節(jié)碼教程10. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備