通过互联网/多种协议导入python模块或动态创建模块 [英] Import python module over the internet/multiple protocols or dynamically create module
问题描述
是否可以使用http
(s
),ftp
,smb
或任何其他协议从互联网上通过import
一个Python模块?如果是这样,怎么办?如果没有,为什么?
Is it possible to import
a Python module from over the internet using the http
(s
), ftp
, smb
or any other protocol? If so, how? If not, why?
我想这是关于让Python使用更多一种协议(读取文件系统)并使它也能使用其他协议.是的,我同意它会慢很多倍,但是一定的优化和更大的未来带宽肯定会平衡它.
I guess it's about making Python use more the one protocol(reading the filesystem) and enabling it to use others as well. Yes I agree it would be many folds slower, but some optimization and larger future bandwidths would certainly balance it out.
例如:
import site
site.addsitedir("https://bitbucket.org/zzzeek/sqlalchemy/src/e8167548429b9d4937caaa09740ffe9bdab1ef61/lib")
import sqlalchemy
import sqlalchemy.engine
推荐答案
原则上可以,但是所有支持此功能的内置工具都通过文件系统.
In principle, yes, but all of the tools built-in which kinda support this go through the filesystem.
为此,您将必须从任何地方加载源,使用compile
进行编译,并使用新模块的__dict__
进行编译.见下文.
To do this, you're going to have to load the source from wherever, compile it with compile
, and exec
it with the __dict__
of a new module. See below.
我已经离开了实际上从互联网上获取的文本,并解析了uris等作为读者的练习(对于初学者:我建议使用requests
)
I have left the actually grabbing text from the internet, and parsing uris etc as an exercise for the reader (for beginners: I suggest using requests
)
在 pep 302 术语中,这将是import
语句集成的详细信息,请参见该文档.
In pep 302 terms, this would be the implementation behind a loader.load_module
function (the parameters are different). See that document for details on how to integrate this with the import
statement.
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)
此时,newmodule
已经是作用域中的模块对象,因此您无需导入它或任何其他内容.
At this point newmodule
is already a module object in scope, so you don't need to import it or anything.
modulesource = '''
a = 'foo'
def myfun(astr):
return a + astr
'''
newmod = makemodule(modulesource)
print(newmod.myfun('bat'))
此处的IDONE: http://ideone.com/dXGziO
经python 2测试,应与python 3一起使用(使用文本兼容的打印;使用类似函数的exec语法).
Tested with python 2, should work with python 3 (textually compatible print used;function-like exec syntax used).
这篇关于通过互联网/多种协议导入python模块或动态创建模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!