Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElementTree write function does not write to standard out

I'm trying to output an XML structure to stdout with ElementTree. I'm trying with:

root = ET.Element('networkData')    
tree = ET.ElementTree(root)
tree.write(sys.stdout)

but I get no output. Changing the argument to a string produces an XML file as expected. Using the debugger (adding encoding tip from SO) I get:

-> tree.write(sys.stdout, encoding='utf-8')
(Pdb) n
TypeError: write() argument must be str, not bytes

Googling the error I get a few hits but none that seems to address this issue. Also, I get confused by the error message as sys.stdout is a _io.TextIOWrapper object.

like image 646
Bengt62 Avatar asked Aug 10 '26 09:08

Bengt62


1 Answers

The problem has to do with encoding. Without correct encoding, the argument is treated as binary and not as string, which explains the error message. The proper write-statement should be:

tree.write(sys.stdout, encoding='unicode')

or

tree.write(sys.stdout.buffer)

as pointed out in the comments.

like image 108
Bengt62 Avatar answered Aug 11 '26 23:08

Bengt62