回答:
mcandreのおかげで、答えは次のとおりです。
#python3
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe())
print(frameinfo.filename, frameinfo.lineno)
import inspect inspect.getframeinfo(inspect.currentframe()).lineno
currentframe()
が呼び出されたときに発生します。つまり、これを単純化することはできませんgetframeinfo(currentframe()).lineno
(ファイル名ではなく、行番号のみに関心がある場合)。docs.python.org/2/library/inspect.html#inspect.currentframe
使用currentframe().f_back
するかどうかは、関数を使用するかどうかによって異なります。
inspectを直接呼び出す:
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
あなたのためにそれを行う関数を呼び出す:
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()
共通ファイルで使用すると便利-呼び出し元のファイル名、行番号、機能を出力します。
import inspect
def getLineInfo():
print(inspect.stack()[1][1],":",inspect.stack()[1][2],":",
inspect.stack()[1][3])
ファイル名:
__file__
# or
sys.argv[0]
ライン:
inspect.currentframe().f_lineno
(inspect.currentframe().f_back.f_lineno
上記とは異なります)
NameError: global name '__file__' is not defined
私のPythonインタプリタ上:Python 2.7.6 (default, Sep 26 2014, 15:59:23)
。stackoverflow.com/questions/9271464/…を
sysを使用する方が良い-
print dir(sys._getframe())
print dir(sys._getframe().f_lineno)
print sys._getframe().f_lineno
出力は次のとおりです。
['__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
貢献するだけで
そこにあるlinecache
のpython内のモジュールは、ここに助けることができる2つのリンクです。
linecacheモジュールドキュメント
linecacheソースコード
ある意味では、ファイル全体をキャッシュに「ダンプ」して、クラスの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
追加情報については、エラー処理については、単に使用することができます
from sys import exc_info
try:
raise YourError # or some other error
except Exception:
print(exc_info() )
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
__file__
ます:stackoverflow.com/questions/3056048/…を
これdmsg
は私がVSCode 1.39.2のPython 3.7.3の行番号を取得するために機能するものです(デバッグメッセージのニーモニックです):
import inspect
def dmsg(text_s):
print (str(inspect.currentframe().f_back.f_lineno) + '| ' + text_s)
変数name_s
とその値を表示して呼び出すには:
name_s = put_code_here
dmsg('name_s: ' + name_s)
出力は次のようになります。
37| name_s: value_of_variable_at_line_37