检查Python中下一行的代码

时间:2014-03-12 20:21:31

标签: python code-inspection

# 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)的行号和内容而不是当前行?

这对于调试很方便,oneliner可以显示它下面的行代码。

修改

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

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 个答案:

答案 0 :(得分:1)

import inspect; import sys ; print open(sys.argv[0]).readlines()[inspect.currentframe().f_lineno].strip()

虽然这可能不太有用。

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print frameinfo.filename, frameinfo.lineno