Python覚書

ソースファイルのエンコード指定

# coding:UTF-8

エントリーポイントの書き出し

if __name__ == "__main__":
	print "Hello Entry Point."

ディレクトリの列挙

import os

def getdirs(path):
	dirs=[]
	for item in os.listdir(path):
		if os.path.isdir(os.path.join(path,item)):
			dirs.append(item)
	return dirs

コマンドラインパーサー

from optparse import OptionParser

usage = "usage: %prog [options] keyword"
parser = OptionParser(usage)

parser.add_option(
  "-ショート名", "--ロング名",
  dest="プロパティ名",
  type="型(stringとか)",
  default="デフォルト値(省略化)",
  help="説明"
)
parser.add_option(
  "-n", "--long",
  dest="prop",
  default=True,
  action="store_false", #オプションが指定された時にdestにfalseを設定する
  help="説明"
)

(options, args) = parser.parse_args()

# エラー処理
if len(args) > 0:
    # 処理できないargsが有ったので、エラーメッセージを表示しプログラムを終了
    parser.error("requires keyword. Try [-h] option to see help.")

#使い方
print options.プロパティ名

参考
http://docs.python.jp/2/library/optparse.html

ProtocolBuffer <=> Dictionary

https://github.com/Livefyre/protobuf-to-dict

環境変数の取得

#type 1
val = os.environ.get("ENV_VARIABLE") 
if val != None
    print val

#type 2
val = os.environ.get("ENV_VARIABLE", "DefaultVal") 

#type 3
val = os.environ["ENV_VARIABLE"]

#Dictionary的にアクセス
for k, v in os.environ.items():
    print("{key} : {value}".format(key=k, value=v))

Stringのフォーマット

"Hello {0}".format("World")

"Hello {what}".format(what="World")

参考
http://docs.python.jp/2/library/stdtypes.html?highlight=format#str.format

外部プロセスの呼び出し

import subprocess
cmd_with_args = "notepad.exe target.txt"
try:
  subprocess.call( cmd_with_args, shell=True )
except:
  print "cmd error %s" % cmd_with_args

その他参考
http://doloopwhile.hatenablog.com/entry/20100614/1276489378

Pythonで1Kとか1Gとかを数値にする(with regexのサンプルにもなるかなー)

http://mataro777.hateblo.jp/entry/2014/02/26/115853

ディレクトリをZip化

基本的には一気に出来ないので、ループで回して処理。

http://coreygoldberg.blogspot.jp/2009/07/python-zip-directories-recursively.html

ファイルパスの正規化と、環境に合わせたパスの取得

realpathはWindows+Cygwinの場合「c:\hogehgoe」を「/cygdrive/c/hogehoge」とかに変換する。

os.path.normpath( os.path.realpath(path) )

WebサーバーからHttpでファイルのダウンロード

import urllib
urllib.urlretrieve ("http://パス", "セーブするファイル名.txt")

参考
http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python

Iniファイルの任意のセクションのパラメータを書き換える

# coding:UTF-8

import re
import sys
import fileinput

if __name__ == "__main__":

	trgFile = sys.argv[1]
	trgSection = sys.argv[2]
	trgParam = sys.argv[3]
	newValue = sys.argv[4]

	rSection = "^\s*(?P<section>\[\S*\])\s*(?P<comment>;.*$)?"
	rParameter = "^\s*(?P<param>{0})\s*=\s*(?P<value>\S*)\s*(?P<comment>;.*$)?".format(trgParam)

	rSec = re.compile( rSection )
	rPrm = re.compile( rParameter )

	inSection = False
	for line in open(trgFile):
		line = line.strip()
		if line != "":
			secRes = rSec.search(line)
			if secRes != None:
				if secRes.group("section") == trgSection:
					inSection = True
				else:
					inSection = False
				print line
				continue

			if inSection == True:
				res = rPrm.search(line)
				if res != None:
					if res.group("value") != newValue:
						print ";---Modified by tool---"
						print ";{0}".format(line)
						print u"{0} = {1} {2}".format(res.group("param"), newValue, res.group("comment") if res.group("comment") != None else "")
					else:
						print line
				else:
					print line
			else:
				print line
		else:
			print line