开发者

How do you get the name of a calling module as a string using inspect in Python (I keep getting a module object)

开发者 https://www.devze.com 2023-03-09 17:38 出处:网络
I\'m trying to get the name of a calling module by using inspect. When I return what should be the module string, I get this:

I'm trying to get the name of a calling module by using inspect. When I return what should be the module string, I get this:

<module 'mymod.wrapper' from '/usr/local/lib/python2

I've looked at the docs and couldn't see anything about what the reason for this may be (I'm tired, so I m开发者_开发问答ay have missed it).

Here is the class

import inspect


class Wrapper():


    def getView(self, view, database=False):

        module = self._getDatabase()
        print(module)

    def _getDatabase(self):

        # Get calling module
        frm = inspect.stack()[1]
        modWhole = str(inspect.getmodule(frm[0]))
        modSplit = modWhole.split('.')
        mod = modSplit[0] + '.' + modSplit[1]
        return mod

Also, any advice on how to reconize and prevent this problem in the future is much appreciated. Thanks.


inspect.getmodule() returns the module object itself, not its name.

Try replacing

str(inspect.getmodule(frm[0]))

with

inspect.getmodule(frm[0]).__name__

Also, bear in mind that inspect.getmodule() can return None.


You can use the __name__ attribute:

>>> import xml
>>> xml.__name__
'xml'
>>> m = __import__('xml')
<module 'xml' from '/usr/lib/python2.7/xml/__init__.pyc'>
>>> m.__name__
'xml'
0

精彩评论

暂无评论...
验证码 换一张
取 消