新聞中心
使用程序難免會(huì)有出錯(cuò)的時(shí)候,如何從大篇代碼中找出錯(cuò)誤,不僅考驗(yàn)?zāi)芰?,還要考驗(yàn)小伙們的耐心。辛辛苦苦敲出的代碼運(yùn)行不出結(jié)果,非常著急是可以理解的。那么我們在python3中使用os.popen()出錯(cuò)該怎么辦?本篇文章小編同樣以錯(cuò)誤的操作方法為大家進(jìn)行講解,一起找尋不對(duì)的地方吧。

成都創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站制作、網(wǎng)站設(shè)計(jì)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的信宜網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
在當(dāng)前 desktop 目錄下,有如下內(nèi)容:
desktop $ls client.py server.py 中文測試 arcpy.txt codetest.py test.py
如上所示:有一個(gè)中文命名的文件 ----> 中文測試
# -*- coding:utf-8 -*- # python3.5.1 import os,sys print (sys.getdefaultencoding()) #系統(tǒng)默認(rèn)編碼 dir_list = os.listdir() for li in dir_list: print (li)
輸出如下:
utf-8 arcpy.txt client.py codetest.py server.py test.py 中文測試
可以看出默認(rèn)編碼為 utf-8,os.listdir()命令可以正常輸出中文字符。
在使用 os.popen()時(shí):
# -*- coding:utf-8 -*-
# python3.5.1
import os,sys
print (sys.getdefaultencoding()) #系統(tǒng)默認(rèn)編碼
dir_list = os.popen('ls','r').read()
for li in dir_list:
print (li)報(bào)錯(cuò)如下:
utf-8 Traceback (most recent call last): File "Desktop/codetest.py", line 8, indir_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í)行沒有問題,這個(gè)是編輯器的事。建議用subprocess
對(duì)于這個(gè)解決方法,有的小伙伴們覺得太簡單了,但是我們找尋方法的過程是困難的,學(xué)會(huì)的趕緊保存吧。更多Python學(xué)習(xí)推薦:PyThon學(xué)習(xí)網(wǎng)教學(xué)中心。
名稱欄目:創(chuàng)新互聯(lián)Python教程:python3中os.popen()使用出錯(cuò)怎么辦?
轉(zhuǎn)載來源:http://fisionsoft.com.cn/article/cdjccis.html


咨詢
建站咨詢
