检查Python中下一行的代码

1 投票
4 回答
912 浏览
提问于 2025-04-17 22:01
# 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),而不是当前这一行呢?

这样在调试的时候会很方便,可以一行代码显示下面那行的内容。

编辑

通过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
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print frameinfo.filename, frameinfo.lineno
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
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
1
import inspect; import sys ; print open(sys.argv[0]).readlines()[inspect.currentframe().f_lineno].strip()

虽然这可能没什么用。

撰写回答