2015-12-21 43 views
0

我有一個python腳本,我正在生成安裝在我的機器上的軟件列表。讓這個腳本的名稱是「install.py」 - 它看起來如下:如何處理python腳本中的UnicodeEncodeError?

import wmi 
w = wmi.WMI() 
for p in w.Win32_Product(): 
    if (p.Version is not None) and (p.Caption is not None): 
     print p.Caption + " & "+ p.Version + "\\\\" 
     print "\hline" 

現在,我實際上是由一些執行它另一個腳本書面方式這個腳本的輸出到一個output.tex文件說「 output_file.py」,看起來如下:

with open("D:/output.tex", "w+") as output: 
    process = sp.call(["python", "D:/install.py"], stdout=output) 

因此,當上述件執行我得到輸出‘output.tex’但隨着誤差:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 43: 
ordinal not in range(128) 

所以,實際上唐沒有那麼詳細軟件在我的系統上。那麼我該怎麼做才能在腳本中刪除這個錯誤。請幫助。

+0

你可以嘗試在python腳本的開頭使用'from __future__ import unicode_literals'。或者您可以嘗試使用unicode編碼打開文件。請參閱https://docs.python.org/2/howto/unicode.html – Randrian

回答

0

當前的問題是,當重定向sys.stdout時,Python 2使用ascii編碼(sys.getdefaultencoding())。你可以用PYTHONIOENCODING ENVVAR覆蓋它:

call([sys.executable, os.path.join(script_dir, 'install.py')], stdout=file, 
    env=dict(os.environ, PYTHONIOENCODING='utf-8')) 

這將足以在* nix系統,但Windows可能與傳遞install.py和文件字節之間干擾(例如,the pipe | is broken for binary content in PowerShell)。

要解決這個問題,您可以將文件名作爲命令行參數傳遞給install.py,然後寫入文件而不是打印到sys.stdout那裏。

正確的解決方案是將必要的功能放入函數中,並且import the module instead of running it as a subprocess。如果您想以與shown in the link不同的進程運行代碼,則可以使用multiprocessing

相關問題