How to import a module given its name as string?

前端 未结 11 1417
不思量自难忘°
不思量自难忘° 2020-11-21 06:19

I\'m writing a Python application that takes as a command as an argument, for example:

$ python myapp.py command1

I want the application to

11条回答
  •  不知归路
    2020-11-21 06:49

    The recommended way for Python 2.7 and 3.1 and later is to use importlib module:

    importlib.import_module(name, package=None)

    Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

    e.g.

    my_module = importlib.import_module('os.path')
    

提交回复
热议问题