2017年Python環境設定 – andaconda/virtualenv/cookiecutter/dotenv

1. Install anaconda / conda

condaによるポータブルなPython環境構築のすすめを参考にすると、(ana)condaが最近の主流とのこと。 下記にアクセスし、各OSのパッケージをダウンロードしてインストール。3系を使います。

https://www.continuum.io/downloads

あとでLinux上で動かす予定なので、なるべく依存関係を作りたくないので、pyenvの導入はしないことにしました。

2. Create virtualenv

Rubyのbundler相当なのが、virtualenvらしいので、仮想環境を作り、その環境に入る。

$ conda create -n kagamibot
$ conda env list
$ source activate kagamibot # deactivate で出る

3. Install packages

基本、conda installでパッケージを入れていくだが、パッケージがないことも多く、そんなときは、conda-forgeを入れるようになるので、最初から追加しておく

$ conda config --add channels conda-forge

とはいえ、virtualenv変更後はpipでも良いので、 conda installでなかったら、pip installみたいな感じ。

$ conda install xxx 
$ pip install xxx

virtualenvでのパッケージはcondaで管理できるので、新しいプロジェクトをコピーするときは、下記のようにexport/importする

conda env export > myenv.yaml  #  conda env create --file myenv.yaml

(参考)http://qiita.com/Hironsan/items/4479bdb13458249347a1

4. Create Project

調べてみるとプロジェクトのディレクトリ構造の自由度が高い。 つまり、人々が各々ディレクトリを作ったり、ファイルを作ったりしている。それがフレームワークを使ってる私みたいな人には、非常に気持ちが悪い。 プロジェクトの雛形が欲しいので、調べるとcookiecutterというのがあるのでそれを使う。

今回はデータサイエンス用のテンプレを使用しているが、テンプレートはpythonだけでなく多言語のもある。 詳しくは、githubのcookiecutterを参照してほしいが、 下記のようなboilerplateができるので自分で考えなくてよいのは非常によい。

├── LICENSE
├── Makefile           <- Makefile with commands like `make data` or `make train`
├── README.md          <- The top-level README for developers using this project.
├── data
│   ├── external       <- Data from third party sources.
│   ├── interim        <- Intermediate data that has been transformed.
│   ├── processed      <- The final, canonical data sets for modeling.
│   └── raw            <- The original, immutable data dump.
│
├── docs               <- A default Sphinx project; see sphinx-doc.org for details
│
├── models             <- Trained and serialized models, model predictions, or model summaries
│
├── notebooks          <- Jupyter notebooks. Naming convention is a number (for ordering),
│                         the creator's initials, and a short `-` delimited description, e.g.
│                         `1.0-jqp-initial-data-exploration`.
│
├── references         <- Data dictionaries, manuals, and all other explanatory materials.
│
├── reports            <- Generated analysis as HTML, PDF, LaTeX, etc.
│   └── figures        <- Generated graphics and figures to be used in reporting
│
├── requirements.txt   <- The requirements file for reproducing the analysis environment, e.g.
│                         generated with `pip freeze > requirements.txt`
│
├── src                <- Source code for use in this project.
│   ├── __init__.py    <- Makes src a Python module
│   │
│   ├── data           <- Scripts to download or generate data
│   │   └── make_dataset.py
│   │
│   ├── features       <- Scripts to turn raw data into features for modeling
│   │   └── build_features.py
│   │
│   ├── models         <- Scripts to train models and then use trained models to make
│   │   │                 predictions
│   │   ├── predict_model.py
│   │   └── train_model.py
│   │
│   └── visualization  <- Scripts to create exploratory and results oriented visualizations
│       └── visualize.py
│
└── tox.ini            <- tox file with settings for running tox; see tox.testrun.org

作成方法は、

$ conda install cookiecutter
$ cookiecutter https://github.com/drivendata/cookiecutter-data-science 
# インタラクティブに質問に答えるかたちでプロジェクト作成

プロジェクト名のディレクトリが作成されるので、そこに入り、パッケージをインストール。

$ cd kagamibot 
# pipのインストール用のrequirements.txtをcondaでインストールする。
$ cat requirements.txt | while read package; do conda install $package; done

5. python-dotenv

Githubに載せたくないAPIのキーなどを管理する cookiecutterのテンプレートにあるのに、requirements.txtにないのでインストール。

$ conda install phython-dotenv

# PROJECT_ROOT/.env
TWITTER_AUTH_TOKEN=xxx

使い方は、下記のような感じ。

import os
from dotenv import load_dotenv, find_dotenv

# find .env automagically by walking up directories until it's found
dotenv_path = find_dotenv()

# load up the entries as environment variables
load_dotenv(dotenv_path)

twitter_auth_token = os.environ.get("TWITTER_AUTH_TOKEN")

以上が、色々なページを参考にして構築した環境です。 こういうのって時間がかかるので、参考になれば幸いです。

macOSのelasticserachの使用メモリサイズの変更方法

気づいたら、2G使ってたので変更。そもそも開発用なのでそんなに必要ない。

$ vi /usr/local/opt/elasticsearch/libexec/config/jvm.options

-Xms256m # from -Xms2g
-Xmx256m # from -Xmx2g

256Mも使ってないけど一応。

Sublime Text 3のSwitch Projectの編集方法・削除方法

消したはずのプロジェクトが残る現象発生。 削除するのは現セッションのRecent workspacesから取り除く必要あり。

Sublime Textを閉じたあとに

$ vi ~/Library/Application\ Support/Sublime\ Text\ 3/Local/Session.sublime_session

で、recent workspacesを消す。

    "workspaces":
    {
        "recent_workspaces":
        [
            "/Users/shohey1226/gdrive/st_projects/Gauss.sublime-workspace",
            "/Users/shohey1226/gdrive/st_projects/Personal.sublime-workspace"  
        ]
    }

[React Native] HTTP requestのRetryを実装する

Mediumに英語のエントリRetry POST request when it’s failed on React Nativeを書いた内容と同じですが、地下鉄で地下に潜るとreact-native-oauthmakeRequestが失敗するケースが発生しました。Twitterの2つ目の投稿が投げられていなかったり、FBへの投稿も落ちていました。そこで、リトライするコードを書きました。

Async Retryを使います。これはnode-retryをラップしたもので、例がシンプルで良さそうだったので使います。(async/awaitの文法にも慣れているので)

 $ cd PROJECT_DIR
 $ yarn add async-retry # or npm install async-retry --save

問題なくインストールできます。そして、コードは、下記のような感じ。

import retry from 'async-retry'

...

  async _tweetWithRetry(text){
    return await retry(async () => {
      let encodedText = encodeURIComponent(text);
      const endpoint = `https://api.twitter.com/1.1/statuses/update.json?status=${encodedText}`;
      const res = await manager.makeRequest('twitter', endpoint, { method: 'post' });
      return res;
    }, {
      retries: 5
    });
  },

2つ目の引数にnode-retryのオプションを書いてくイメージです。今回はエラーハンドリングは特にしないで5回リトライする単純なコードです。iphoneのデベロッパーのところにある”Very bad network”で試したところ、コンソールに数回トライしているのを確認しました。(Testをうまく書けるのかな。。)

以上、リトライを実装したい方は参考にしてみてください。