【问题标题】:How to import a python module accessible via an url如何导入可通过 url 访问的 python 模块
【发布时间】:2011-05-30 10:36:09
【问题描述】:

我的公司使用某种版本控制存档工具(Microsoft Windows),我想从中直接导入。但我找不到这样做的方法。

这是我尝试过的:

>>> import sys
>>> sys.path.append(r"http://some_path_copied_and_pasted/05.Autres%20Outils/Regen_Engine")
>>> sys.path
['C:\\Python26\\Lib\\idlelib', 'C:\\Python26\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'http://some_path_copied_and_pasted/05.Autres%20Outils/Regen_Engine']
>>> import regen_engine as r
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    import regen_engine as r
ImportError: No module named regen_engine

我尝试将 URL 的“%20”替换为“”(空格),但结果是一样的。我也尝试过使用imp 模块,但没有更好的。

所以这是我的问题:

  1. 是否可以从 URL 进行导入?
  2. 如果是,我该如何实现?

也许一种解决方案是使用 Sharepoint 的其他隐藏路径访问此文件,因此为它添加一个标签是合适的。

【问题讨论】:

  • 千万不要尝试,但是看看 xhtmlhook:boddie.org.uk/python/xhtmlhook
  • 据我了解,这似乎与用于文档目的的 xhtml 更相关。我的意思是,Sharepoint 作为一个 Web 门户可见,但我仍然可以通过在具有完整 URL 的 Web 浏览器中直接访问来找到我的 python 脚本。

标签: python sharepoint import


【解决方案1】:
import urllib
def urlimport(x):
    exec urllib.urlopen(x) in globals()

这是错误的做法,你不应该在生产代码中使用它,它只是一个概念证明。

【讨论】:

  • 按照你的例子,我开始通过阅读脚本来测试这个。但现在我有一些连接问题:URLError: &lt;urlopen error [Errno 10061] No connection could be made because the target machine actively refused it&gt;。所以我想我得先检查一下,我敢打赌它与这个不太酷的 Sharepoint 门户有关,也许是某种访问权限政策。不像乍一看那么简单......
  • 这很明显,因此我的评论是“我必须检查一下”。从您的第一个答案中,我了解到 Python 可以从 URL 导入(即使有点棘手);现在我的工作是了解如何处理这个共享点服务器。所以感谢您提供的证据。
  • 这样做我得到了一个错误:“TypeError: exec: arg 1 must be a string, file, or code object”。我稍微改变了它以导入 urllib;文件路径 = urllib.urlretrieve(url)[0];使用 open(filepath) as f: exec f in globals(); ```
【解决方案2】:

试试:

def dynamic_import_by_uri(file)
    file = os.path.abspath(file)
    exec open(file, 'rb') in globals()

它可以工作,但对生产版本不安全...

【讨论】:

    猜你喜欢
    • 2015-10-26
    • 2019-05-29
    • 2015-04-02
    • 2020-03-02
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2015-09-29
    相关资源
    最近更新 更多