Skip to content

Pip

A tool for installing and managing Python packages.

Categories

How to install

아래와 같이 간편하게 설치할 수 있다.

$ sudo easy_install pip

자동 설치 방법

https://pip.pypa.io/en/latest/installing.html 에서 get-pip.py를 다운받은 후 Python으로 실행하면 된다.

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py

If setuptools (or distribute) is not already installed, get-pip.py will install setuptools for you.

To upgrade an existing setuptools (or distribute), run

$ pip install -U setuptools

간단하게 한 줄로 해결할 수 있다.

curl -s -L https://bootstrap.pypa.io/get-pip.py | python

바이너리로 설치

python -m pip install --only-binary wheel {opts} {packages}

소스코드로 설치

pip install <package> --no-binary :all: {opts} {packages}

How to upgrade

$ sudo pip install --upgrade [PACKAGE_NAME]

수동 설치 방법

## md5=2332e6f97e75ded3bddde0ced01dbda3
$ curl -O https://pypi.python.org/packages/source/p/pip/pip-6.0.8.tar.gz
$ tar xzf pip-6.0.8.tar.gz 
$ cd pip-6.0.8
$ python setup.py install

Version specifiers

~=같은 버전 지정 방법. 자세한 내용은 PEP 440#Version specifiers 항목 참조.

requirements.txt vs constraints.txt

자세한 내용은 Python:Constraints#requirements.txt vs constraints.txt 항목 참조.

Download package file

$ pip download [PACKAGE_NAME]

외부 사이트 참조 방법 (Package Index Options)

-i, --index-url
Python Package Index의 기본 URL(기본값 https://pypi.org/simple). 이것은 PEP 503(the simple repository API)을 준수하는 저장소 또는 동일한 형식으로 배치된 로컬 디렉토리를 가리켜야 합니다.
--extra-index-url
--index-url 외에 사용할 패키지 색인의 추가 URL입니다. --index-url과 동일한 규칙을 따라야 합니다.
--no-index
패키지 색인 무시 (대신 --find-links URL만 확인한다)
--find-links
HTML 파일에 대한 URL 또는 경로인 경우 sdist(.tar.gz) 또는 wheel(.whl) 파일과 같은 아카이브에 대한 링크를 구문 분석합니다.
디렉토리인 로컬 경로 또는 file:// URL인 경우 디렉토리 목록에서 아카이브를 찾습니다.
VCS 프로젝트 URL에 대한 링크는 지원되지 않습니다.

예시로, pytorch에서 사용할 경우 다음과 같다:

requirements.txt파일 상단에 위 옵션을 사용할 수 있다.

로컬 디렉토리 참조하여 설치 방법 (개발자 모드)

pip install --help
...
  -e, --editable <path/url>   Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url.

그래서 pip install -e ~/Project/avplayer 처럼 하면 된다.

Cache directory

The default location for the cache directory depends on the Operating System:

Unix
~/.cache/pip and it respects the XDG_CACHE_HOME directory.
macOS
~/Library/Caches/pip
Windows
<CSIDL_LOCAL_APPDATA>\pip\Cache

Command line

With pip 20.1 or later, you can find it with:

pip cache dir

Pythonic and cross-platform way

import pip
from distutils.version import LooseVersion

if LooseVersion(pip.__version__) < LooseVersion('10'):
    # older pip version
    from pip.utils.appdirs import user_cache_dir
else:
    # newer pip version
    from pip._internal.utils.appdirs import user_cache_dir

print(user_cache_dir('pip'))
print(user_cache_dir('wheel'))

배포 방법

implementation, platform, abi

I don't think there is one definitive list. You have to collect it from different sources. Start with PEP 425

  • python tag: ‘py27’, ‘cp33’
  • abi tag: ‘cp32dmu’, ‘none’
  • platform tag: ‘linux_x86_64’, ‘any’
  • --implementation:
    • cp: CPython
    • ip: IronPython
    • pp: PyPy
    • jy: Jython
  • --platform:
    • win32
    • linux_i386
    • linux_x86_64

PIP LIST in PYTHON CODE

WARNING

코드에서 직접 PIP를 호출하는 것은 권장되지 않는다. 공식 문서 참조: https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program

pkg_resources

import pkg_resources
print([p.project_name for p in pkg_resources.working_set])
# note that this is same as calling pip._vendor.pkg_resources.working_set

iter_modules

Takes a long time to execute (~300ms on computer w/ I5 CPU, SSD, & 8 gigs ram). The benefit is that it will have a far more extensive list of modules and it will output importable names.

Ex: python-dateutil is imported as dateutil, but iter_modules will give you the importable name: dateutil

from pkgutil import iter_modules
print([p.name for p in iter_modules()])

Troubleshooting

Install MacOSX

MacOSX에서 설치할 경우 아래와 같은 에러가 발생할 수 있다.

Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-RRbrVj/scons/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-vQQgw8-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-RRbrVj/scons

따라서 pip 및 그 밖의 Python 패키지를 설치할 경우 아래와 같이 pip -H옵션을 사용해야 한다.

$ sudo -H python get-pip.py
$ sudo -H pip install scons

Operation not permitted

Mac OSX에서 sudo -H pip install {PACKAGE}와 같은 방식으로 패키지 설치시 아래와 같은 에러가 발생할 수 있다.

Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
...
OSError: [Errno 1] Operation not permitted: '/System/Library/Frameworks/Python.framework/Versions/2.7/share'

이는, 해당 디렉토리가 시스템에 의해 보호되고 있음을 뜻한다. 아래와 같이 확인할 수 있다.

$ ls -lO /System/Library/Frameworks/Python.framework/Versions/2.7/
$ csrutil status

restricted로 보호되어 있음을 확인할 수 있다.

이 경우, pyenv, virtualenv 등을 사용하여 별도의 디렉터리에 Python 패키지를 관리하도록 설정해야 한다.

CERTIFICATE_VERIFY_FAILED

CERTIFICATE_VERIFY_FAILED 항목 참조. 또는 다음 목록 중 선택.

  • Use HTTP instead of HTTPS (e.g. --index-url=http://pypi.python.org/simple/).
  • Use --cert <trusted.pem> or CA_BUNDLE variable to specify alternative CA bundle.
    • E.g. you can go to failing URL from web-browser and import root certificate into your system.
  • Run python -c "import ssl; print(ssl.get_default_verify_paths())" to check the current one (validate if exists).
  • OpenSSL has a pair of environments (SSL_CERT_DIR, SSL_CERT_FILE) which can be used to specify different certificate database 1.
  • Use --trusted-host<hostname> to mark the host as trusted.
  • In Python use verify=False for requests.get (see: SSL Cert Verification).
  • Use --proxy<proxy> to avoid certificate checks.
  • sudo apt-get install ca-certificates

check, freeze, install, list, show 명령에서 FileNotFoundError 가 발생될 경우

site-packages/pip/__main__.py를 확인해 보면 다음과 같은 항목이 있다:

# Remove '' and current working directory from the first entry
# of sys.path, if present to avoid using current directory
# in pip commands check, freeze, install, list and show,
# when invoked as python -m pip <command>
if sys.path[0] in ("", os.getcwd()):
    sys.path.pop(0)

이 중 os.getcwd()항목에서 FileNotFoundError 가 발생된다면, Python:os#FileNotFoundError in os.getcwd 항목을 참조해보자.

docopt is being installed using the legacy 'setup.py install' method

  DEPRECATION: docopt is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559

See also

Favorite site

References