2013-04-02 7 views

答えて

26

あなたはtraceモジュールを使用することができます。

python -m trace -t your_script.py 

それが実行されると、上記のコマンドラインは、コードのすべての行を表示します。

+0

ありがとう、それはうまく動作します。 –

11
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.htmlhttp://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html

+1

私はデフォルトですべての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 " –

+2

これは短く、再ソースを必要とせずにvirtualenvを処理します:alias pyx =" python -mあなたがあなたの答えを更新したなら、それは良いでしょう。(あなたはあなたの答えを更新したといいでしょう。) - trace --ignore-dir \ $(python -c 'import os、sys; print(os.pathsep.join(sys.path [1:]))')-t " –

+0

Python 3でも動作する – tjanez

関連する問題