Finding full pathname in a Python trace

前端 未结 1 577
时光取名叫无心
时光取名叫无心 2021-01-13 13:32

When turning on Python trace, the filename is provided, along with the module and sourcecode.

Is it possible to show the file path as well as the filename?

相关标签:
1条回答
  • 2021-01-13 14:02

    If patching of trace.py is allowed, this task is easy.

    Copy trace.py (from /usr/lib/python2.7/ in my case) to a local directory (e. g. the current one), then patch the function modname(path) in that local copy. That function strips the directories off the module paths, so the package information is lost. The original contains the line

    filename, ext = os.path.splitext(base)
    

    which can be changed to

    filename, ext = os.path.splitext(path)
    

    in order to not strip the directory.

    The output of a call like ./trace.py --trace t.py then looks like this:

     --- modulename: t, funcname: <module>
    t.py(3): import mypackage.mymodule
     --- modulename: mypackage/__init__, funcname: <module>
    __init__.py(1):   --- modulename: mypackage/mymodule, funcname: <module>
    mymodule.py(1): print 42
    42
    t.py(5): print 5
    5
     --- modulename: ./trace, funcname: _unsettrace
    trace.py(80):         sys.settrace(None)
    

    I'm tracing a test script called t.py which imports a module mymodule.py which is in a package mypackage (so the filename is ./mypackage/mymodule.py). That module only prints 42, the test script itself prints 5.

    Does this solve your issue?

    EDIT:

    Upon second view, I propose a different patch.

    In function globaltrace_lt() the modulename is derived by calling modname(); patch this to call fullmodname():

                modulename = fullmodname(filename)
    

    I think this might be a less intrusive patch.

    0 讨论(0)
提交回复
热议问题