CLOVER🍀

That was when it all began.

Pythonの標準モジュールを使って、コマンドラインからHTTPサーバーを起動する

Pythonに標準モジュールとしてHTTPサーバーがあり、コマンドから簡単に使えることはなんとなく知っていたのですが、
実際に使ってみると知っていると便利だなーと思ったのでメモ。

こういう時に、使うといいのではないのでしょうか。

  • 追加のプログラムのインストールや、ソースコードを作成することなくHTTPサーバーを使いたい
    • Python自体がインストールされていることが前提、という点は除きます…
  • 動的な振る舞いは必要なく、あくまでファイルシステム上で静的に動作するHTTPサーバーであればよい

Python 3とPython 2でそれぞれ異なるようなので、それぞれに書いていきます。

Python 2が入っているのは、まだLinuxなどにデフォルトでインストールされているのは2系だから、ですね。

いずれも「-m」オプションを使って、モジュールを使用して起動します。

Python3の場合

環境。

$ python3 -V
Python 3.6.5

起動。

$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

「0.0.0.0」および8000ポートにバインドされ、カレントディレクトリをドキュメントルートとしたHTTPサーバーが起動します。

アクセスすると、標準出力にアクセスログが出力されます。

127.0.0.1 - - [29/Aug/2018 02:59:54] "GET / HTTP/1.1" 200 -

ディレクトリに対してアクセスすると、「index.html」および「index.htm」を探索してくれるようです。

止める時は、Ctrl-cで。

引数は、ポートと、バインドするIPアドレスを指定することができます。

ポート指定。

$ python3 -m http.server 9000
Serving HTTP on 0.0.0.0 port 9000 (http://0.0.0.0:9000/) ...

バインドするIPアドレス指定。指定は、「--bind」で行います。

## 「--bind」のみ
$ python3 -m http.server --bind 127.0.0.1
Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) ...


## ポート指定と合わせて
$ python3 -m http.server 9000 --bind 127.0.0.1
Serving HTTP on 127.0.0.1 port 9000 (http://127.0.0.1:9000/) ...

デフォルトで「0.0.0.0」にバインドされるので、アクセス可能な範囲を絞りたい時に使うのでしょうけれどね。

詳しくは、ドキュメントを。

http.server can also be invoked directly using the -m switch of the interpreter with a port number argument. Similar to the previous example, this serves files relative to the current directory:

python -m http.server 8000
By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. For example, the following command causes the server to bind to localhost only:

python -m http.server 8000 --bind 127.0.0.1
バージョン 3.4 で追加: --bind 引数が導入されました。

https://docs.python.org/ja/3.6/library/http.server.html#module-http.server

Python 2の場合

環境。

$ python -V
Python 2.7.15rc1

こちらは、Python 3の時とはモジュール名が変わります。

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...

アクセスするとアクセスログが出力されることや、停止がCtrl-cであることは、Python 3の時と同じです。

カレントディレクトリがドキュメントルートとして扱われることや、ディレクトリに対するアクセスが「index.html」および
「index.htm」に対して読み込みが行われようとすることも同じです。

ポート指定も可能。

$ python -m SimpleHTTPServer 9000
Serving HTTP on 0.0.0.0 port 9000 ...

こちらは、「--bind」相当もものはなさそうですが、まあ困らないでしょう。

https://docs.python.jp/2/library/simplehttpserver.html

覚えておきましょう。