作为一个实验,我想看看如何从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)