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

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

问题描述

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

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?

我的尝试如下:

>>> 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 确定了示例代码的修复程序,该代码导致远程模块的字符串表示形式。生成的代码如下:


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


推荐答案

是的,你可以。

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

Just fetch the module with the url and once you have it store it as a string where you can run it using eval()

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

Using urllib and eval it can be done easily:

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

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

Do note that some modules (such as Pygame and Pydub) require runtimes and they could not be run using eval() because of the missing runtimes.

祝你的项目顺利,我希望我帮忙。

Good luck with your project, I hope I helped.

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

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