シェルスクリプトでset -x
に相当するPythonコマンドを提示してください。シェルで `set -x`と同じPythonは何ですか?
Pythonで実行される各ソースファイル行を印刷/ログする方法はありますか?
シェルスクリプトでset -x
に相当するPythonコマンドを提示してください。シェルで `set -x`と同じPythonは何ですか?
Pythonで実行される各ソースファイル行を印刷/ログする方法はありますか?
あなたはtraceモジュールを使用することができます。
python -m trace -t your_script.py
それが実行されると、上記のコマンドラインは、コードのすべての行を表示します。
ありがとう、それはうまく動作します。 –
trace
モジュールを使用bash -x
の適切な等価物を得るためには、例えば、インポートされたすべてのモジュールのソース線の印刷をブロックする--ignore-dir
を使用する必要がありますpython -m trace --trace --ignore-dir /usr/lib/python2.7 --ignore-dir /usr/lib/pymodules repost.py
、他のモジュールの場所に必要に応じてさらに--ignore-dir
のディレクティブを追加します。
これは、遅いマシンで数百万のソースラインを吐き出したrequests
のような低速ロードモジュールを見つけるときに重要になります。 --ignore-dir
を適切に使用すると、時間が数秒に短縮され、自分のコードの行だけが表示されます。
$ time python -m trace --trace repost.py 2>&1 | wc
3710176 16165000 200743489
real 1m54.302s
user 2m14.360s
sys 0m1.344s
対
$ time python -m trace --trace --ignore-dir /usr/lib/python2.7 --ignore-dir /usr/lib/pymodules repost.py 2>&1 | wc
42 210 2169
real 0m12.570s
user 0m12.421s
sys 0m0.108s
これは本当にあなたの質問に答えていません。あなたはset -x
のPythonに相当するものを求めました。それを近似する簡単な方法はsys.settrace()
である:
[email protected]:/tmp$ cat test.py
#!/usr/bin/python -OO
'''
test program for sys.settrace
'''
import sys, linecache
TRACING = []
def traceit(frame, event, arg):
if event == "line":
lineno = frame.f_lineno
line = linecache.getline(sys.argv[0], lineno)
if TRACING:
print "%d: %s" % (lineno, line.rstrip())
return traceit
def test():
print 'this first line should not trace'
TRACING.append(True)
print 'this line and the following ought to show'
print "that's all folks"
TRACING.pop()
print 'this last line should not trace'
if __name__ == '__main__':
sys.settrace(traceit)
test()
、実行したときに、与える:
[email protected]:/tmp$ ./test.py
this first line should not trace
19: print 'this line and the following ought to show'
this line and the following ought to show
20: print "that's all folks"
that's all folks
21: TRACING.pop()
this last line should not trace
運動として残っているトレース出力からライン「TRACING.popを()」排除します読者のために。
源:私は "` bashの-x`の同等" を探していたhttps://pymotw.com/2/sys/tracing.htmlとhttp://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html
私はデフォルトですべてのstdlibを除外した小さなエイリアスを作成します:alias pyx = "python -m trace --ignore-dir $(python -c 'import os、sys; print(os.pathsep.join([p for p in sys.pathの場合は "python3.5"、pの場合 "python2.7")))) ')-t " –
これは短く、再ソースを必要とせずにvirtualenvを処理します:alias pyx =" python -mあなたがあなたの答えを更新したなら、それは良いでしょう。(あなたはあなたの答えを更新したといいでしょう。) - trace --ignore-dir \ $(python -c 'import os、sys; print(os.pathsep.join(sys.path [1:]))')-t " –
Python 3でも動作する – tjanez
。 –