Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查模块是否存在,如果不存在,请安装它_Python_Module_Import - Fatal编程技术网

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

Python 检查模块是否存在,如果不存在,请安装它,python,module,import,Python,Module,Import,我想检查模块是否存在,如果不存在,我想安装它 我该怎么做 到目前为止,如果模块不存在,我有正确打印f的代码 try: import keyring except ImportError: print 'f' 您可以启动pip安装%s%keyring在除此之外的部分执行此操作,但我不建议这样做。正确的方法是使用将应用程序打包,以便在安装应用程序时,可以引入依赖项。并非所有模块都可以如此轻松地安装。并不是所有的软件都支持轻松安装,有些软件只能通过构建它们来安装。。另一些则需要一些非

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

我该怎么做

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

try:
    import keyring
except ImportError:
    print 'f'

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

并非所有模块都可以如此轻松地安装。并不是所有的软件都支持轻松安装,有些软件只能通过构建它们来安装。。另一些则需要一些非python的先决条件,比如gcc,这会使事情变得更加复杂(忘了它在Windows上工作得很好)


所以我想说,你可能可以使它适用于一些预先确定的模块,但它不可能是通用的,适用于任何模块。

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

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

因此,在我的
setup.py
文件中,我做了以下操作:

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

因此,如果安装了
package\u name
,则可以继续。否则,请通过我使用
子流程调用的包管理器安装它。如果您只想在未安装模块的情况下打印消息,这种动态导入方法非常有效。自动安装模块不应像通过
子流程发出pip那样。这就是为什么我们有setuptools(或distribute)

我们有一些关于打包的优秀教程,依赖项检测/安装的任务非常简单,只需提供
install\u requires=['fancydependence','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'])

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

您可以使用
os.system
,如下所示:

import os

package = "package_name"

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

注意:Ipython/Jupyter特定解决方案

在使用笔记本/在线内核时,我通常使用


我制作了一个
import\u neccessary\u 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')

这将在脚本中工作,并检查模块是否存在,但安装模块完全是另一种情况。结果表明,使用os.system()可以工作。与os.system.distutils相比,SUBSPROCESS.Popen更可取。您需要使用setuptools或distribute来实现它。这看起来是一个更现代的解决方案,但根本不处理版本固定。我不知道该怎么做…?当我使用此代码时,我得到了
权限拒绝错误
。尝试执行
pip.main(['install','--user',package])
。这对我不起作用,我得到了下一个错误“{module'pip'没有属性'main'}”,这是一个死链接。什么是
!pip安装纸浆
?IPython运行以
开头的任何命令。。读这个。因此,
!pip安装纸浆
将使用jupyter内的pip安装纸浆
try:
  import keyring
except:
  !pip install pulp
  import keyring
# ======================================================================================
# == 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')