IT科技

當前位置 /首頁/IT科技 > /列表

python代碼沒錯但運行不出來

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然後選擇你已經下載好的解釋器即可。

TAG標籤:Python 代碼 運行 #