How to import a module given its name as string?

前端 未结 11 1442
不思量自难忘°
不思量自难忘° 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:43

    With Python older than 2.7/3.1, that's pretty much how you do it.

    For newer versions, see importlib.import_module for Python 2 and and Python 3.

    You can use exec if you want to as well.

    Or using __import__ you can import a list of modules by doing this:

    >>> moduleNames = ['sys', 'os', 're', 'unittest'] 
    >>> moduleNames
    ['sys', 'os', 're', 'unittest']
    >>> modules = map(__import__, moduleNames)
    

    Ripped straight from Dive Into Python.

提交回复
热议问题