Here is how to import a string as a module

1590 단어 서버
    import sys,imp
    
    my_code = 'a = 5'
    mymodule = imp.new_module('mymodule')
    exec my_code in mymodule.__dict__

In Python 3, exec is a function, so this should work:
   import sys,imp
    
    my_code = 'a = 5'
    mymodule = imp.new_module('mymodule')
    exec(my_code, mymodule.__dict__)

Now access the module attributes (and functions, classes etc) as:
print(mymodule.a)
>>> 5

To ignore any next attempt to import, add the module to sys:
sys.modules[‘mymodule’] = mymodule

좋은 웹페이지 즐겨찾기