我有一个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)
所以,实际上我并没有得到我系统上所有软件的详细信息。那么我该怎么做才能消除脚本中的这个错误呢。请帮忙。你知道吗
直接的问题是python2在重定向
sys.stdout
时使用ascii
编码(sys.getdefaultencoding()
)。您可以用PYTHONIOENCODING
envvar覆盖它:在*nix系统上就足够了,但是Windows可能会干扰在} is broken for binary content in PowerShell )之间传递字节。你知道吗
install.py
和文件(例如the pipe ^{为了解决这个问题,您可以将文件名作为命令行参数传递给
install.py
,然后写入文件而不是打印到sys.stdout
。你知道吗正确的解决方案是将必要的功能放入函数和import the module instead of running it as a subprocess。如果希望在另一个进程中作为shown in the link运行代码,可以使用
multiprocessing
。你知道吗相关问题 更多 >
编程相关推荐