3
4

pipでコマンドをインストールしようとすると「venvしろって!」怒られてうざい人向けのtips

Last updated at Posted at 2024-07-13

TLDR;

単発のコマンドラインツールをpipで入れたい時はpipxDockerを使うと良い.

いつからかpipで公開されている便利コマンドを入れようとすると,「OS標準のPython環境を壊すな!」って言われる.

$ pip3 install rfcbibtex
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try brew install
    xyz, where xyz is the package you are trying to
    install.

    If you wish to install a Python library that isn't in Homebrew,
    use a virtual environment:

    python3 -m venv path/to/venv
    source path/to/venv/bin/activate
    python3 -m pip install xyz
...

ちょっとコマンド一つ入れるために言われた通りにvenvするのも面倒くさい

手法

pipxで入れる

コマンドラインツールを分離環境でインストールするためのツールがあった.

pipxをbrewでインストール

brew install pipx

使いたいコマンドをインストール

$ pipx install rfcbibtex
  installed package rfcbibtex 0.3.2, installed using Python 3.12.4
  These apps are now globally available
    - rfcbibtex
⚠️  Note: '/Users/username/.local/bin' is not on your PATH environment
    variable. These apps will not be globally accessible until your PATH is
    updated. Run `pipx ensurepath` to automatically add it, or manually modify
    your PATH in your shell's config file (e.g. ~/.bashrc).
done! ✨ 🌟 ✨

利用中のshellに~/.local/binのパスを追加するコマンドがある.

$ pipx ensurepath

Dockerで入れよう

pipxも入れたくない! / より厳密に実行環境を分離したい人向け.

1. 使いたいコマンドだけのためにDocker imageを作る

  • Dockerfileを書く
FROM python:3.11.9-slim-bookworm

# 作業ディレクトリを設定
WORKDIR /app

# 必要なPythonパッケージをインストール
RUN pip install rfcbibtex

# デフォルトのコマンドを設定
ENTRYPOINT ["rfcbibtex"]

buildする.ここではイメージ名はコマンド名とする.

docker build -t rfcbibtex .

2. shellにaliaseを書く

  • zsh版/bash版
.zshrc
alias rfcbibtex='docker run --rm rfcbibtex'
  • fish版
config.fish
alias rfcbibtex 'docker run --rm rfcbibtex'

3. 実行する

パイプもできるよ

$ rfcbibtex rfc9200 | pbcopy
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4