43

set -xシェルスクリプトと同等のPythonコマンドを提案してください。

Python によって実行された各ソース ファイル行を印刷/ログする方法はありますか?

4

4 に答える 4

22

bash -xモジュールを使用するのと同等のものを適切に取得するには、インポートされたすべてのモジュールのソース行の出力をブロックするtraceために使用する必要があります。たとえば、必要に応じて他のモジュールの場所にディレクティブを追加します。--ignore-dirpython -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

これはあなたの質問に実際には答えません。に相当する Python を要求しましたset -x。それを近似する簡単な方法は次のsys.settrace()とおりです。

jcomeau@aspire:/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()

実行すると、次のようになります。

jcomeau@aspire:/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()」行を削除することは、読者の課題として残されています。

ソース: https://pymotw.com/2/sys/tracing.htmlおよびhttp://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html

于 2015-10-31T08:52:42.743 に答える