Programing

Python 패키지가 설치되어 있는지 확인

lottogame 2020. 9. 11. 19:26
반응형

Python 패키지가 설치되어 있는지 확인


Python 스크립트 내에서 패키지가 설치되었는지 확인하는 좋은 방법은 무엇입니까? 통역사에서는 쉽지만 스크립트 내에서해야합니다.

설치 중에 생성 된 디렉토리가 시스템에 있는지 확인할 수있을 것 같지만 더 좋은 방법이있는 것 같습니다. Skype4Py 패키지가 설치되어 있는지 확인하려고합니다. 그렇지 않으면 설치하겠습니다.

수표 수행에 대한 나의 아이디어

  • 일반 설치 경로에서 디렉토리를 확인하십시오.
  • 패키지 가져 오기를 시도하고 예외가 발생하면 패키지를 설치하십시오.

파이썬 스크립트를 의미하는 경우 다음과 같이하십시오.

try:
 import mymodule
except ImportError, e:
 pass # module doesn't exist, deal with it.

업데이트 된 답변

이를 수행하는 더 좋은 방법은 다음과 같습니다.

import subprocess
import sys

reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]

결과:

print(installed_packages)

[
    "Django",
    "six",
    "requests",
]

requests설치되어 있는지 확인하십시오 .

if 'requests' in installed_packages:
    # Do something

왜 이렇게? 때로는 앱 이름 충돌이 있습니다. 앱 네임 스페이스에서 가져 오는 것은 시스템에 설치된 항목의 전체 그림을 제공하지 않습니다.

제안 된 솔루션이 작동합니다.

  • pip를 사용하여 PyPI 또는 다른 대체 소스 (예 : pip install http://some.site/package-name.zip또는 다른 아카이브 유형) 에서 설치할 때 .
  • 설치시 수동으로 사용 python setup.py install.
  • 시스템 저장소에서 설치할 때 sudo apt install python-requests.

작동 하지 않을 수있는 경우 :

  • 개발 모드에서 설치할 때 python setup.py develop.
  • 개발 모드에서 설치할 때 pip install -e /path/to/package/source/.

이전 답변

이를 수행하는 더 좋은 방법은 다음과 같습니다.

import pip
installed_packages = pip.get_installed_distributions()

pip> = 10.x의 경우 다음을 사용하십시오.

from pip._internal.utils.misc import get_installed_distributions

왜 이렇게? 때로는 앱 이름 충돌이 있습니다. 앱 네임 스페이스에서 가져 오는 것은 시스템에 설치된 항목의 전체 그림을 제공하지 않습니다.

결과적으로 pkg_resources.Distribution개체 목록이 표시 됩니다. 예를 들어 다음을 참조하십시오.

print installed_packages
[
    "Django 1.6.4 (/path-to-your-env/lib/python2.7/site-packages)",
    "six 1.6.1 (/path-to-your-env/lib/python2.7/site-packages)",
    "requests 2.5.0 (/path-to-your-env/lib/python2.7/site-packages)",
]

목록 작성 :

flat_installed_packages = [package.project_name for package in installed_packages]

[
    "Django",
    "six",
    "requests",
]

requests설치되어 있는지 확인하십시오 .

if 'requests' in flat_installed_packages:
    # Do something

As of Python 3.3, you can use the find_spec() method

import importlib.util

# For illustrative purposes.
package_name = 'pandas'

spec = importlib.util.find_spec(package_name)
if spec is None:
    print(package_name +" is not installed")

If you want to have the check from the terminal, you can run

pip3 show package_name

and if nothing is returned, the package is not installed.

If perhaps you want to automate this check, so that for example you can install it if missing, you can have the following in your bash script:

pip3 show package_name 1>/dev/null #pip for Python 2
if [ $? == 0 ]; then
   echo "Installed" #Replace with your actions
else
   echo "Not Installed" #Replace with your actions, 'pip3 install --upgrade package_name' ?
fi

As an extension of this answer:

For Python 2.*, pip show <package_name> will perform the same task.

For example pip show numpy will return the following or alike:

Name: numpy
Version: 1.11.1
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: numpy-discussion@scipy.org
License: BSD
Location: /home/***/anaconda2/lib/python2.7/site-packages
Requires: 
Required-by: smop, pandas, tables, spectrum, seaborn, patsy, odo, numpy-stl, numba, nfft, netCDF4, MDAnalysis, matplotlib, h5py, GridDataFormats, dynd, datashape, Bottleneck, blaze, astropy

You can use the pkg_resources module from setuptools. For example:

import pkg_resources

package_name = 'cool_package'
try:
    cool_package_dist_info = pkg_resources.get_distribution(package_name)
except pkg_resources.DistributionNotFound:
    print('{} not installed'.format(package_name))
else:
    print(cool_package_dist_info)

Note that there is a difference between python module and a python package. A package can contain multiple modules and module's names might not match the package name.


I'd like to add some thoughts/findings of mine to this topic. I'm writing a script that checks all requirements for a custom made program. There are many checks with python modules too.

There's a little issue with the

try:
   import ..
except:
   ..

solution. In my case one of the python modules called python-nmap, but you import it with import nmap and as you see the names mismatch. Therefore the test with the above solution returns a False result, and it also imports the module on hit, but maybe no need to use a lot of memory for a simple test/check.

I also found that

import pip
installed_packages = pip.get_installed_distributions()

installed_packages will have only the packages has been installed with pip. On my system pip freeze returns over 40 python modules, while installed_packages has only 1, the one I installed manually (python-nmap).

Another solution below that I know it may not relevant to the question, but I think it's a good practice to keep the test function separate from the one that performs the install it might be useful for some.

The solution that worked for me. It based on this answer How to check if a python module exists without importing it

from imp import find_module

def checkPythonmod(mod):
    try:
        op = find_module(mod)
        return True
    except ImportError:
        return False

NOTE: this solution can't find the module by the name python-nmap too, I have to use nmap instead (easy to live with) but in this case the module won't be loaded to the memory whatsoever.


If you'd like your script to install missing packages and continue, you could do something like this (on example of 'krbV' module in 'python-krbV' package):

import pip
import sys

for m, pkg in [('krbV', 'python-krbV')]:
    try:
        setattr(sys.modules[__name__], m, __import__(m))
    except ImportError:
        pip.main(['install', pkg])
        setattr(sys.modules[__name__], m, __import__(m))

A quick way is to use python command line tool. Simply type import <your module name> You see an error if module is missing.

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
>>> import sys
>>> import jocker
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named jocker
$

Hmmm ... the closest I saw to a convenient answer was using the command line to try the import. But I prefer to even avoid that.

How about 'pip freeze | grep pkgname'? I tried it and it works well. It also shows you the version it has and whether it is installed under version control (install) or editable (develop).


Go option #2. If ImportError is thrown, then the package is not installed (or not in sys.path).

참고URL : https://stackoverflow.com/questions/1051254/check-if-python-package-is-installed

반응형