I have a bunch of legacy code to encode raw emails containing many print statements such as
print >>f, "Content-Type: text/plain"
This is good and useful for emails, but now we use the same code to output the HTTP request. The problem is that the Python print statement prints '\n' , while HTTP requires '\r\n' .
It looks like Python (at least 2.6.4) generates the final byte code PRINT_NEWLINE for the print statement, which is implemented as
ceval.c:1582: err = PyFile_WriteString("\n", w);
Thus, there is no easy way to override the default print behavior for a new line. I reviewed the following solutions
After recording the output, simply do
.replace('\n', '\r\n') . This will interfere with HTTP messages using multiple encoding. Create a wrapper around the target file object and the
.write def write(self, data): if data == '\n': data = '\r\n' return self._file.write(data)
Write a regular expression that translates
print >>f, text to
f.write(text + line_end) , where
line_end can be
'\n' or
'\r\n' .
I believe that the third option will be the most suitable. It would be interesting to hear what your approach to the Python problem will be.
python cpython printing
brotchie
source share