このコードはあなたにとって興味深いかもしれません。
トレースバックを取得し、表示されるべきではない最初のファイルを削除します。次に、Python の動作をシミュレートします。
Traceback (most recent call last):
トレースバックに複数のファイルが含まれている場合にのみ表示されます。これは、余分なフレームがなかったかのように見えます。
ここに私のコード、 string があると仮定しますtext
:
try:
exec(text)
except:
# we want to format the exception as if no frame was on top.
exp, val, tb = sys.exc_info()
listing = traceback.format_exception(exp, val, tb)
# remove the entry for the first frame
del listing[1]
files = [line for line in listing if line.startswith(" File")]
if len(files) == 1:
# only one file, remove the header.
del listing[0]
print("".join(listing), file=sys.stderr)
sys.exit(1)