'Python script output fails: "... 'ascii' codec can't encode character .."

I am running one python script with 2 properties. It is being executed successfully on linux server. Python version is 2.7.18

python test.py arg1 arg2

If I try to put output to the file execution fails.

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)

Edited: Added problematic part of the code which processes XML file and write that part of the code in the output as well

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

What can be done so that output is saved to the file? Thank you!



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sai Prasad