How can I access the current executing module or class name in Python?

前端 未结 11 1840
醉酒成梦
醉酒成梦 2020-12-05 01:30

I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:

foo.py:

11条回答
  •  离开以前
    2020-12-05 02:12

    Using __file__ alone gives you a relative path for the main module and an absolute path for imported modules. Being aware this we can get the module file constantly either way with a little help from our os.path tools.

    For filename only use __file__.split(os.path.sep)[-1].

    For complete path use os.path.abspath(__file__).

    Demo:

    /tmp $ cat f.py
    from pprint import pprint
    import os
    import sys
    
    pprint({
        'sys.modules[__name__]': sys.modules[__name__],
        '__file__': __file__,
        '__file__.split(os.path.sep)[-1]': __file__.split(os.path.sep)[-1],
        'os.path.abspath(__file__)': os.path.abspath(__file__),
    })
    
    /tmp $ cat i.py
    import f
    

    Results:

    ## on *Nix ##
    
    /tmp $ python3 f.py
    {'sys.modules[__name__]': ,
     '__file__': 'f.py',
     '__file__.split(os.path.sep)[-1]': 'f.py',
     'os.path.abspath(__file__)': '/tmp/f.py'}
    
    /tmp $ python3 i.py
    {'sys.modules[__name__]': ,
     '__file__': '/tmp/f.pyc',
     '__file__.split(os.path.sep)[-1]': 'f.pyc',
     'os.path.abspath(__file__)': '/tmp/f.pyc'}
    
    ## on Windows ##
    
    PS C:\tmp> python3.exe f.py
    {'sys.modules[__name__]': ,
     '__file__': 'f.py',
     '__file__.split(os.path.sep)[-1]': 'f.py',
     'os.path.abspath(__file__)': 'C:\\tools\\cygwin\\tmp\\f.py'}
    
    PS C:\tmp> python3.exe i.py
    {'sys.modules[__name__]': ,
     '__file__': 'C:\\tools\\cygwin\\tmp\\f.py',
     '__file__.split(os.path.sep)[-1]': 'f.py',
     'os.path.abspath(__file__)': 'C:\\tools\\cygwin\\tmp\\f.py'}
    

    If you want to strip the '.py' off the end, you can do that easily. (But don't forget that you may run a '.pyc' instead.)

提交回复
热议问题