添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
I am downvoting you so you might notice that your accepted answer is incorrect. philologon Jul 8 '16 at 15:50 This is incorrect and results in the line number of the compiled FOO.pyc file instead. Here is what I use instead message = 'Code location {0.filename}@{0.lineno}:'.format(inspect.getframeinfo(inspect.currentframe())) as per @arilou's post. Daniel Sokolowski Sep 10 '13 at 19:41 To all Googlers: This is not the correct answer. THE CORRECT ANSWER IS BELOW , with more than 15 up votes. Fernando Silveira Jun 26 '14 at 20:18 To all future Googlers. As of March 2015, there is only one answer "below" with > 15 votes, the one by Joey. Should there be more by the time that you read this, Fernando was referring to Joey's anwer Mawg Mar 6 '15 at 8:01 This answer is correct IF you put it in a function and call it everywhere. f_back return the caller frame. Just like original ActiveState code iman Jan 8 '16 at 17:48 Does using this method have any performance impact (like minor increase in run time or more CPU needed ) ? gsinha Dec 14 '14 at 5:41 @gsinha: Every function call has performance impact. You have to measure if this impact is acceptable for you. omikron Nov 9 '15 at 14:45 So, if you like "one line" type answers use: import inspect inspect.getframeinfo(inspect.currentframe()).lineno 1-ijk Sep 21 '17 at 18:11 To expand on this, at what point is the line number "evaluated", in the second or third line? I.e does frameinfo.lineno give you the line numer when you evaluate it, or when you created it with getframeinfo(currentframe()) ? Limok Palantaemon Mar 26 '18 at 13:48 filename = getframeinfo(cf).filename print "This is line 5, python says line ", cf.f_lineno print "The filename is ", filename

Calling a function that does it for you:

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()

Handy if used in a common file - prints file name, line number and function of the caller:

import inspect
def getLineInfo():
    print(inspect.stack()[1][1],":",inspect.stack()[1][2],":",
          inspect.stack()[1][3])
                NameError: global name '__file__' is not defined on my Python interpreter: Python 2.7.6 (default, Sep 26 2014, 15:59:23). See stackoverflow.com/questions/9271464/…
                    – bgoodr
                May 5 '17 at 17:41
print dir(sys._getframe())
print dir(sys._getframe().f_lineno)
print sys._getframe().f_lineno

The output is:

['__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']
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 

Just to contribute,

there is a linecache module in python, here is two links that can help.

linecache module documentation
linecache source code

In a sense, you can "dump" a whole file into its cache , and read it with linecache.cache data from class.

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

For additional info, for error handling, you can simply use

from sys import exc_info
     raise YourError # or some other error
except Exception:
     print(exc_info() )
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0 with attribution required. rev 2019.10.7.35131