如何检测python是否打印了太多字符串



如何检测python是否打印过多?

例如,python是否打印了10个字符串还是10根以上的绳子?

这是我的代码:

def findall(directory):
files = os.listdir(directory)
for fl in files:
path = str(os.path.join(directory,fl))
toomuch = str(10)
final_path = str(print(path))
final_path = str(True)
listdir = str(os.listdir(path))
if listdir > toomuch:
final_path = False
print("Too much file to load :/")
elif final_path == True:
print(final_path)
else:
final_path = False
return

如何检测是否打印了超过10个目录?

您可以将每个字符串值附加到一个数组中,并对其进行计数。或者声明一个值为0的变量,并在每次迭代时将其增加一,然后您将获得该循环的总迭代次数。

出于调试目的,这个小技巧将达到您的目的。

在该解决方案中,全局变量aprintCounter被保留,builtinprint函数被custom print替换。在自定义打印中,我们可以添加额外的自定义代码,如打印计数器值。

但是,由于全局变量的使用不是线程安全的,因此生产代码应该避免使用此解决方案。

import builtins as __builtin__
# A globabl counter for the print function call
printCounter = 0 
# Override the builtin print method with custom print function
def print(*args, **kwargs):
global printCounter
printCounter += 1
__builtin__.print(f'Total print so far {printCounter}') # Printing coutner
return __builtin__.print(*args, **kwargs)
for i in range(5):
print(i)

结果:

Total print so far 1
0
Total print so far 2
1
Total print so far 3
2
Total print so far 4
3
Total print so far 5
4

最新更新