eval to import a module

后端 未结 2 1307
小蘑菇
小蘑菇 2020-12-09 02:52

I can\'t import a module using the eval() function.

So, I have a function where if I do import vfs_tests as v it works. However, the same i

相关标签:
2条回答
  • 2020-12-09 03:33

    Actually. if you absolutely need to import using eval (for example, code injection), you can do it as follow in Python 3, since exec is a function:

    eval("exec('import whatever_you_want')")
    

    For example:

    0 讨论(0)
  • 2020-12-09 03:46

    Use exec:

    exec 'import vfs_tests as v'
    

    eval works only on expressions, import is a statement.

    exec is a function in Python 3 : exec('import vfs_tests as v')

    To import a module using a string you should use importlib module:

    import importlib
    mod = importlib.import_module('vfs_tests')
    

    In Python 2.6 and earlier use __import__.

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