using variable in import command

后端 未结 2 1553
南旧
南旧 2020-12-03 19:15

I have a variable like

k = os

If I have to import os I can write

import os

then I get no error But how

相关标签:
2条回答
  • 2020-12-03 20:13

    You can use the __import__ function:

    k = 'os'
    module = __import__(k)
    
    0 讨论(0)
  • 2020-12-03 20:14

    Use importlib module if you want to import modules based on a string:

    >>> import importlib
    >>> os = importlib.import_module('os')
    >>> os
    <module 'os' from '/usr/lib/python2.7/os.pyc'>
    

    When you do something like this:

    >>> k = 'os'
    >>> import k
    

    then Python still looks for file named k.py, k.pyc etc not os.py as you intended.

    0 讨论(0)
提交回复
热议问题