python: change sys.stdout print to custom print function

后端 未结 3 1254
面向向阳花
面向向阳花 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')
    
    0 讨论(0)
  • 2020-12-31 20:20

    How about doing from __future__ import print_function. This way you will use Python3 print function instead of print statement from Python2. Then you can redefine the print function:

    def print(*args, **kwargs):
        __builtins__.print("Custom--->", *args, **kwargs)
    

    There is a catch however, you will have to start using print function.

    0 讨论(0)
  • 2020-12-31 20:34

    One solution may be to use a context manager if it's localised.

    #!/usr/bin/env python
    from __future__ import print_function
    
    from contextlib import contextmanager
    
    
    #############################
    @contextmanager
    def no_stdout():
        import sys
        old_stdout = sys.stdout
    
        class CustomPrint():
            def __init__(self, stdout):
                self.old_stdout = stdout
    
            def write(self, text):
                if len(text.rstrip()):
                    self.old_stdout.write('custom Print--->' + text)
    
        sys.stdout = CustomPrint(old_stdout)
    
        try:
            yield
        finally:
            sys.stdout = old_stdout
    
    
    #############################
    print("BEFORE")
    with no_stdout():
        print("WHY HELLO!\n")
        print("DING DONG!\n")
    
    print("AFTER")
    
    

    The above produces:

    BEFORE
    custom Print--->WHY HELLO!
    custom Print--->DING DONG!
    AFTER
    

    The code would need tidying up esp. around what the class should do WRT setting stdout back to what it was.

    0 讨论(0)
提交回复
热议问题