Ble*_*ers 7 python network-protocols python-import python-exec
是否有可能import一个Python模块从过使用互联网http(s), ftp,smb或任何其它协议?如果是这样,怎么样?如果没有,为什么?
我想这是为了让Python使用更多的协议(读取文件系统)并使其能够使用其他协议.是的我同意它会慢很多倍,但是一些优化和更大的未来带宽肯定会平衡它.
例如:
import site
site.addsitedir("https://bitbucket.org/zzzeek/sqlalchemy/src/e8167548429b9d4937caaa09740ffe9bdab1ef61/lib")
import sqlalchemy
import sqlalchemy.engine
Run Code Online (Sandbox Code Playgroud)
我喜欢这个答案。应用它时,我对其进行了一些简化- 类似于通过HTTPjavascript包含的外观和感觉。
这是结果:
import os
import imp
import requests
def import_cdn(uri, name=None):
if not name:
name = os.path.basename(uri).lower().rstrip('.py')
r = requests.get(uri)
r.raise_for_status()
codeobj = compile(r.content, uri, 'exec')
module = imp.new_module(name)
exec (codeobj, module.__dict__)
return module
Run Code Online (Sandbox Code Playgroud)
用法:
redisdl = import_cdn("https://raw.githubusercontent.com/p/redis-dump-load/master/redisdl.py")
# Regular usage of the dynamic included library
json_text = redisdl.dumps(host='127.0.0.1')
Run Code Online (Sandbox Code Playgroud)
import_cdn函数放在公共库中,这样您就可以重复使用这个小函数原则上是的,但是所有支持此功能的内置工具都会通过文件系统。
为此,您必须从任意位置加载源代码,使用 编译它compile,并exec使用__dict__新模块的 编译它。见下文。
我已经从互联网上实际抓取文本,并解析 uris 等作为读者的练习(对于初学者:我建议使用requests)
用pep 302术语来说,这将是函数背后的实现loader.load_module(参数不同)。有关如何将其与import声明集成的详细信息,请参阅该文档。
import imp
modulesource = 'a=1;b=2' #load from internet or wherever
def makemodule(modulesource,sourcestr='http://some/url/or/whatever',modname=None):
#if loading from the internet, you'd probably want to parse the uri,
# and use the last part as the modulename. It'll come up in tracebacks
# and the like.
if not modname: modname = 'newmodulename'
#must be exec mode
# every module needs a source to be identified, can be any value
# but if loading from the internet, you'd use the URI
codeobj = compile(modulesource, sourcestr, 'exec')
newmodule = imp.new_module(modname)
exec(codeobj,newmodule.__dict__)
return newmodule
newmodule = makemodule(modulesource)
print(newmodule.a)
Run Code Online (Sandbox Code Playgroud)
此时newmodule已经是范围内的模块对象,因此您不需要导入它或任何内容。
modulesource = '''
a = 'foo'
def myfun(astr):
return a + astr
'''
newmod = makemodule(modulesource)
print(newmod.myfun('bat'))
Run Code Online (Sandbox Code Playgroud)
Ideone 在这里: http: //ideone.com/dXGziO
使用 python 2 进行测试,应该适用于 python 3(使用文本兼容的打印;使用类似函数的 exec 语法)。