LoginSignup
0

More than 3 years have passed since last update.

posted at

updated at

開発用ローカルサーバのPythonコマンドを統一するスクリプトの書き方

Macのローカルで簡易にWebサーバを建てたい時は、
Pythonのワンライナーでサクッと建てられるので便利です。
でも、バージョンが2系と3系ではコマンドが微妙に違うので使い分ける必要があり、
pyenv等を使用してローカルのバージョンを切り替えて使っている場合などではちょっとだけ不便でした。

Python 2系のコマンド

ポート8000番で建てたい場合

$ python -m SimpleHTTPServer 8000

Python 3系のコマンド

ポート8000番で建てたい場合

$ python -m http.server 8000

そこで、バージョンに関わらず実行できるスクリプトを作り、それにエイリアスを貼ることで同一コマンドで実行できるようにします。

Pythonバージョンに関わらず実行できる簡易サーバースクリプト

以下のようなスクリプトを ~/.bash_profile に追記すると、バージョンに関わらず py-server コマンドで実行できるようになります。
なお、実行時のデフォルトポート番号は8000にしています。

~/.bash_profile
# pythonのバージョンに関わらず簡易サーバーを建てるコマンド
python-local-server() {
  local PORT=8000
  if [ $# -gt 0 ] ; then
    PORT="$@"
  fi
  local PV=$(python -V 2>&1 | cut -d ' ' -f 2 | cut -c 1)
  if [ $PV -eq "3" ] ; then
    python -m http.server ${PORT}
  else
    python -m SimpleHTTPServer ${PORT}
  fi
}
alias py-server=python-local-server

追記したあとは ~/.bash_profile を読み込み直します。

$ source ~/.bash_profile

実行時、以下のようにコマンド入力すれば、任意のポート番号でも実行できるようにしています。

$ py-server 3333
Serving HTTP on 0.0.0.0 port 3333 (http://0.0.0.0:3333/) ...

参考記事

Python2系のバージョン抽出が素直には動かず苦労したため、以下の記事に助けられました。
CentOS7のシェル上でPythonのバージョン(2.7.5など)だけを取得する - Qiita

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
What you can do with signing up
0