How to import a module in Python 3 from a string? -


a solution problem available python 2, uses imp module deprecated in python 3.

imp has been replaced importlib works file based imports. specifically, importlib.import_module requires file name - not string or file handler.

i made workaround dumping contents of url file , importing it

def initlog():     modulename = '_mylogging'     try:         import _mylogging     except importerror:         r = requests.get('http://(...)/mylogging.py')         open(modulename+'.py', "w") f:             f.write(r.text)     finally:         import _mylogging      return _mylogging.mylogging().getlogger() 

but avoid intermediate file.

putting security, network performance , availability issues aside - is there way feed string importlib? (or file handler, in case use io.stringio)

you can adapt exactly same answer 3.x, using the replacement imp.new_module:

from types import moduletype  foo = moduletype('foo') 

and the replacement exec statement:

foo_code = """ class foo:     pass """  exec(foo_code, globals(), foo.__dict__) 

after works expected:

>>> dir(foo) ['foo', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] >>> foo.foo() <__main__.foo object @ 0x110546ba8> 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -