Pythonスクリプトのファイル名と行番号


113

Pythonスクリプトでファイル名と行番号を取得するにはどうすればよいですか。

例外トレースバックから取得した正確なファイル情報。この場合、例外は発生しません。

回答:


161

mcandreのおかげで、答えは次のとおりです。

#python3
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print(frameinfo.filename, frameinfo.lineno)

1
この方法を使用すると、パフォーマンスに影響がありますか(実行時間のわずかな増加や必要なCPUの増加など)?
gsinha

6
@gsinha:すべての関数呼び出しはパフォーマンスに影響します。この影響が許容できるかどうかを測定する必要があります。
omikron 2015年

5
だから、「1行」型の答えのようなあなたが使用している場合:import inspect inspect.getframeinfo(inspect.currentframe()).lineno
1-IJK

1
@LimokPalantaemonは、currentframe()が呼び出されたときに発生します。つまり、これを単純化することはできませんgetframeinfo(currentframe()).lineno(ファイル名ではなく、行番号のみに関心がある場合)。docs.python.org/2/library/inspect.html#inspect.currentframe
Aaron Millerを

1
@ joey、printステートメントに括弧を入れるべきではありませんか?
MCG 2018年

49

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

2
加えて、呼び出し可能な関数でソリューションを提供します。非常に素晴らしい!
MikeyE 2017年

21

共通ファイルで使用すると便利-呼び出し元のファイル名、行番号、機能を出力します。

import inspect
def getLineInfo():
    print(inspect.stack()[1][1],":",inspect.stack()[1][2],":",
          inspect.stack()[1][3])

11

ファイル名

__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/…を
bgoodr

10

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

6

貢献するだけで

そこにある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() )


3

Python 3では、次のバリエーションを使用できます。

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

コードでは、次を使用できます。

Deb("Some useful information")
Deb()

生産する:

123: Some useful information
124:

ここで、123と124は、呼び出し元の行です。


0

これ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
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.