lycheejam's tech log

チラ裏のメモ帳 | プログラミングは苦手、インフラが得意なつもり。

MacでPython3デフォルトにする

概要

pythonコマンドで3.x系のPythonを使用出来るようにする話です。

homebrewでインストールしているPythonですが、pythonコマンドだと2.X系がデフォルトになっています。
pythonの3.X系を使うにはpython3コマンドを使う必要があるので、しんどいな〜と言う感じで設定しました。

目次

前提

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.14.6
BuildVersion:   18G95

Homebrewでpythonインストール済み。(2.x系も3.x系も)
シェルはbashです。fishとかxnoshの場合は知りません。

現状

pythonコマンドで2.x系がデフォで使用されている。

$ python -V
Python 2.7.10

これを3.x系に変更します。

手順

brewでpython3のインストールパスを確認して、そのパスを通すだけです。

Homebrewでpython3のインストールパスを確認

brewコマンドでインストールパスを確認します

$ brew info python
python: stable 3.7.4 (bottled), HEAD
export PATH=$PATH:/Users/{user}/.nodebrew/current/bin
Interpreted, interactive, object-oriented programming language
https://www.python.org/
/usr/local/Cellar/python/3.7.4_1 (3,919 files, 60.9MB) *
  Poured from bottle on 2019-09-15 at 18:41:28
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/python.rb
==> Dependencies
Build: pkg-config ✘
Required: gdbm ✔, openssl@1.1 ✔, readline ✔, sqlite ✔, xz ✔
==> Options
--HEAD
    Install HEAD version
==> Caveats
Python has been installed as
  /usr/local/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have been installed into
  /usr/local/opt/python/libexec/bin

If you need Homebrew's Python 2.7 run
  brew install python@2

You can install Python packages with
  pip3 install <package>
They will install into the site-package directory
  /usr/local/lib/python3.7/site-packages

See: https://docs.brew.sh/Homebrew-and-Python
==> Analytics
install: 534,726 (30 days), 1,411,488 (90 days), 4,989,324 (365 days)
install_on_request: 271,696 (30 days), 702,815 (90 days), 2,621,699 (365 days)
build_error: 0 (30 days)

ここにインストールされているみたいですね。

Unversioned symlinks python, python-config, pip etc. pointing to python3, python3-config, pip3 etc., respectively, have been installed into /usr/local/opt/python/libexec/bin

PATHを通す。

私の場合は諸々、.bashrcで管理しているのでそちらにパスを追記します。
追記するパスは前述の/usr/local/opt/python/libexec/binです。

※nodebrewのパスが混じってますが気にしない。

  • ~/.bashrc
- export PATH=$PATH:/Users/{user}/.nodebrew/current/bin
+ export PATH=/usr/local/opt/python/libexec/bin:/Users/{user}/.nodebrew/current/bin:$PATH

再読み込み。

パスを反映させるために再読み込みをします。

$ source .bashrc

反映確認

pythonコマンドで3.x系がデフォになっているか確認します。

$ python -V
Python 3.7.4
$ which python
/usr/local/opt/python/libexec/bin/python

以上

雑感

一々、python3って入力するのがだるすぎて設定しました...
あと会社のMacbookaws cliインストールするのにこの設定が必要で詰まっちゃったので...