在Python中查找print语句

Cas*_*ash 18 python

有时我会在项目中留下调试打印语句,很难找到它.有什么方法可以找出特别是印刷品的线条吗?

边注

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

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

And*_*lke 38

你问过静态解决方案.这是一个动态的.假设您运行代码并查看错误的打印或写入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'
>>> 
Run Code Online (Sandbox Code Playgroud)

对于更复杂的东西,将'sys.stdout'替换为报告print语句所在位置的东西.我将使用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()
Run Code Online (Sandbox Code Playgroud)

这是输出

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)
Run Code Online (Sandbox Code Playgroud)

如果你走这条路线,也可以参见'linecache'模块,你可以用它来打印线的内容.查看traceback.print_stack的实现,了解如何执行此操作的详细信息.

  • `AttributeError:'TracePrints' 对象没有属性 'flush'` (2认同)

小智 7

对于Python3,我使用它修补打印来打印文件名、行号和函数

import builtins
from inspect import getframeinfo, stack
original_print = print

def print_wrap(*args, **kwargs):
    caller = getframeinfo(stack()[1][0])
    original_print("FN:",caller.filename,"Line:", caller.lineno,"Func:", caller.function,":::", *args, **kwargs)

builtins.print = print_wrap
Run Code Online (Sandbox Code Playgroud)


Geo*_*Geo 5

这篇文章可以证明非常有价值.查找line事件并从框架中提取方法名称(如果我没记错的话).更多信息可以在这里找到