解決python3中os.popen()出錯的問題
使用程序難免會有出錯的時候,如何從大篇代碼中找出錯誤,不僅考驗能力,還要考驗小伙們的耐心。辛辛苦苦敲出的代碼運行不出結果,非常著急是可以理解的。那么我們在python3中使用os.popen()出錯該怎么辦?本篇文章小編同樣以錯誤的操作方法為大家進行講解,一起找尋不對的地方吧。
在當前 desktop 目錄下,有如下內(nèi)容:
desktop $ls client.py server.py 中文測試 arcpy.txt codetest.py test.py
如上所示:有一個中文命名的文件 ----> 中文測試
# -*- coding:utf-8 -*- # python3.5.1 import os,sys print (sys.getdefaultencoding()) #系統(tǒng)默認編碼 dir_list = os.listdir() for li in dir_list: print (li)
輸出如下:
utf-8 arcpy.txt client.py codetest.py server.py test.py 中文測試
可以看出默認編碼為 utf-8,os.listdir()命令可以正常輸出中文字符。
在使用 os.popen()時:
# -*- coding:utf-8 -*-
# python3.5.1
import os,sys
print (sys.getdefaultencoding()) #系統(tǒng)默認編碼
dir_list = os.popen('ls','r').read()
for li in dir_list:
print (li)
報錯如下:
utf-8
Traceback (most recent call last):
File "Desktop/codetest.py", line 8, in <module>
dir_list = os.popen('ls','r').read()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 76: ordinal not in range(128)
解決:
命令行執(zhí)行沒有問題,這個是編輯器的事。建議用subprocess

到此這篇關于解決python3中os.popen()出錯的問題的文章就介紹到這了,更多相關python3中os.popen()使用出錯怎么辦內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- python基礎教程之popen函數(shù)操作其它程序的輸入和輸出示例
- Python?subprocess.Popen?實時輸出?stdout的解決方法(正確管道寫法)
- Python調(diào)用系統(tǒng)命令的四種方法詳解(os.system、os.popen、commands、subprocess)
- Python調(diào)用系統(tǒng)命令os.system()和os.popen()的實現(xiàn)
- python中的subprocess.Popen()使用詳解
- 對Python subprocess.Popen子進程管道阻塞詳解
- Python中的Popen函數(shù)demo演示
相關文章
Python實現(xiàn)報警信息實時發(fā)送至郵箱功能(實例代碼)
這篇文章主要介紹了Python實現(xiàn)報警信息實時發(fā)送至郵箱,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11
使用Nginx+uWsgi實現(xiàn)Python的Django框架站點動靜分離
這篇文章主要介紹了使用Nginx+uWsgi實現(xiàn)Python的Django框架站點動靜分離的部署實例,即靜態(tài)由Nginx處理而Python頁面由Django自帶的HTTP服務器處理,需要的朋友可以參考下2016-03-03

