How to import a module given its name as string?

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

    If you want it in your locals:

    >>> mod = 'sys'
    >>> locals()['my_module'] = __import__(mod)
    >>> my_module.version
    '2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'
    

    same would work with globals()

提交回复
热议问题