如何在python脚本中处理UnicodeEncodeError?

2024-04-24 03:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,从中生成安装在我机器上的软件列表。此脚本的名称为'安装.py'-如下所示:

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"

现在我将这个脚本的输出写入输出.tex从另一个脚本执行它,比如说“output”_文件.py,如下所示:

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

所以当上面的部分被执行时,我确实得到了输出“输出.tex“但是伴随着错误:

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

所以,实际上我并没有得到我系统上所有软件的详细信息。那么我该怎么做才能消除脚本中的这个错误呢。请帮忙。你知道吗


Tags: inpy脚本机器noneoutput软件is
1条回答
网友
1楼 · 发布于 2024-04-24 03:57:26

直接的问题是python2在重定向sys.stdout时使用ascii编码(sys.getdefaultencoding())。您可以用PYTHONIOENCODINGenvvar覆盖它:

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。你知道吗

相关问题 更多 >