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

前端 未结 11 1816
醉酒成梦
醉酒成梦 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:05

    The "currently executing module" clearly is foo, as that's what contains the function currently running - I think a better description as to what you want is the module of foo's immediate caller (which may itself be foo if you're calling a f() from a function in foo called by a function in bar. How far you want to go up depends on what you want this for.

    In any case, assuming you want the immediate caller, you can obtain this by walking up the call stack. This can be accomplished by calling sys._getframe, with the aprropriate number of levels to walk.

    def f():
        caller = sys._getframe(1)  # Obtain calling frame
        print "Called from module", caller.f_globals['__name__']
    

    [Edit]: Actually, using the inspect module as suggested above is probably a cleaner way of obtaining the stack frame. The equivalent code is:

    def f():
        caller = inspect.currentframe().f_back
        print "Called from module", caller.f_globals['__name__']
    

    (sys._getframe is documented as being for internal use - the inspect module is a more reliable API)

    0 讨论(0)
  • 2020-12-05 02:06

    I think what you want to use is the inspect module, to inspect the python runtime stack. Check out this tutorial. I think it provides an almost exact example of what you want to do.

    0 讨论(0)
  • 2020-12-05 02:07

    From the comment -- not the question.

    I am simply curious to see if what I am trying to do is possible.

    The answer to "is it possible" is always "yes". Always. Unless your question involves time travel, anti-gravity or perpetual motion.

    Since the answer is always "yes", your question is ill-formed. The real question is "what's a good way to have my logging module know the name of the client?" or something like that.

    The answer is "Accept it as a parameter." Don't mess around with inspecting or looking for mysterious globals or other tricks.

    Just follow the design pattern of logging.getLogger() and use explicitly-named loggers. A common idiom is the following

    logger= logging.getLogger( __name__ )
    

    That handles almost all log naming perfectly.

    0 讨论(0)
  • 2020-12-05 02:07

    __file__ is the path of current module the call is made.

    0 讨论(0)
  • 2020-12-05 02:08

    This should work for referencing the current module:

    import sys
    sys.modules[__name__]
    
    0 讨论(0)
  • 2020-12-05 02:11

    It's been a while since I've done python, but I believe that you can get access to the globals and locals of a caller through its traceback.

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