Python 检查模块是否存在,如果不存在则安装

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4527554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:08:01  来源:igfitidea点击:

Check if module exists, if not install it

pythonmoduleimport

提问by dotty

I want to check if a module exists, if it doesn't I want to install it.

我想检查一个模块是否存在,如果不存在,我想安装它。

How should I do this?

我该怎么做?

So far I have this code which correctly prints fif the module doesn't exist.

到目前为止,我有这段代码,f如果模块不存在,它会正确打印。

try:
    import keyring
except ImportError:
    print 'f'

采纳答案by user225312

Here is how it should be done, and if I am wrong, please correct me. However, Noufal seems to confirm it in another answer to this question, so I guess it's right.

这是应该如何完成的,如果我错了,请纠正我。然而,Noufal 似乎在这个问题的另一个答案中证实了这一点,所以我猜是对的。

When writing the setup.pyscript for some scripts I wrote, I was dependent on the package manager of my distribution to install the required library for me.

setup.py为我编写的某些脚本编写脚本时,我依赖我的发行版的包管理器为我安装所需的库。

So, in my setup.pyfile, I did this:

所以,在我的setup.py文件中,我这样做了:

package = 'package_name'
try:
    return __import__(package)
except ImportError:
    return None

So if package_namewas installed, fine, continue. Else, install it via the package manager which I called using subprocess.

所以如果package_name安装了,很好,继续。否则,通过我调用的包管理器安装它subprocess

回答by Noufal Ibrahim

You can launch pip install %s"%keyringin the except part to do this but I don't recommend it. The correct way is to package your application using distutilsso that when it's installed, dependencies will be pulled in.

您可以pip install %s"%keyring在 except 部分启动以执行此操作,但我不建议这样做。正确的方法是使用distutils打包您的应用程序,以便在安装时引入依赖项。

回答by Assaf Lavie

Not all modules can be installed so easily. Not all of them have easy-install support, some can only be installed by building them.. others require some non-python prerequisites, like gcc, which makes things even more complicated (and forget about it working well on Windows).

并非所有模块都可以如此轻松地安装。并非所有这些都具有易于安装的支持,有些只能通过构建它们来安装..其他需要一些非 Python 先决条件,例如 gcc,这使事情变得更加复杂(忘记它在 Windows 上运行良好)。

So I would say you could probably make it work for some predetermined modules, but there's no chance it'll be something generic that works for any module.

所以我会说你可以让它适用于一些预定的模块,但它不可能是适用于任何模块的通用东西。

回答by Frangossauro

This approach of dynamic import work really well in cases you just want to print a message if module is not installed. Automatically installing a module SHOULDN'Tbe done like issuing pip via subprocess. That's why we have setuptools (or distribute).

这种动态导入方法在您只想在未安装模块的情况下打印消息的情况下非常有效。自动安装模块不应像通过subprocess. 这就是为什么我们有安装工具(或分发)。

We have some great tutorials on packaging, and the task of dependencies detection/installation is as simple as providing install_requires=[ 'FancyDependency', 'otherFancy>=1.0' ]. That's just it!

我们有一些很棒的打包教程,依赖检测/安装的任务就像提供install_requires=[ 'FancyDependency', 'otherFancy>=1.0' ]. 仅此而已!

But, if you really NEEDto do by hand, you can use setuptoolsto help you.

但是,如果你真的需要手工做,你可以使用setuptools来帮助你。

from pkg_resources import WorkingSet , DistributionNotFound
working_set = WorkingSet()

# Printing all installed modules
print tuple(working_set)

# Detecting if module is installed
try:
    dep = working_set.require('paramiko>=1.0')
except DistributionNotFound:
    pass

# Installing it (anyone knows a better way?)
from setuptools.command.easy_install import main as install
install(['django>=1.2'])

回答by ewil

import pip

def import_or_install(package):
    try:
        __import__(package)
    except ImportError:
        pip.main(['install', package])       

This code simply attempt to import a package, where package is of type str, and if it is unable to, calls pip and attempt to install it from there.

此代码只是尝试导入一个包,其中 package 的类型为str,如果无法导入,则调用 pip 并尝试从那里安装它。

回答by lsr729

You can use os.systemas follows:

您可以os.system按如下方式使用:

import os

package = "package_name"

try:
    __import__package
except:
    os.system("pip install "+ package)