如何从 URL 导入 Python 模块? [英] How can a Python module be imported from a URL?

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

问题描述

作为实验,我想看看如何从 URL 导入 Python 模块.这里的假设目标是从一个中心位置导入,使模块保持最新.这怎么可能?

我的尝试如下:

<预><代码>>>>导入 urllib>>>>>>def import_URL(URL):... 在 globals() 中执行 urllib.urlopen(URL)...>>>import_URL("https://cdn.rawgit.com/wdbm/shijian/master/shijian.py")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 2 行,在 import_URL 中类型错误:exec:arg 1 必须是字符串、文件或代码对象

<小时>

Martijn Pieters 确定了示例代码的修复,导致远程模块的字符串表示.生成的代码如下:

导入urllibdef import_URL(URL):在 globals() 中执行 urllib.urlopen(URL).read()

解决方案

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

它与 Python 的导入系统完全集成,因此您无需exec in globals() 中的任何内容.你只是:

>>>使用 httpimport.remote_repo(['package1'], 'http://my-codes.example.com/python_packages'):...导入包1...

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

<小时>

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

As an experiment, I want to see how to import a Python module from a URL. The hypothetical goal here would be to import from a central location which keeps the modules up-to-date. How could this be done?

My attempt is as follows:

>>> 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


EDIT: Martijn Pieters identified a fix for the example code that results in the string representation of the remote module. The resulting code is as follows:

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

解决方案

Basically there is a module exactly for this purpose called httpimport. Currently it supports importing from a URL that contains the package/module and also from archives (.tar.*, .zip) that can be found in URLs (this is a way to handle remote dependencies).

It is fully integrated with Python's import system so you don't need to exec anything in globals(). You just:

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

and then package1 is usable for the rest of the script like it was a local resource.


Disclaimer: I'm the author of this module.

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

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