覆盖Python的print语句的换行生成行为 [英] Overriding the newline generation behaviour of Python's print statement
问题描述
我有一堆用于编码原始电子邮件的旧代码,其中包含许多打印语句,例如
I have a bunch of legacy code for encoding raw emails that contains a lot of print statements such as
print >>f, "Content-Type: text/plain"
对于电子邮件来说,这一切都很好,但是我们现在利用相同的代码来输出HTTP请求。问题是Python打印语句输出'\n'
,而HTTP要求'\r\n'
。
This is all well and good for emails, but we're now leveraging the same code for outputting HTTP request. The problem is that the Python print statement outputs '\n'
whilst HTTP requires '\r\n'
.
看起来Python(至少为2.6.4)会生成尾随 PRINT_NEWLINE
字节代码进行打印语句实现为
It looks like Python (2.6.4 at least) generates a trailing PRINT_NEWLINE
byte code for a print statement which is implemented as
ceval.c:1582: err = PyFile_WriteString("\n", w);
因此,似乎没有简单的方法可以覆盖默认的换行行为。我考虑过以下解决方案
Thus it appears there's no easy way to override the default newline behaviour of print. I have considered the following solutions
.replace('\n','\r \n')
。这会干扰使用分段编码的HTTP消息。 .write
方法.replace('\n', '\r\n')
. This will interfere with HTTP messages that use multipart encoding..write
methoddef write(self, data):
if data == '\n':
data = '\r\n'
return self._file.write(data)
print>> f,文本
转换为 f.write(text + line_end)
,其中 line_end
可以是'\n'
或' lir\n'
。print >>f, text
to f.write(text + line_end)
where line_end
can be '\n'
or '\r\n'
.我相信第三个选择最合适。听说您使用Python方式解决问题会很有趣。
I believe the third option would be the most appropriate. It would be interesting to hear what your Pythonic approach to the problem would be.
推荐答案
您应该现在就永远解决问题通过定义一个新的输出函数。如果打印了一个函数,那会容易得多。
You should solve your problem now and for forever by defining a new output function. Were print a function, this would have been much easier.
我建议编写一个新的输出函数,尽可能地模仿现代打印函数的签名(因为重用了良好的界面是好的),例如:
I suggest writing a new output function, mimicing as much of the modern print function signature as possible (because reusing a good interface is good), for example:
def output(*items, end="\n", file=sys.stdout):
pass
一旦您替换了所有有问题的打印件,就不再有这个问题-您可以随时更改函数的行为!这是在Python 3中将print设置为函数的一个重要原因-因为在Python 2.x中,所有项目总是经过所有 print
语句的阶段不再灵活,也没有简单的出路。
Once you have replaced all prints in question, you no longer have this problem -- you can always change the behavior of your function instead! This is a big reason why print was made a function in Python 3 -- because in Python 2.x, "all" projects invariably go through the stage where all the print
statements are no longer flexible, and there is no easy way out.
这篇关于覆盖Python的print语句的换行生成行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!