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

一、問題描述

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

$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)

 

二、方案探索

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

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

在代碼中加上以下幾句便可。ubuntu

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

http://docs.python.org/howto/unicode.html 這個是python的unicode編碼API文檔,英文好的同窗能夠看一下,加深理解。安全

 

三、解決方案

3.1 拷貝臨時數據到本地

根據上面錯誤提示,拷貝升級包代碼到本地,並修改權限爲本身能夠編輯app

$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命令讓其後臺執行:spa

$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 &

已經能夠正常升級了,以下:.net

相關文章
相關標籤/搜索