How to dynamically import modules using exec

Now I want to build the get_doc () function, which can get the module doc. Here is the code

def get_doc(module):
    exec "import module"
    print module.__doc__

And the returned information:

Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    get_doc(sys)
NameError: name 'sys' is not defined
+4
source share
2 answers

The problem is that you import "module"instead of the specified module, and you did not put the name moduleanywhere. A stupid solution for this would be to always useexec

def get_doc(module):
    exec "import {}".format(module)
    exec "print {}.__doc__".format(module)"

But instead, execI would suggest using a function __import__:

def get_doc(module):
    module = __import__(module)
    print module.__doc__

This allows you to increase flexibility, and you can modify, use the module as you wish.

+3
source

When you speak

get_doc(sys)

python sys. , , -

  • __import__ ,

    def get_doc(module):
        mod = __import__(module)
        print mod.__doc__
    
    get_doc("sys")
    

. , exec , this, , aIKid.

+2

All Articles