Python 脚本输出失败:"... 'ascii'编解码器无法编码字符..”
我正在运行一个具有 2 个属性的 python 脚本。已在linux服务器上成功执行。 Python 版本是 2.7.18
python test.py arg1 arg2
如果我尝试将输出放入文件执行失败。
python test.py arg1 arg2 > output.txt
Traceback (most recent call last):
File "test2.py", line 462, in <module>
main()
File "test.py", line 457, in main
git_migrate(logfile, args[0], args[1], args[2], depot)
File "test.py", line 397, in git_migrate
print ('#### transaction[0].text ####:'+transaction[0].text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 127: ordinal not in range(128)
编辑:添加了处理 XML 文件的代码的有问题的部分,并将该部分代码也写入输出中
logfile='/tmp/tmp.xml'
print ('entered git_migrate ')
tree = ElemTree.parse(logfile)
root = tree.getroot()
transactions = []
print ('prepare to enter root loop')
for transaction in root.iter('transaction'):
if transaction[0].text:
print ('#### transaction[0].text ####:'+str(transaction[0].text))
print (' transaction.id:'+transaction.attrib['id'])
print (' transaction.user:'+transaction.attrib['user'])
print (' transaction.time:'+transaction.attrib['time'])
transactions.append(
[transaction.attrib['id'], transaction[0].text, transaction.attrib['user'], transaction.attrib['time']])
else:
print (" NO transaction comment or text!!!!! Nothing will be added to the list ")
可以做什么,以便将输出保存到文件中? 谢谢你!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看错误,似乎您正在尝试将 Unicode 字符转换为 Ascii 字符。您是否尝试使用 utf-8 编码写入文件或转义 unicode 字符。
此外,如果没有源代码,就不可能提供更多的输入。
Looking at the error, seems like you are trying to convert a Unicode character to an Ascii character. Did you try writing to file with utf-8 encoding or escape the unicode character.
Also without source code it would not be possible to give any more inputs.