【Python】【解決】UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1: ordinal not in range(128)


1、問題描述

今天在升級Ubuntu到14.04,使用命令行啟動軟件更新器,進行版本升級,結果開始升級就異常退出了,具體打印如下:

$update-manager -d
正在檢查新版 Ubuntu
使用 'trusty.tar.gz.gpg''trusty.tar.gz' 進行驗證 
正在提取 'trusty.tar.gz'
Traceback (most recent call last):
  File "/tmp/ubuntu-release-upgrader-r_0oij/trusty", line 10, in <module>
    sys.exit(main())
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/DistUpgradeMain.py", line 243, in main
    if app.run():
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/DistUpgradeController.py", line 1826, in run
    return self.fullUpgrade()
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/DistUpgradeController.py", line 1717, in fullUpgrade
    if not self.updateSourcesList():
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/DistUpgradeController.py", line 760, in updateSourcesList
    if not self.rewriteSourcesList(mirror_check=True):
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/DistUpgradeController.py", line 736, in rewriteSourcesList
    logging.debug("entry '%s' was disabled (unknown mirror)" % get_string_with_no_auth_from_source_entry(entry))
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/utils.py", line 89, in get_string_with_no_auth_from_source_entry
    return str(tmp)
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/sourceslist.py", line 232, in __str__
    return self.str().strip()
  File "/tmp/ubuntu-release-upgrader-r_0oij/DistUpgrade/sourceslist.py", line 256, in str
    line += u" #%s" % self.comment
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1: ordinal not in range(128)

 

2、方案探索

主要錯誤是上面最后一行的Unicode解碼問題,網上搜索說是讀取文件時使用的編碼默認時ascii而不是utf8,導致的錯誤;原始資料路徑為:

http://blog.csdn.net/vincent_czz/article/details/7719012

在代碼中加上如下幾句即可。

import sys
reload(sys)
sys.setdefaultencoding('utf8')

http://docs.python.org/howto/unicode.html 這個是python的unicode編碼API文檔,英文好的同學可以看一下,加深理解。

 

3、解決方案

3.1 拷貝臨時數據到本地

根據上面錯誤提示,拷貝升級包代碼到本地,並修改權限為自己可以編輯

$sudo cp -R /tmp/ubuntu-release-upgrader-r_0oij ./upgrade
$sudo chown qunengrong:qunengrong upgrade/ -R

3.2 修正讀取文件的代碼

打開上面報錯的文件,如DistUpgradeMain.py,進行編輯並保存;

## 原來為下面行
#import sys
## 改為下面的3行
import sys
reload(sys)
sys.setdefaultencoding('utf8')

 

3.3 手動啟動升級

為了安全和防止升級過程被打斷,建議提交到后台執行,如使用nohup,輸入密碼后按CTRL+Z終端,然后輸入bg命令讓其后台執行:

$nohup sudo ./trusty 
nohup: 忽略輸入並把輸出追加到"nohup.out"
[sudo] password for qunengrong: 

^Z
[1]+  已停止               nohup sudo ./trusty
qunengrong@qunengrong-Studio-1450 ~/tests/apt/upgrade
$bg
[1]+ nohup sudo ./trusty &

已經可以正常升級了,如下:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM