python: change sys.stdout print to custom print function

后端 未结 3 1255
面向向阳花
面向向阳花 2020-12-31 19:45

Im trying to understand how to create a custom print function. (using python 2.7)

import sys
class CustomPrint():
    def __init__(self):
        self.old_s         


        
3条回答
  •  無奈伤痛
    2020-12-31 20:18

    It's not recursion. What happens is your write function is called twice, once with the text you expect, second time with just '\n'. Try this:

    import sys
    class CustomPrint():
        def __init__(self):
            self.old_stdout=sys.stdout
    
        def write(self, text):
            text = text.rstrip()
            if len(text) == 0: return
            self.old_stdout.write('custom Print--->' + text + '\n')
    
        def flush(self):
            self.old_stdout.flush()
    

    What I do in the above code is I add the new line character to the text passed in the first call, and make sure the second call made by the print statement, the one meant to print new line, doesn't print anything.

    Now try to comment out the first two lines and see what happens:

        def write(self, text):
            #text = text.rstrip()
            #if len(text) == 0: return
            self.old_stdout.write('custom Print--->' + text + '\n')
    

提交回复
热议问题