简体   繁体   English

更改内置函数 - 打印

[英]Change builtin function - Print

I'm trying to change the print builtin function from python.我正在尝试从 python 更改打印内置函数。 The reason I'm trying to achieve this is cause my application has an verbose sys.argv, and I want to use print to console out the message whether the verbose is True or False.我试图实现这一点的原因是我的应用程序有一个详细的 sys.argv,我想使用打印来控制台输出消息,无论详细信息是 True 还是 False。

I've tried to use create a new function, but I get a recursion error:我尝试使用创建一个新函数,但出现递归错误:

>>> import builtins
>>> def new_print(*args, **kwargs):
...     print('print:', *args, **kwargs)
... 
>>> old_print = builtins.print
>>> old_print(1)
1
>>> builtins.print = new_print
>>> print(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in new_print
  File "<stdin>", line 2, in new_print
  File "<stdin>", line 2, in new_print
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

I've tried using sys.stdout():我试过使用 sys.stdout():

>>> import builtins
>>> import sys
>>> def new_print(*args, **kwargs):
...     sys.stdout(*args, **kwargs)
... 
>>> old_print = builtins.print
>>> old_print(1)
1
>>> builtins.print = new_print
>>> print(1
... )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in new_print
TypeError: '_io.TextIOWrapper' object is not callable

Although using those options, none seemed to work properly.尽管使用了这些选项,但似乎没有一个能正常工作。

I need the new print function to be accesible for all my module files, without needing to import it every time.我需要新的打印功能可以访问我的所有模块文件,而无需每次都导入它。 That's why I'm trying to change the builtin function, but I'm not sure that changing this in my init .py file will make a difference for my other files.这就是我尝试更改内置函数的原因,但我不确定在我的init .py 文件中更改它是否会对我的其他文件产生影响。

Please, if you have any idea on what could help me, please leave it below.请,如果您对什么可以帮助我有任何想法,请将其留在下面。

You almost had it.你几乎拥有它。 Call old_print in your new function:在新函数中调用old_print

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

old_print = print
print = new_print

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM