K4750.NET

Matplotlib on Ubuntu on Windows

Python 用グラフ描画ライブラリ「Matplotlib」を Ubuntu on Windows 環境で動かしてみた。


1.Ubuntu on Windows のインストール

まずは「Windows Subsystem for Linux」をインストール。その後、開発者モードを有効化の上、Bash+Ubuntuをインストールする。以下がとても詳しい。

Bash のインストールが終わったら、上記サイトを参考に Bash 上で初期設定およびパッケージの最新化を行う。

$ sudo sh -c 'echo 127.0.1.1 $(hostname) >> /etc/hosts'
$ sudo sed -i -e 's%http://.*.ubuntu.com%http://ftp.jaist.ac.jp/pub/Linux%g' /etc/apt/sources.list
$ sudo apt update
$ sudo apt upgrade

それにしても、、Windows上でネイティブなLinuxディストリビューションが動作するなんて・・・なんて キモチワルイ 驚きな!


2.各種 Ubuntu パッケージのインストール

Matplotlib のインストールに必要な各種パッケージをインストールする。Python3 を使いたいので、基本的には Python3 用をインストールする。

$ sudo aptitude install python3-pip
$ sudo aptitude install libfreetype6 libfreetype6-dev
$ sudo aptitude install pkg-config
$ sudo aptitude install cython
$ sudo aptitude install python3-tk

3.Python 用モジュールのインストール

Python3 用の各種モジュールは pip3 を使ってインストールする。

$ sudo pip3 install setuptools
$ sudo pip3 install ipython
$ sudo pip3 install cython
$ sudo pip3 install pandas
$ sudo pip3 install matplotlib

なんか時々ビルドに失敗しているように見えるが・・・試しに ipython を起動してみる。

$ ipython
Python 3.4.3 (default, Sep 14 2016, 12:36:27)
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

ipython は問題なく起動するようだね!


4.Matplotlib 動作確認

肝心な Matplotlib は・・・

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5,4,3,2,1])
plt.savefig('graph.png')

ファイル「graph.png」が作れたようだ。

作成した graph.png を Windows から開いてみる。Ubuntu 環境の home ディレクトリは、例えば k4750 ユーザだと、以下のような場所に存在する。

C:\Users\k4750\AppData\Local\lxss\home\k4750
Matplotlib で描画したグラフその1

\(^o^)/


5.notebook は動作せず・・・

なお、、ブラウザから ipython を使うための notebook モジュールを試してみたが・・・

$ sudo pip3 install notebook

インストールはできた(?)けど、ブラウザからアクセスして対話的に python 言語を処理させようとするも、うまく動作せず^^; 同じ手順で、Ubuntu on VMWare でインストールしたら問題なく動作したので、、Windows 上では(今のところ)無理ってことなのかな。

DjangoインストールからHelloWorldまで

Python で実装された Web アプリケーションフレームワーク「Django」で Hello, World! を表示するまでのメモ。


1.前提

Djangoを動作させる環境は以下のとおり。

  • Ubuntu 14.04 LTS
  • Python 3.4.3
  • Apache 2.4.7

2.インストール前準備

Django の INSTALL 方法を確認し・・・

# wget https://www.djangoproject.com/m/releases/1.10/Django-1.10.2.tar.gz
# tar xvfz Django-1.10.2.tar.gz; cd Django-1.10.2
# more INSTALL

いざインストールコマンドをたたくと「setuptools」というモジュールがないことが分かったので・・・

# python setup.py install
Traceback (most recent call last):
  File "setup.py", line 5, in 
    from setuptools import find_packages, setup
ImportError: No module named 'setuptools'

Python3 用の setuptools をインストールする。

# aptitude search setuptools
...
p   python3-setuptools     - Python3 Distutils Enhancements
p   python3-setuptools-git - plugin for setuptools that enables git integration
v   python3.4-setuptools   -
# aptitude install python3-setuptools

3.インストール

Django の setup.py を使ってインストールを実行する。

# python setup.py install
...
Installed /usr/local/lib/python3.4/dist-packages/Django-1.10.2-py3.4.egg
Processing dependencies for Django==1.10.2
Finished processing dependencies for Django==1.10.2

Django のバージョンを確認してみる。

# python
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
1.10.2

以下の方法でも確認が可能だ。

# python -m django --version
1.10.2

4.開発用サーバ(Development server)の動作確認

本家のチュートリアル を参考に、まずは Django 付属の開発用サーバを動かしてみる。

最初に「プロジェクト」を作る。名前は「mysite」とする。

$ cd /pathto/sitedir/
$ django-admin startproject mysite
$ find
.
./mysite
./mysite/manage.py
./mysite/mysite
./mysite/mysite/settings.py
./mysite/mysite/__init__.py
./mysite/mysite/urls.py
./mysite/mysite/wsgi.py

作成した「mysite」へ移動し開発用サーバを起動する。

$ cd mysite
$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

October 08, 2016 - 02:14:31
Django version 1.10.2, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

lynx http://127.0.0.1:8000/ を実行して、動作しているか確認してみる。

It worked!

Congratulations on your first Django-powered page.

   Of course, you haven't actually done any work yet. Next, start your first app by running python manage.py startapp [app_label].

   You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!

ページは表示された。先ほど開発用サーバを起動したコンソールを見てみると・・・

...
Quit the server with CONTROL-C.
[08/Oct/2016 02:19:09] "GET / HTTP/1.1" 200 1767

アクセスログが出力されている。問題なく動作しているようだ。一旦Ctrl + Cで開発用サーバを停止しておく。


5.Django で Hello, world!

開発用サーバの動作が確認できたので、Django アプリケーション「helloworld」を作ってみる。

$ python manage.py startapp helloworld
$ find
./helloworld
./helloworld/admin.py
./helloworld/models.py
./helloworld/migrations
./helloworld/migrations/__init__.py
./helloworld/apps.py
./helloworld/views.py
./helloworld/tests.py
./helloworld/__init__.py

まず、ファイル helloworld/views.py を以下の内容へ書き換え、HTTPレスポンスとして「Hello, world!」を返す「index」関数を定義する。

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world!")

続いて、helloworld/urls.py を以下の内容で新たに作成し、URLのパターンと「index」関数の紐づけを定義する。

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

さらに、mysite/urls.py を編集する(1行目書き換え、5行目追記)。ここではURLパターンと上記「helloworld」アプリケーションとの紐づけを定義している。

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^helloworld/', include('helloworld.urls')),
    url(r'^admin/', admin.site.urls),
]

再度、開発用サーバを起動し・・・

$ python manage.py runserver

lynx http://127.0.0.1:8000/helloworld/ を実行してみる。

   Hello, world!

\(^o^)/


6.Apache + mod_wsgi + Django で Hello, world!

開発用サーバをインターネットに晒すわけにはいかないので、Apache 経由で動作するよう設定する。

Apache 経由で Django を使用するためには、橋渡しとなる Apache モジュール「mod_wsgi」が必要になる。mod_wsgi は Ubuntu 用のパッケージとして提供されていないように見えるので、、mod_wsgi をコンパイル・インストールするのに必要な各種パッケージをまずはインストールする。

# aptitude install apache2-dev
# aptitude install python3-dev

次いで、コンパイル・インストール。作業には このあたり が参考になる。

$ wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.5.7.tar.gz
$ tar xvfz 4.5.7.tar.gz; cd mod_wsgi-4.5.7
$ ./configure
$ make
$ sudo make install

Apache の httpd.conf に以下を追記する(「/pathto/sitedir」は適宜読み替えてください)。

LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so

WSGIScriptAlias /django /pathto/sitedir/mysite/mysite/wsgi.py
WSGIPythonPath /pathto/sitedir/mysite

<Directory /pathto/sitedir/mysite/mysite>
  <Files wsgi.py>
    Allow from all
    Order deny,allow
  </Files>
</Directory>

Apache を再起動し・・・

$ sudo service apache2 restart

lynx http://app.k4750.net/django/helloworld/ を実行してみる。

   Hello, world!

\(^o^)/


7.DEBUGモードの無効化

インターネットに晒す場合のもう一つの注意点として、DEBUGモードがある。先ほど作成した mysite プロジェクトの mysite/settings.py を見ると・・・

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

DEBUGモードが有効(DEBUG = True)になっているので、無効化する。その際「ALLOWED_HOSTS」も設定する必要があるようだ(設定しないと、全てのページで「Bad Request (500)」表示されるようになるハズ)。

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['app.k4750.net']

これで、Djangoアプリケーションをインターネットへ晒す準備が整った。\(^o^)/