【问题标题】:Is there a way to override the print method in Python 3.x?有没有办法覆盖 Python 3.x 中的 print 方法?
【发布时间】:2020-09-15 10:39:18
【问题描述】:

非常简单的问题 - 我已搜索但未找到此问题的答案。

这样做可能有点傻,但我很好奇是否可以挂钩到 python 3.X 的 print(*arg, **kwarg) 函数并覆盖它/在调用结束时添加 time.sleep(var)

当然,我可以定义另一种方法并用 time.sleep(var) 包装它,但我只是好奇如何覆盖预构建的函数。

【问题讨论】:

  • orig_print = print; print = new_function 应该可以工作。但我几乎不认为这是推荐的。你最好问问自己为什么你需要做这样的事情。
  • edit您的问题明确说明您需要什么。您想在函数、代码块、模块还是整个应用程序中覆盖print

标签: python python-3.x methods python-object


【解决方案1】:

如果您想全局修补任何功能,例如出于测试/调试目的,最安全的方法是使用unittest.mock.patch():

def x():
    '''the code under test'''
    print('Hello, world!')

...
from unittest.mock import patch
orig_print = print

with patch('builtins.print') as m:
    def my_print(*args, **kwargs):
        orig_print('PATCHED:', *args, **kwargs)

    m.side_effect = my_print

    x()  # prints 'PATCHED: Hello, world!'

# prints 'Hello, world!', because the patch context is exited
# and the original function is restored: 
x() 

【讨论】:

    【解决方案2】:

    你也可以试试这一款

    out = print
    print = lambda *args, **kwargs: [time.sleep(1), out(*args, **kwargs)]
    

    【讨论】:

      【解决方案3】:

      你可以,你可以这样做:

      def new_print(*args, **kwargs):
          # Your new print function here
          pass
      
      print = new_print
      

      建议您保存旧的打印功能,如果您想在打印功能中使用它,您将需要它。 你可以这样做

      old_print = print
      def new_print(*args, **kwargs):
          old_print(*args, **kwargs)
      
      print = new_print
      

      如果你现在想在其中添加睡眠,只需将其放入新函数中即可

      import time
      
      old_print = print
      def new_print(*args, **kwargs):
          old_print(*args, **kwargs)
          time.sleep(5)
      
      print = new_print
      

      【讨论】:

        【解决方案4】:

        只是为了表明它会起作用,这里是一个例子。如您所知,绝对不建议这样做。

        import sys
        def new_print(msg):
            sys.stdout.write("I always add this text\n")
            sys.stdout.write(msg)
        
        print = new_print
        
        print("Test")
        

        我总是添加这个文本

        测试

        【讨论】:

          猜你喜欢
          • 2020-08-29
          • 2020-08-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-24
          • 1970-01-01
          • 2012-03-29
          • 2018-10-05
          相关资源
          最近更新 更多