モジュールのアップデート

pip list -o

とすると,outdated なパッケージ一覧が出ます. 一度インストールしたパッケージをアップグレードする場合には、-U (--upgrade)を使います。

% pip install scipy -U

anacondaのアップデート

conda update condo
conda update anaconda 
conda update --all

Python32bit と 64bitの共存

** フォルダの新規作成
# 格納親ディレクトリの
RESULT_DIR_ROOT = '(tmp)TF_Average_txt'
if os.path.exists(RESULT_DIR_ROOT):
   shutil.rmtree(RESULT_DIR_ROOT)
   os.mkdir(RESULT_DIR_ROOT)
else:
   os.mkdir(RESULT_DIR_ROOT)

Python PATHの設定

64bit版と32bit版を共存させる。ターミナルではデフォルトで32bit版を使いたい。 そこで、システム環境設定からPYTHONPATHを変更する

PYTHONPATHの設定

set PYTHONPATH=%PYTHONPATH%;C:\Anaconda2_32bit;
set PYTHONPATH=%PYTHONPATH%;C:\Users\0160929\AppData\Local\Continuum\Anaconda;

SYSTEM PATHへ追加

PATH = %PATH%;C:\Users\0160929\AppData\Local\Continuum\Anaconda\Lib\site-packages\PyQt4;C:\Users\0160929\AppData\Local\Continuum\Anaconda;C:\Users\0160929\AppData\Local\Continuum\Anaconda\Scripts;
PATH = %PATH%;C:\Anaconda2_32bit;C:\Anaconda2_32bit\Scripts;
PATHも通す
C:\Anaconda2_32bit; 
C:\Anaconda2_32bit\Scripts;
C:\Anaconda2_32bit\Library\bin

ファイルフォルダ操作

フォルダ内のフォルダ一覧を取得

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)
UPLOAD_FOLDER_NAME = 'image' 
PHISICAL_ROOT = os.path.abspath('./')
ALLOWED_EXTENSIONS = set(['.PNG', '.png', '.JPG', '.jpg', '.jpeg', '.gif'])
UPLOAD_FOLDER = os.path.join(PHISICAL_ROOT, UPLOAD_FOLDER_NAME)

iPython Notebook

起動方法

$ipython notebook

iPythonおまじない

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

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

nbviwer

.ipynbファイルをgistかgithubにアップロードして置くことで、vbviwerによりwebページとして表示することができる。

s-nbviewer.jpg

→nbviwer

時間計測

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

PyInstaller?

pyinstaller SimpleTextEditor.py --onefile --noconsole
  1. --onefile : .exeを一つのファイルにする
  1. --windowed, -w : コマンドプロンプト非表示
  1. -i<appicon.icon>, --icon=<appicon.icon> : プログラムのアイコンを設定
  1. --noconsole : コマンドプロンプト非表示

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

 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: ''

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

→組み込み例外

       # ファイルが存在しない場合は返却
       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

例外処理のよい例・悪い例

まずは悪い例

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

py2exe

→http://www.py2exe.org/

→py2exe Python スクリプトからスタンドアロンのWindowsプログラムへの変換

→Py2exe 利用ノート

→Pythonで単体で動くバイナリを作ろう!

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

platformを調べる

################# 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

opencv.jpg

初心者ミス

Pythonをコーディングしている時に発生する初心者ミスをまとめておく。

型判定・型判別

PythonでC言語のDLLを呼び出す

詳しくはこちら

ダミーのcファイル : dll.c

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の呼び出し確認用コード

	#!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? コードテンプレート

#! coding:utf-8
"""
${NAME}

Created by ${USER}  (${DATE} ${TIME})
"""

def main():
   pass

if __name__ == "__main__":
   main()

パスの取り扱い

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

os別のエンコード対策はこちら https://gist.github.com/peace098beat/696e741f941801ed705e

   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

エクスプローラを開く

       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)
# 日本語Path対応
       # OSを判定し、文字コードを取得
       if os.name is 'nt':
           code = 'cp932'
       else:
           code = 'utf-8'
       # UNICODE文字列から、OSに合わせてエンコード:文字化け回避
       filename_ = filename.encode(code)
       # エクスプローラをオープン
       cmd_file = 'explorer /select, "%s"' % (os.path.normpath(filename_))
       Popen(cmd_file)

辞書ソート

               # -- ソート結果の表示
               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)

文字化け対応(日本語Path)

 # OSを判定し、文字コードを取得
import os
 if os.name is 'nt':
   code = 'cp932'
else:
   code = 'utf-8'
# 文字列(Unicode)をバイト列へエンコード
filename_ = filename.encode(code)

PyAudio?で音量を変える

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

PythonでWindowsAPIを使う

# ダウンロードする
pyHook-1.5.1-cp27-none-win_amd64.whl
# ダウンロードしたフォルダでShift+右クリック>コマンドプロンプトを開く
pip install pyHook-1.5.1-cp27-none-win_amd64.whl
http://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/
import pythoncom, pyHook

def OnMouseEvent(event):
   # called when mouse events are received
   print 'MessageName:',event.MessageName
   print 'Message:',event.Message
   print 'Time:',event.Time
   print 'Window:',event.Window
   print 'WindowName:',event.WindowName
   print 'Position:',event.Position
   print 'Wheel:',event.Wheel
   print 'Injected:',event.Injected
   print '---'
# return True to pass the event to other handlers
   return True
# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.MouseAll = OnMouseEvent
# set the hook
hm.HookMouse()
# wait forever
pythoncom.PumpMessages()

タスクトレイアプリ

http://moco.sakura.ne.jp/python/pyside-でタスクトレイアプリケーション作成/

pythonでのWindowsサービスの書き方 http://masahito.hatenablog.com/entry/20110511/1305107553

QThreadでストレスフルな生活を

http://melpystudio.blog82.fc2.com/blog-entry-125.html

ファイル名をTimeStamp?にする

filename_base = datetime.datetime.now().strftime("%Y%m%d_%H%M")
filename = os.path.abspath(os.path.join(DIRPATH_LOGFILE, filename_base) + '.csv')

文字コーーーーーード

UNICODE = String 文字! それ以外は(例utf-8)はバイトコード!!

# 解析結果をstring(UNICODE)型へキャスト
print_str = str(token).decode('utf8')
# Unicode をバイトコードへエンコード
code = 'cp932' or 'utf-8'
out_word = words.encode(code)

ネットワークリソースのダウンロード

# Network Resourse Download
import urllib 
url = 'http://localhost/recome/(ed)REC_A01_14B330_Mic7.wav'
path = 'download.wav'
urllib.urlretrieve(url, path)

累乗計算

   def ruijou(self, x):
       from numpy import log2, floor
       y0 = log2(x)
       # 最小t
       p = floor(y0)
       return int(2 ** p)
トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS