如何从URL导入Python模块?

时间:2015-02-03 14:08:46

标签: python url import module

作为一项实验,我想了解如何从URL导入Python模块。这里的假设目标是从一个中心位置导入,使模块保持最新状态。怎么可以这样做?

我的尝试如下:

>>> import urllib
>>> 
>>> def import_URL(URL):
...     exec urllib.urlopen(URL) in globals()
... 
>>> import_URL("https://cdn.rawgit.com/wdbm/shijian/master/shijian.py")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in import_URL
TypeError: exec: arg 1 must be a string, file, or code object

编辑:Martijn Pieters确定了导致远程模块的字符串表示形式的示例代码的修复程序。结果代码如下:

import urllib
def import_URL(URL):
    exec urllib.urlopen(URL).read() in globals()

3 个答案:

答案 0 :(得分:5)

是的,你可以。

只需使用网址获取模块,然后将其存储为字符串,您可以使用eval()

运行该模块

使用urllibeval可以轻松完成:

import urllib.request
a = urllib.request.urlopen(url)
eval(a.read())

请注意,某些模块(例如Pygame和Pydub)需要运行时,并且由于缺少运行时而无法使用eval()运行。

祝你的项目好运,我希望我帮助过。

答案 1 :(得分:2)

基本上有一个专门用于此目的的模块称为httpimport。当前,它支持从包含程序包/模块的URL以及从URL中可以找到的档案(.tar。* 、. zip)中导入(这是处理远程依赖项的一种方法)。

它与Python的导入系统完全集成,因此您无需exec进行任何in globals()的操作。你只是:

>>> with httpimport.remote_repo(['package1'], 'http://my-codes.example.com/python_packages'):
...     import package1
...

然后package1就可以用于脚本的其余部分,就像它是本地资源一样。


免责声明:我是该模块的作者。

答案 2 :(得分:0)

以下是复制和粘贴的示例:

url = "https://gist.githubusercontent.com/operatorequals/ee5049677e7bbc97af2941d1d3f04ace/raw/e55fa867d3fb350f70b2897bb415f410027dd7e4"
with httpimport.remote_repo(["hello"], url):
    import hello
hello.hello()

此答案的灵感来自@operatorequals