文件名和python脚本的行号

Joe*_*oey 98 python debugging file

如何在python脚本中获取文件名和行号.

我们从异常回溯中获取的文件信息.在这种情况下,不会引发异常.

Joe*_*oey 146

感谢mcandre,答案是:

from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print frameinfo.filename, frameinfo.lineno
Run Code Online (Sandbox Code Playgroud)

  • @gsinha:每个函数调用都会影响性能.您必须衡量这种影响是否可以接受. (6认同)
  • 所以,如果你喜欢"一行"类型的答案,请使用:`import inspect inspect.getframeinfo(inspect.currentframe()).lineno` (5认同)
  • 使用这种方法是否有任何性能影响(例如运行时间略有增加或需要更多 CPU)? (2认同)
  • 为了扩展这一点,在第二行或第三行中的什么时候“评估”行号?即,当您评估它时,或者使用 getframeinfo(currentframe()) 创建它时,“frameinfo.lineno”是否会为您提供行号? (2认同)
  • @LimokPalantaemon,当调用 `currentframe()` 时会发生这种情况,这意味着您不能比 `getframeinfo(currentframe()).lineno` 更简化(如果您只关心行号而不是文件名)。请参阅 https://docs.python.org/2/library/inspect.html#inspect.currentframe (2认同)

aar*_*ren 41

是否使用currentframe().f_back取决于您是否使用某项功能.

直接致电检查:

from inspect import currentframe, getframeinfo

cf = currentframe()
filename = getframeinfo(cf).filename

print "This is line 5, python says line ", cf.f_lineno 
print "The filename is ", filename
Run Code Online (Sandbox Code Playgroud)

调用为您执行此操作的函数:

from inspect import currentframe

def get_linenumber():
    cf = currentframe()
    return cf.f_back.f_lineno

print "This is line 7, python says line ", get_linenumber()
Run Code Online (Sandbox Code Playgroud)

  • 另外一个,用于提供可调用功能的解决方案.非常好! (2认同)
  • 一直想从函数中调用 - 这有帮助。谢谢 (2认同)

Str*_*oup 20

如果在公共文件中使用,则很方便 - 打印文件名,行号和调用者的功能:

import inspect
def getLineInfo():
    print(inspect.stack()[1][1],":",inspect.stack()[1][2],":",
          inspect.stack()[1][3])
Run Code Online (Sandbox Code Playgroud)

  • 应该是公认的答案 (2认同)

ari*_*lou 10

文件名:__file__sys.argv[0]
行:( inspect.currentframe().f_lineno不是inspect.currentframe().f_back.f_lineno如上所述)


Ter*_*ist 8

在 Python 3 中,您可以使用以下变体:

def Deb(msg = None):
  print(f"Debug {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")
Run Code Online (Sandbox Code Playgroud)

在代码中,您可以使用:

Deb("Some useful information")
Deb()
Run Code Online (Sandbox Code Playgroud)

生产:

123: Some useful information
124:
Run Code Online (Sandbox Code Playgroud)

其中 123 和 124 是发出呼叫的线路。

  • 这是最简单也是最好的,尤其是当 `sys` 已经导入时。其他答案中的“检查”对于我的用例来说是多余的。 (3认同)

Dan*_*ilo 7

只为贡献,

linecachepython中有一个模块,这里有两个可以提供帮助的链接。

linecache 模块文档
linecache 源代码

从某种意义上说,您可以将整个文件“转储”到它的 cache 中,并使用 linecache.cache 类中的数据读取它。

import linecache as allLines
## have in mind that fileName in linecache behaves as any other open statement, you will need a path to a file if file is not in the same directory as script
linesList = allLines.updatechache( fileName ,None)
for i,x in enumerate(lineslist): print(i,x) #prints the line number and content
#or for more info
print(line.cache)
#or you need a specific line
specLine = allLines.getline(fileName,numbOfLine)
#returns a textual line from that number of line
Run Code Online (Sandbox Code Playgroud)

有关其他信息,对于错误处理,您可以简单地使用

from sys import exc_info
try:
     raise YourError # or some other error
except Exception:
     print(exc_info() )
Run Code Online (Sandbox Code Playgroud)


sta*_*010 7

这是一个打印文件名和行号的简短函数。

from inspect import currentframe, getframeinfo


def HERE(do_print=True):
    ''' Get the current file and line number in Python script. The line 
    number is taken from the caller, i.e. where this function is called. 

    Parameters
    ----------
    do_print : boolean
        If True, print the file name and line number to stdout. 

    Returns
    -------
    String with file name and line number if do_print is False.

    Examples
    --------
    >>> HERE() # Prints to stdout

    >>> print(HERE(do_print=False))
    '''
    frameinfo = getframeinfo(currentframe().f_back)
    filename = frameinfo.filename.split('/')[-1]
    linenumber = frameinfo.lineno
    loc_str = 'File: %s, line: %d' % (filename, linenumber)
    if do_print:
        print('HERE AT %s' % (loc_str))
    else:
        return loc_str
Run Code Online (Sandbox Code Playgroud)

用法:

HERE() # Prints to stdout
# Output: HERE AT File: model.py, line: 275

print(HERE(False)) # Retrieves string and prints it.
# Output: File: model.py, line: 276
Run Code Online (Sandbox Code Playgroud)


小智 6

最好也使用sys-

print dir(sys._getframe())
print dir(sys._getframe().f_lineno)
print sys._getframe().f_lineno
Run Code Online (Sandbox Code Playgroud)

输出为:

['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace']
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
14
Run Code Online (Sandbox Code Playgroud)


小智 5

import inspect    

file_name = __FILE__
current_line_no = inspect.stack()[0][2]
current_function_name = inspect.stack()[0][3]

#Try printing inspect.stack() you can see current stack and pick whatever you want 
Run Code Online (Sandbox Code Playgroud)