gpt4 book ai didi

python - 抑制函数的输出

转载 作者:行者123 更新时间:2023-12-01 06:23:42 24 4
gpt4 key购买 nike

有一件事情我想消除,那就是当函数 print 输出时,我知道重写 sys.stdout.write which print( ) 函数使用。但我认为这不是一个理想的解决方案。我正在寻找理想的Pythonic方式来做到这一点?

from timeit import Timer
from functools import partial

def timing_decorator(function):
def wrapper(*args, **kwargs):
# print(function)
callable_f = partial(function, *args, **kwargs)
# print(dir(Timer))
total = Timer(callable_f).timeit(1)
print(total)
return total
return wrapper

# example function
@timing_decorator
def hello(arg):
print(arg)
return

hello('hi')

输出:

hi
0.00036

我的预期输出是:

0.00036

最佳答案

我们可以使用标准库的 unittest 模块中的 patch 来覆盖 print 功能通过使用上下文管理器来调用使用此包装器的函数。然而,话虽如此,@kindall 采用的方法是首选,因为它更 Pythonic,因为这个答案是使用本质上用于测试目的的东西。

from unittest.mock import patch

def timing_decorator(function):
def wrapper(*args, **kwargs):
# print(function)
callable_f = partial(function, *args, **kwargs)
with patch('__main__.print'):
total = Timer(callable_f).timeit(1)
print(f"{function.__name__}: {total:.5f}ms")
return total
return wrapper

关于python - 抑制函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60268345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com