Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

printing - 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"

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 ' ' whilst HTTP requires ' '.

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("
", w);

Thus it appears there's no easy way to override the default newline behaviour of print. I have considered the following solutions

After writing the output simply do a .replace(' ', ' '). This will interfere with HTTP messages that use multipart encoding. Create a wrapper around the destination file object and proxy the .write method
def write(self, data):
    if data == '
':
        data = '
'
    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 ' ' or ' '.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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="
", file=sys.stdout):
    pass

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...