检查模块是否存在,如果没有安装

时间:2010-12-24 17:30:45

标签: python module import

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

我该怎么做?

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

try:
    import keyring
except ImportError:
    print 'f'

8 个答案:

答案 0 :(得分:16)

import pip

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

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

答案 1 :(得分:12)

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

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

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

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

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

答案 2 :(得分:10)

这种动态导入方法非常适用于您只想在未安装模块时打印消息的情况。自动安装模块不应该,就像通过subprocess发送pip一样。这就是为什么我们有setuptools(或分发)。

我们有一些很好的包装教程,依赖检测/安装的任务就像提供install_requires=[ 'FancyDependency', 'otherFancy>=1.0' ]一样简单。就是这样!

但是,如果您真的需要手动执行,您可以使用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'])

答案 3 :(得分:2)

注意:Ipython / Jupyter专用解决方案。

在使用笔记本电脑/在线内核时,我通常使用systems call进行操作。

try:
  import keyring
except:
  !pip install pulp
  import keyring

答案 4 :(得分:1)

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

答案 5 :(得分:1)

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

import os

package = "package_name"

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

答案 6 :(得分:1)

我做了一个import_neccessary_modules()函数来解决这个常见问题。

# ======================================================================================
# == Fix any missing Module, that need to be installed with PIP.exe. [Windows System] ==
# ======================================================================================
import importlib, os
def import_neccessary_modules(modname:str)->None:
    '''
        Import a Module,
        and if that fails, try to use the Command Window PIP.exe to install it,
        if that fails, because PIP in not in the Path,
        try find the location of PIP.exe and again attempt to install from the Command Window.
    '''
    try:
        # If Module it is already installed, try to Import it
        importlib.import_module(modname)
        print(f"Importing {modname}")
    except ImportError:
        # Error if Module is not installed Yet,  the '\033[93m' is just code to print in certain colors
        print(f"\033[93mSince you don't have the Python Module [{modname}] installed!")
        print("I will need to install it using Python's PIP.exe command.\033[0m")
        if os.system('PIP --version') == 0:
            # No error from running PIP in the Command Window, therefor PIP.exe is in the %PATH%
            os.system(f'PIP install {modname}')
        else:
            # Error, PIP.exe is NOT in the Path!! So I'll try to find it.
            pip_location_attempt_1 = sys.executable.replace("python.exe", "") + "pip.exe"
            pip_location_attempt_2 = sys.executable.replace("python.exe", "") + "scripts\pip.exe"
            if os.path.exists(pip_location_attempt_1):
                # The Attempt #1 File exists!!!
                os.system(pip_location_attempt_1 + " install " + modname)
            elif os.path.exists(pip_location_attempt_2):
                # The Attempt #2 File exists!!!
                os.system(pip_location_attempt_2 + " install " + modname)
            else:
                # Neither Attempts found the PIP.exe file, So i Fail...
                print(f"\033[91mAbort!!!  I can't find PIP.exe program!")
                print(f"You'll need to manually install the Module: {modname} in order for this program to work.")
                print(f"Find the PIP.exe file on your computer and in the CMD Command window...")
                print(f"   in that directory, type    PIP.exe install {modname}\033[0m")
                exit()


import_neccessary_modules('art')
import_neccessary_modules('pyperclip')
import_neccessary_modules('winsound')

答案 7 :(得分:0)

并非所有模块都可以轻松安装。并非所有这些都支持简单安装,有些只能通过构建它们来安装..其他需要一些非python先决条件,比如gcc,这会使事情变得更复杂(并且忘记它在Windows上运行良好)。

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