gpt4 book ai didi

python - 在 Python 中查找打印语句

转载 作者:IT老高 更新时间:2023-10-28 21:06:20 25 4
gpt4 key购买 nike

有时我将调试打印语句留在我的项目中,很难找到它。有什么方法可以找出哪一行正在打印特别的东西?

旁注

看来,智能搜索可以解决大多数情况。在 Pydev(和其他 IDE)中,有一个搜索功能,允许搜索项目中的所有文件。当然,使用带有 -rn 标志的 grep 可以获得类似的效果,尽管您只能获取行号而不是直接链接。

"print("在我的代码中工作得更好,并且通常在 print 语句中有额外的文本可以使用正则表达式进行搜索。最困难的情况是当您刚刚编写 print(x) 时,尽管这可以搜索 x 中的值不以引号开头或结尾的正则表达式(感谢!BecomingGuro)

最佳答案

您询问了静态解决方案。这是一个动态的。假设您运行代码并看到错误的打印或写入 sys.stdout,并且想知道它来自哪里。您可以替换 sys.stdout 并让异常回溯帮助您:

>>> import sys
>>> def go():
... sys.stdout = None
... print "Hello!"
...
>>> go()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in go
AttributeError: 'NoneType' object has no attribute 'write'
>>> print "Here"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'write'
>>>

对于更复杂的东西,将“sys.stdout”替换为报告打印语句所在位置的东西。我将使用 traceback.print_stack() 来显示完整的堆栈,但是您可以执行其他操作,例如使用 sys._getframe() 来查找一个堆栈级别以获取行号和文件名。

import sys
import traceback

class TracePrints(object):
def __init__(self):
self.stdout = sys.stdout
def write(self, s):
self.stdout.write("Writing %r\n" % s)
traceback.print_stack(file=self.stdout)

sys.stdout = TracePrints()

def a():
print "I am here"

def b():
a()

b()

这是输出

Writing 'I am here'
File "stdout.py", line 19, in <module>
b()
File "stdout.py", line 17, in b
a()
File "stdout.py", line 14, in a
print "I am here"
File "stdout.py", line 9, in write
traceback.print_stack(file=self.stdout)
Writing '\n'
File "stdout.py", line 19, in <module>
b()
File "stdout.py", line 17, in b
a()
File "stdout.py", line 14, in a
print "I am here"
File "stdout.py", line 9, in write
traceback.print_stack(file=self.stdout)

如果你走这条路线,另请参阅“linecache”模块,您可以使用它来打印行的内容。查看 traceback.print_stack 的实现,了解如何执行此操作的详细信息。

关于python - 在 Python 中查找打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1617494/

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