如何自动安装缺少的 python 模块?
我希望能够写:
try:
import foo
except ImportError:
install_the_module("foo")
处理这种情况的推荐/惯用方法是什么?
我见过很多脚本只是打印错误或警告,通知用户缺少模块,并(有时)提供有关如何安装的说明。但是,如果我知道该模块在 PyPI 上可用,那么我肯定可以更进一步安装过程。不?
I would like to be able to write:
try:
import foo
except ImportError:
install_the_module("foo")
What is the recommended/idiomatic way to handle this scenario?
I've seen a lot of scripts simply print an error or warning notifying the user about the missing module and (sometimes) providing instructions on how to install. However, if I know the module is available on PyPI, then I could surely take this a step further an initiate the installation process. No?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
冒着投反对票的风险,我想建议一个快速破解方法。请注意,我完全同意接受的答案:依赖关系应该在外部进行管理。
但对于您绝对需要破解类似自包含的东西的情况,您可以尝试如下所示:
Risking negative votes, I would like to suggest a quick hack. Please note that I'm completely on board with accepted answer that dependencies should be managed externally.
But for situations where you absolutely need to hack something that acts like self contained, you can try something like below:
安装问题不是源代码的主题!
您可以在包的
setup.py
中正确定义依赖项使用
install_requires
配置。这就是要走的路......由于
ImportError
安装某些东西有点奇怪和可怕。不要这样做。
Installation issues are not subject of the source code!
You define your dependencies properly inside the
setup.py
of your packageusing the
install_requires
configuration.That's the way to go...installing something as a result of an
ImportError
is kind of weird and scary. Don't do it.
不要碰用户的安装。
Don't touch user's installation.
这是我整理的解决方案,我将其称为
pyInstall.py
。它实际上检查模块是否已安装,而不是依赖ImportError
(在我看来,使用if
而不是try 来处理此问题看起来更干净
/除外
)。我在版本 2.6 和 2.7 下使用过它...如果我不想将
print
作为函数处理...它可能会在旧版本中工作...并且我认为它会在旧版本中工作3.0+版本,但我从未尝试过。另外,正如我在
getPip
函数的注释中指出的那样,我认为该特定函数无法在 OS X 下工作。以下是一些使用示例:
编辑:A获取 pipPath 的更多跨平台方法是:
这假设 pip 已/将安装在系统路径上。它在非 Windows 平台上往往相当可靠,但在 Windows 上,最好使用我原来答案中的代码。
Here's the solution I put together which I call
pyInstall.py
. It actually checks whether the module is installed rather than relying onImportError
(it just looks cleaner, in my opinion, to handle this with anif
rather than atry
/except
).I've used it under version 2.6 and 2.7... it would probably work in older versions if I didn't want to handle
print
as a function... and I think it'll work in version 3.0+ but I've never tried it.Also, as I note in the comments of my
getPip
function, I don't think that particular function will work under OS X.Here are some usage examples:
Edit: A more cross-platform way of getting pipPath is:
This makes the assumption that
pip
is/will be installed on the system path. It tends to be pretty reliable on non-Windows platforms, but on Windows it may be better to use the code in my original answer.