Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Script fails with Python 3.x when py-lxml installed #28

Open
freultwah opened this issue Dec 2, 2020 · 4 comments
Open

Script fails with Python 3.x when py-lxml installed #28

freultwah opened this issue Dec 2, 2020 · 4 comments

Comments

@freultwah
Copy link

I stumbled upon a Python 2 to Python 3 conversion issue when trying to run the script with py-lxml installed.

# ./airprint-generate.py
Traceback (most recent call last):
  File "/root/./airprint-generate.py", line 279, in <module>
    apg.generate()
  File "/root/./airprint-generate.py", line 226, in generate
    tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8")
  File "src/lxml/etree.pyx", line 2057, in lxml.etree._ElementTree.write
  File "src/lxml/serializer.pxi", line 758, in lxml.etree._tofilelike
  File "src/lxml/etree.pyx", line 318, in lxml.etree._ExceptionContext._raise_if_stored
  File "src/lxml/serializer.pxi", line 682, in lxml.etree._FilelikeWriter.write
TypeError: write() argument must be str, not bytes

I fixed it by opening the file as binary:

--- airprint-generate.py.us.bak 2020-12-02 14:00:09.404088000 +0200
+++ airprint-generate.py        2020-12-02 14:05:06.222074000 +0200
@@ -220,7 +220,7 @@
                 if self.directory:
                     fname = os.path.join(self.directory, fname)
                 
-                f = open(fname, 'w')
+                f = open(fname, 'wb')
 
                 if etree:
                     tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8")

I could see no adverse effects when py-lxml was not installed.

@abbsi
Copy link

abbsi commented Dec 20, 2020

Same issue, and the fix above resolved it. Thanks!

@jhayashi
Copy link

Ditto. Thanks!

@undrwater
Copy link

Same here. Is there any reason not to make this change globally? IOW, will it break something?

nolltre added a commit to nolltre/airprint-generate that referenced this issue Jan 19, 2021
Fix the etree in python lxml wanting to have the file opened in the 'wb'
mode. Fixes the 'TypeError: write() argument must be str, not bytes'
error message but retains compatibility if lxml would be missing. Closes
issues tjfontaine#26 and tjfontaine#28
@gearfox
Copy link

gearfox commented Dec 9, 2022

pip3 uninstall lxml
./airprint-generate.py -d /etc/avahi/services/
ls /etc/avahi/services/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants