1
# script.py  

greeting = "hi"
import inspect; import traceback; print traceback.format_stack(inspect.currentframe())[-1]
print greeting

脚本第四行的代码打印出文件名、行号和当前行:

$ python script.py   
File "script.py", line 4, in <module>
    import inspect; import traceback; print traceback.format_stack(inspect.currentframe())[-1]
hi

但是我怎样才能打印出下一行(print greeting)而不是当前行的行号和内容?

这将便于调试,一个单行显示它下面的行的代码。

编辑

通过本的回答,我得到了这个可怕的生物:

import inspect; import sys; _lne = inspect.currentframe().f_lineno; print "{0}, line {1}:".format(__file__, _lne+1); print open(sys.argv[0]).readlines()[_lne].strip()

它有 166 个字符长,非常冗长。请注意,IndexError当没有下一行时它会引发。

运行python script.py将打印出以下内容

script.py, line 5:  
print greeting
hi

我希望我发布的原始行中的一些细微更改可能会导致所需的行为,因为其中包括文件名和编号,而无需显式打印这些。它提供的缩进也不是不受欢迎的。

4

4 回答 4

1

编码:

# Put format_stack_offset() in a separate module to invoke as needed
def format_stack_offset(frame=None, offset=1):
    from traceback import linecache
    import inspect; 
    if not frame:
        frame = inspect.currentframe().f_back
    lineno = frame.f_lineno + offset
    co = frame.f_code
    filename = co.co_filename
    name = co.co_name
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, frame.f_globals)
    retVal =  '\n  File "%s", line %d, in %s' % (filename, lineno, name)
    if line:
        retVal += "\n        " + line.strip()
    return retVal

# script.py
greeting = "hi"
print format_stack_offset()  # This is a one liner to show next line
print greeting

生产

 File "/tmp/script.py", line 22, in <module>
    print greeting
 hi
于 2014-03-12T20:50:55.040 回答
1

添加一个小辅助函数来查找和打印相关的文件名和行:

import inspect, linecache

def show_next(cf):
    'Show the line following the active line in a stackframe'
    filename = cf.f_code.co_filename
    line = cf.f_lineno
    print linecache.getline(filename, line+1)


greeting = "hi"

show_next(inspect.currentframe())
print greeting

当然,如果需要,也可以变成一行:

greeting = "hi"
import inspect, linecache; _f=inspect.currentframe(); print linecache.getline(_f.f_code.co_filename, _f.f_lineno+1)
print greeting
于 2014-03-12T20:38:30.873 回答
1
import inspect; import sys ; print open(sys.argv[0]).readlines()[inspect.currentframe().f_lineno].strip()

虽然这可能不太有用。

于 2014-03-12T20:34:03.070 回答
0
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print frameinfo.filename, frameinfo.lineno
于 2014-03-12T20:36:35.543 回答