如何从URL导入Python模块?

d3p*_*3pd 16 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
Run Code Online (Sandbox Code Playgroud)

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

import urllib
def import_URL(URL):
    exec urllib.urlopen(URL).read() in globals()
Run Code Online (Sandbox Code Playgroud)

ope*_*als 12

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

它与 Python 的导入系统完全集成,因此您不需要exec任何in globals(). 你刚才:

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

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


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

  • 绝对地!采取这个要点:https://gist.github.com/operatorequals/64375aabe09e1da3fe59ffddad3448db#file-stealthy_opener-py Raw模式返回这个URL:https://gist.githubusercontent.com/operatorequals/64375aabe09e1da3fe59ffddad3448db/raw/a4347c3a26a60a25 7a146ccc5c968f2044257126/stealthy_opener。 py 因此,请使用带有以下 URL 的“load”:https://gist.githubusercontent.com/operatorequals/64375aabe09e1da3fe59ffddad3448db/raw/a4347c3a26a60a257a146ccc5c968f2044257126/(没有文件名)并加载“stealthy_opener”“模块”。 (2认同)

Sim*_*mon 7

是的你可以。

只需使用url提取模块,然后将其存储为字符串即可在其中运行 eval()

使用urllib,eval可以轻松完成:

import urllib.request
a = urllib.request.urlopen(url)
eval(a.read())
Run Code Online (Sandbox Code Playgroud)

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

祝您项目顺利,希望对您有所帮助。

  • 这不是存在安全风险吗?而且,如果依赖模块也应该从 url 加载怎么办? (2认同)