Entries from 2009-10-01 to 1 month

PythonでGUIDを生成する

PythonでGUIDを生成する方法。 標準ライブラリのuuidモジュールを使えば良い。 >>> import uuid >>> str(uuid.uuid4()) '4155f6f5-fa9e-4669-87a1-7ee43a4a70c5'

Google App Engineでエラーが

久しぶりにGoogle App Engineでdev_appserver.pyを起動すると以下のようなエラーが出た。 INFO 2009-10-21 00:00:00,375 py_zipimport.py:108] zipimporter('C:\\Python25\\lib\\site-packages\\simplejson-2.0.9-py2.5-win32.egg', 'simplejson\\') Traceba…

Pythonでバイトコードを書き換える

Pythonでバイトコードを書き換える方法。co_codeがreadonlyなのでcodeオブジェクトをわざわざ作り直している。 以下の例では乗算を累乗に変更している。 import new import opcode def hoge(n): return 2 * n hoge(16) #=>32 piyo = hoge.func_code.co_code.…

htmlentitydefs

こんなモジュールがあるのか。 >>> import htmlentitydefs >>> htmlentitydefs.name2codepoint['copy'] 169 >>> htmlentitydefs.codepoint2name[ord('&')] 'amp'

turtleモジュールでturtle graphics

面白い。

PythonでBrainfuckコンパイラ

PythonでBrainfuckコンパイラを書いた*1。MS-DOS上で実行可能な.COMファイルを出力する。32ビットWindows上で動くはず。 helloworld++++++++>+++++++++++>+++++.>++.+++++++..+++.>-.------------.+.">*2がコンパイル/実行出来ることは確認した。 最適化など…

str.endswithには配列も指定できる

Pythonのstr.endswithには配列も指定できることを知った。 path.endswith(('/','\\'))

様々な書き方

変数pathが、使用しているOSのファイルパスの区切り文字で終わっていなければ区切り文字を終端に付加するプログラム。 import os # 1 if path.endswith(os.path.sep): path += os.path.sep # 2 path += os.path.sep if path.endswith(os.path.sep) else '' #…

__new__

Python 2.6.3 (r263rc1:75186, Oct 2 2009, 20:40:30) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class Hoge(object): ... def __new__(self): ... return 0 ... >>> Hoge() 0