網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

python代碼沒錯但執行不出來

欄目: IT科技 / 發佈於: / 人氣:1.99W

1、python代碼沒錯但執行不出來的原因:

某項目中使用python腳本方式將日誌檔案中的數據持續的轉換格式輸出到另一檔案中以供其他日誌分析應用使用。但是當後臺執行採取重定向方式輸出到某一檔案時,發現並沒有內容輸出,命令如下:

python xxx.py > xxx.log &

測試發現,當前臺直接輸出到終端時正常,使用後臺執行重定向的方式輸出到檔案中時無法輸出。

python代碼沒錯但執行不出來

2、解決辦法:

發現是在程序執行時,輸出有快取,只有當程序執行結束或者緩衝區滿後纔會輸出。因爲程序是一致在執行的所以不可能等待程序結束在輸出。並且要求是有實時性的所以等緩衝區滿輸出的方式也不可取。

所以採用在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/nologin

apache:x:48:48:Apache:/var/www:/sbin/nologin

saslauth:x:498:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin

postfix:x:89:89::/var/spool/postfix:/sbin/nologin

gdm:x:42:42::/var/lib/gdm:/sbin/nologin

pulse:x:497:496:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin

但是輸出的結果是

Process finished with exit code 0

後來排查發現原來是解釋器的問題

我之前使用的解釋器是pycharm提供的虛擬解釋器

#####如何檢視解釋器

點file?C>new projects

python代碼沒錯但執行不出來 第2張

如果選擇的是2就是使用了pycharm提供的虛擬解釋器,又因爲passwd.txt檔案不是在虛擬環境中的所以就沒有輸出。

點擊3然後選擇你已經下載好的解釋器即可。