**モジュールのアップデート [#k6b5fc40]
 pip list -o
とすると,outdated なパッケージ一覧が出ます.
一度インストールしたパッケージをアップグレードする場合には、-U (--upgrade)を使います。

 % pip install scipy -U

anacondaのアップデート
 conda update condo
 conda update anaconda 
 conda update --all

** Python32bit と 64bitの共存 [#a5cc0411]
- (状態) Anaconda64bitがプライマリとしてインストール
- Anacondaの32bitをC直下にインストール
- PyCharm上でconnsoleを開くと64bit。
- 下batのPATH部分だけをコンソールに走らす。
PythonPathを変えるbat
 @echo off
 ::: 実行前の準備 
 set EXEC_DIR=%~dp0
 ::: python
 PATH=C:\Anaconda2_32bit;C:\Anaconda2_32bit\Scripts;%PATH%
 cd %EXEC_DIR%
 PROMPT #$S
 %ComSpec%

** ファイルフォルダ操作 [#v0573099]
*** フォルダ内のフォルダ一覧を取得 [#g1d9b436]
 BASE_DIR = os.path.dirname(sys.argv[0])
 SEARCH_PATH = os.path.join(BASE_DIR, '*')
 SOURCE_DIR =[dir for dir in glob.glob() if os.path.isdir(dir)]
 sys.path.append(os.path.join(BASE_DIR, './GolfClassification/FiSig/'))

 file_name = os.path.basename(filepath)


** iPython Notebook [#g6ea7e98]
起動方法

 $ipython notebook

** iPythonおまじない [#lb7e6868]
iPythonとmatplotlibを使ってグラフを描画するときのおまじない。

 %matplotlib inline
 import numpy as np
 import matplotlib.pyplot as plt


** nbviwer [#h75d005f]
.ipynbファイルをgistかgithubにアップロードして置くことで、vbviwerによりwebページとして表示することができる。
#ref(s-nbviewer.jpg,,50%)
[[→nbviwer>http://nbviewer.ipython.org/]]

** 時間計測 [#x64e078e]

    import time
    start = time.time()
    print(">>  Finish Analys :{0}".format(time.time() - start))

** PyInstaller [#qde9d4cd]

 pyinstaller SimpleTextEditor.py --onefile --noconsole

+ --onefile : .exeを一つのファイルにする

+ --windowed, -w : コマンドプロンプト非表示

+ -i<appicon.icon>, --icon=<appicon.icon> :  プログラムのアイコンを設定

+ --noconsole : コマンドプロンプト非表示

*** エラー  IOError: [Errno 22] invalid mode ('rb') or filename: '' [#s77fd814]

  File "C:\Users\fifi\Anaconda\lib\site-packages\PyInstaller\build.py", line 796, in cacheDigest
    data = open(fnm, "rb").read()
 IOError: [Errno 22] invalid mode ('rb') or filename: ''

- 見つけた対策 1

[[http://codedmi.com/questions/785472/pyinstaller-errno-22]]

	Well reinstalled pywin32 and now working :S just going go with it
	Just spent the better part of a week tracking this bug down. Was getting this error just by trying to compile a script importing numpy or pandas and printing "hello world".
	Eventually fixed it by running command prompt as administrator... Yeah.
	Hope this helps some poor desperate soul.
	I had the same issues but found these other solutions did not fix the problem. I did however find a fix as follows:
	First, my situation may be a little different to the OP as I'm using the Anaconda Python distribution on Windows 7, and used the conda command line too to install pywin32, and then used pip to install pyinstaller.
	I found the same IOError was preceded by this earlier error message in the pyinstaller output log:
	ImportError: No system module 'pywintypes' (pywintypes27.dll)  
	The solution that fixed both errors was to copy the DLL files:
	pywintypes27.dll
	pythoncom27.dll 
	sitting in: C:\<anaconda-dir>\Lib\site-packages\win32
	to C:\<anaconda-dir>\Lib\site-packages\win32\lib
	Where <anaconda-dir> will either be your root Anaconda directory:
	C:\Users\<username>\AppData\Local\Continuum\Anaconda\ by default,
	or an environment you have set up e.g.
	C:\Users\<username>\AppData\Local\Continuum\Anaconda\envs\<environment-name>
	A came across this answer thanks to Tompa here, who found it solved a similar problem in py2exe.


** エラーの発行 raise [#ya1a635b]

[[→組み込み例外>http://docs.python.jp/2/library/exceptions.html#exceptions.EnvironmentError]]

        # ファイルが存在しない場合は返却
        if not os.path.exists(filepath):
            # raise StandardError("File is not exist %s" % (filepath))
            return

 try:
     # ファイルオープン
     data = wave.open(filepath, 'rb')
 except IOError:
     raise StandardError("Cant file load %s" % (filepath))
 else:
     # 正常時の処理
 finally:
     pass

** 例外処理のよい例・悪い例 [#hc442a98]

まずは悪い例

 def get_status(file):
    if not os.path.exists(file):
        print "file not found"
        sys.exit(1)
    return open(file).readline()

これだと、open(file)の際に出たエラーを捕まえていない。

よい例

 def get_status(file):
    try:
        return open(file).readline()
    except EnvironmentError as err:
        print "Unable to open file: {}".format(err)
        sys.exit(1)

** LookupError: unknown encoding: windows-31j [#r75276b1]

- Pycahrmの設定で、文字コード設定をUTF=8に変更する

** py2exe [#m8b6bf68]

[[→http://www.py2exe.org/>http://www.py2exe.org/]]

[[→py2exe Python スクリプトからスタンドアロンのWindowsプログラムへの変換>http://www.python.jp/Zope/Zope/articles/tips/py2exe]]

[[→Py2exe 利用ノート>https://showa-yojyo.github.io/note/python-py2exe.html]]

[[→Pythonで単体で動くバイナリを作ろう!>http://python.matrix.jp/pages/modules/py2exe.html]]

どうもPySideを使っているとPyInstallerが上手くexe化してくれない。しかたがないので、py2exeをつかってみる。

- 日本語で読むならこちら
-- 非常に丁寧に説明がされており、概要をしるにはぴったり。
[[PYINSTALLERの遅さにがっかりしてPY2EXEにしたら爆速で驚いた件>http://april.fool.jp/blogs/2014/10/python-pyinstaller%E3%81%AE%E9%81%85%E3%81%95%E3%81%AB%E3%81%8C%E3%81%A3%E3%81%8B%E3%82%8A%E3%81%97%E3%81%A6py2exe%E3%81%AB%E3%81%97%E3%81%9F%E3%82%89%E7%88%86%E9%80%9F%E3%81%A7%E9%A9%9A%E3%81%84/]]
-- 公式のチュートリアル(英語)。まずはHelloworldをexe化するべし。
[[py2exe tutorial>http://www.py2exe.org/index.cgi/Tutorial]]


** platformを調べる [#of715af6]

 ################# if PySide not installed inside houdini libs
 import platform
 
 if platform.system() == 'Windows':
    sp = 'C:/Python27/Lib/site-packages'
    if not sp in sys.path:
        # if os.path.exists(sp):
        sys.path.insert(0, sp)
        print sp


** OpenCV for Python [#a9fc4196]
- 参考資料
[[OpenCV Computer Vision with Python>http://www.amazon.co.jp/OpenCV-Computer-Vision-Python-Joseph-ebook/dp/B00CHMQ8L4/ref=sr_1_cc_2?s=aps&ie=UTF8&qid=1441677744&sr=1-2-catcorr&keywords=python+opencv]]

#ref(opencv.jpg)

** 初心者ミス [#l781acba]
Pythonをコーディングしている時に発生する初心者ミスをまとめておく。
- def__init(self)
-- 正しくは、def __init__(self)。意外と良くやってしまう。

**型判定・型判別 [#l8b1bc1f]
- type か isinstanceを使う
-- if type(a):
-- if isinstance(a, int):

**  PythonでC言語のDLLを呼び出す [#t66c4af7]
[[詳しくはこちら>https://gist.github.com/peace098beat/7837b71b83e5476e1cc1]]

*** ダミーのcファイル : dll.c [#p457d348]
 void printdll(double * a_ary, int a_ary_length) {
	int i;
	for (i = 0; i < a_ary_length; i++) {
		// printf("a_ary[%d] = %d\n", i, a_ary[i]);
		a_ary[i] = a_ary[i]*a_ary[i];
	}
 }

*** dllの呼び出し確認用コード [#oba2387b]

	#!coding: utf-8
	# ***************************************************
	#
	#	main.py
	#		dllの呼び出し確認用コード
	#
	# ***************************************************
	from ctypes import *

	# 標準dllの呼び出し(テスト)
	# cdll.msvcrt.printf('Hello, world!\n')
	# cdll.msvcrt.printf('double value: %f\n', c_double(3.14))

	# 自作dllの呼び出し
	userdll = windll.LoadLibrary('rcadll.dll')

	# 定数
	FRAME_SIZE = 1024

	# 配列のオブジェクトを作成する
	# C言語で言うならば、array_aype = (int*)malloc(sizeof(int) * FRAME_SIZE)
	ArrayType = c_double * FRAME_SIZE
	stft_data = ArrayType()

	ResultData = c_double * 5
	res_data = ResultData()

	# 作成した配列に値を入れる
	for i, val in enumerate(stft_data):
	    stft_data[i] = i

	# 自作のdllを呼び出す(値を2乗する関数)
	# ポインタを渡している格好になる.
	userdll.printdll(stft_data, FRAME_SIZE)


** PyCharm コードテンプレート [#z279d0be]

 #! coding:utf-8
 """
 ${NAME}
 
 Created by ${USER}  (${DATE} ${TIME})
 """
 
 def main():
    pass
 
 if __name__ == "__main__":
    main()


** パスの取り扱い [#nd6582f6]
 os.path.dirname(sys.argv[0])
 os.path.normpath()
 os.path.join()
 os.path.exists()
 path, ext = os.path.splitext(target_filepath)
 basename = os.path.basename(path)

** csv writer [#p762241a]

    def save(self, filename=None):
        if filename is None:
            filename = 'result.csv'
        filename = os.path.normpath(filename)
        with open(filename, 'wb') as f:  #'wb'じゃないと変な改行入る。
            writer = csv.writer(f, delimiter=',')
            for i in range(len(self.wav_filepath_s)):
                writer.writerow([self.wav_filepath_s[i]])
            for i in range(len(self.wav_filepath_s)):
                writer.writerow([os.path.basename(self.wav_filepath_s[i])])
            writer.writerow(['eval (1)', ])
            for i in range(len(self.wav_filepath_s)):
                writer.writerow(self.result_table[i])
csvが文字化けしたら。。(現時点では意味が分からない)
http://d.hatena.ne.jp/bonlife/20070831/1188564822
** エクスプローラを開く [#u12ee4fe]
        import subprocess
        cmd_dir = 'explorer "%s"' % (os.path.normpath(os.path.dirname(filename)))
        subprocess.Popen(cmd_dir)
        cmd_file = 'explorer /select, "%s"' % (os.path.normpath(filename))
        subprocess.Popen(cmd_file)


** 辞書ソート [#h8206c4e]
                # -- ソート結果の表示
                sum_list = [sum(ary) for ary in result_table]
                name_list = [os.path.basename(path) for path in self.wav_filepath_s]
                summary = zip(name_list, sum_list)
                summary =  sorted(summary, key=itemgetter(1))
                # summary = sorted(summary, key=lambda x:x[1])
                writer.writerows(summary)

** PyAudioで音量を変える [#edc1a5e9]
PyEQが参考になる。
バイナリデータをPCMに変えて、
PCMをfloatに変換
ブースト処理をかけて
float->PCM->binaryに戻すとできる。
http://flamingoengine.googlecode.com/svn/trunk/backends/audio/pyaudio_mixer.py

https://mail.python.org/pipermail/tutor/2012-September/091529.html

まとめ
https://gist.github.com/peace098beat/e00e30e10cb6b8ff753c

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS