动态导入Python模块 [英] Dynamically importing Python module

查看:121
本文介绍了动态导入Python模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个受信任的远程服务器,其中存储了许多自定义的Python模块.我可以通过HTTP(例如使用urllib2.urlopen)作为文本/纯文本来获取它们,但是我无法将获取的模块代码保存到本地硬盘上.如何将代码作为完全可操作的Python模块(包括其全局变量和导入)导入?
我想我必须使用execimp模块的功能的某种组合,但是我仍然无法使其工作.

I have a trusted remote server that stores many custom Python modules. I can fetch them via HTTP (e.g. using urllib2.urlopen) as text/plain, but I cannot save the fetched module code to the local hard disk. How can I import the code as a fully operable Python module, including its global variables and imports?
I suppose I have to use some combination of exec and imp module's functions, but I've been unable to make it work yet.

推荐答案

看起来应该可以解决问题:

It looks like this should do the trick: importing a dynamically generated module


>>> import imp
>>> foo = imp.new_module("foo")
>>> foo_code = """
... class Foo:
...     pass
... """
>>> exec foo_code in foo.__dict__
>>> foo.Foo.__module__
'foo'
>>>

此外,按照ActiveState文章中的建议,您可能希望将新模块添加到sys.modules:

Also, as suggested in the ActiveState article, you might want to add your new module to sys.modules:


>>> import sys
>>> sys.modules["foo"] = foo
>>> from foo import Foo
<class 'Foo' …>
>>>

这篇关于动态导入Python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆