Porting Py2 to Py3 and http.client.HTTPMessage

Hi, Got a problem porting code.

Seems that StringIO in Python3 have no ‘clone’.
In this example I only show the fault I get when I use StringIO.

When I look into /usr/lib64/python3.9/io.py I see that a lot of stuff is imported from _io.
My guess is that ‘_io’ is c-lib but I can’t find that lib (libio.so) so I can not verify it the function ‘clone’ exist or not…?

Following code works in Python2 but not in Python3?

import http.client
from io import StringIO
    
if __name__ == '__main__':
   res=http.client.HTTPMessage(StringIO(u"headers"))
   print(str(res))

[]$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print(str(res))
  File "/usr/lib64/python3.9/email/message.py", line 135, in __str__
    return self.as_string()
  File "/usr/lib64/python3.9/email/message.py", line 158, in as_string
    g.flatten(self, unixfrom=unixfrom)
  File "/usr/lib64/python3.9/email/generator.py", line 97, in flatten
    policy = policy.clone(max_line_length=self.maxheaderlen)
AttributeError: '_io.StringIO' object has no attribute 'clone'

Or,
Is there another way creating a http message from in may case raw text from a file.

Hi Phil,

I don’t think your code works in Python2 either.

[steve ~]$ python2.7 -c "import http.client"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named http.client


[steve ~]$ python2.7 -c "from io import StringIO; StringIO().clone()"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: '_io.StringIO' object has no attribute 'clone'

Hi!
What happens if you put following into a file ‘fault.py’

import http.client
from io import StringIO
    
if __name__ == '__main__':
   res=http.client.HTTPMessage(StringIO(u"headers"))
   print(str(res))

And run:
python2 fault.py

What happens is that I waste two minutes of my life telling you “Exactly
the same error occurs” wink

[steve ~]$ python2 -V
Python 2.7.17
[steve ~]$ python2 fault.txt 
Traceback (most recent call last):
  File "fault.txt", line 1, in <module>
    import http.client
ImportError: No module named http.client

What happens if you run that? Double check that you are running the
right file with the exact same contents. Run python2 -V to check the
version.

It may also help to run which python2 if you are on Linux or Apple
Mac, if you are on Windows I don’t know how you find out what the
path to the Python executable is on Windows.

There is no http.client in the Python 2 standard library, so whatever
you are running is either different from the code you have told us, or
is using a non-standard library:

https://docs.python.org/2.7/library/httplib.html

Quote: “The httplib module has been renamed to http.client in Python 3.”