tag:blogger.com,1999:blog-18928065097437581282024-02-07T13:06:20.013+09:00PythonメモOSはUbuntu 9.04<br>
PythonはPython 2.6.2Unknownnoreply@blogger.comBlogger110125tag:blogger.com,1999:blog-1892806509743758128.post-39926614692048709512010-01-10T00:20:00.020+09:002010-03-05T15:52:44.359+09:00オブジェクトを比較し -1, 0, 1 を返す組み込み関数の cmp を使う<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_comment"># 戻り値は数値
# x < y なら -1, x == y なら 0, x > y なら 1</span>
i = cmp(<span class="py_string">"a"</span>, <span class="py_string">"b"</span>)
<span class="py_comment"># クラスに特殊メソッド __cmp__ を定義すると</span>
<span class="py_comment"># 結果を変更できる</span>
<span class="py_keyword">class</span> A:
<span class="py_keyword">def</span> __cmp__(self, x):
<span class="py_keyword">return</span> <span class="py_number">1</span>
</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/ref/specialnames.html">3.4 特殊メソッド名</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/customization.html">3.4.1 基本的なカスタマイズ</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/customization.html#l2h-193">__cmp__(self, other)</a></li>
</ul>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-12447967492051380742009-12-26T15:36:00.004+09:002009-12-26T15:40:50.188+09:00ホームディレクトリを取得する<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> os.path
<span class="py_keyword">import</span> os
hd = os.environ[<span class="py_string">"HOME"</span>]
hd = os.path.expanduser(<span class="py_string">"~"</span>)</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-os.html">14.1 os -- 雑多なオペレーティングシステムインタフェース</a></li>
<li><a href="http://www.python.jp/doc/release/lib/module-os.path.html">11.1 os.path -- 共通のパス名操作</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-35705110287648119152009-12-22T00:42:00.003+09:002009-12-22T01:20:11.902+09:00関数から関数名を文字列で取得する<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">def</span> func():
<span class="py_keyword">print</span> <span class="py_string">"hello"</span>
<span class="py_comment"># 関数オブジェクトから関数名を取得する</span>
s = func.__name__
<span class="py_keyword">import</span> __main__
<span class="py_comment"># モジュールオブジェクトから関数オブジェクトを取得する</span>
f = getattr(__main__, s)
f()</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/node832.html">26.10.1 型とメンバ</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-34944153374387176162009-12-20T16:36:00.001+09:002009-12-20T16:39:22.632+09:00カーソルを変更する<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> gtk
<span class="py_keyword">def</span> widget_set_cursor(widget):
<span class="py_comment"># 標準のカーソル</span>
widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.TOP_LEFT_ARROW))
<span class="py_comment"># カーソルを消す</span>
widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.BLANK_CURSOR))</pre>
<br/>
<a href="http://library.gnome.org/devel/pygtk/stable/class-gdkcursor.html">gtk.gdk.Cursor</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-16675594658608098122009-11-14T17:56:00.008+09:002009-12-20T14:29:46.863+09:00MIMEタイプを取得するmimetypes モジュールを使う<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> mimetypes
<span class="py_keyword">print</span> mimetypes.guess_type(<span class="py_string">"test.py"</span>)</pre>
<br/>
実行すると
<pre class="tm">('text/x-python', None)</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-mimetypes.html">7.6 mimetypes -- ファイル名を MIME 型へマップする</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/module-mimetypes.html#l2h-1493">guess_type(filename[, strict])</a></li>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-28593501195285628182009-10-31T00:34:00.006+09:002009-12-14T16:31:49.861+09:00URIからパスを取得するurlparse モジュールを使う<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> urlparse
<span class="py_keyword">import</span> urllib
o = urlparse.urlparse(<span class="py_string">"file:///home/yoshi"</span>)
s = o.path
<span class="py_comment"># 日本語が含まれている場合</span>
s = urllib.unquote(s)
<span class="py_keyword">print</span> o
<span class="py_keyword">print</span> s</pre>
<br/>
実行すると
<pre class="tm">ParseResult(scheme='file', netloc='', path='/home/yoshi', params='', query='', fragment='')
/home/yoshi</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-urlparse.html">18.17 urlparse -- URL を解析して構成要素にする</a></li>
<li><a href="http://www.python.jp/doc/release/lib/module-urllib.html">18.5 urllib -- URL による任意のリソースへのアクセス</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/module-urllib.html#l2h-3883">unquote(string)</a></li>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-12362951467457037932009-10-29T21:11:00.005+09:002009-12-14T16:30:58.400+09:00オブジェクトのブール値を取得する組み込み関数 bool で取得する
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_comment"># 組み込み関数boolで取得できる</span>
b = bool([])
<span class="py_comment"># クラスに特殊メソッド __nonzero__ __len__</span>
<span class="py_comment"># を定義すると返す値を変更できる</span>
<span class="py_comment"># 二つとも定義すると __nonzero__ が優先される</span>
<span class="py_keyword">class</span> A:
<span class="py_keyword">def</span> __nonzero__(self):
<span class="py_keyword">return</span> False
<span class="py_keyword">class</span> B:
<span class="py_keyword">def</span> __len__(self):
<span class="py_keyword">return</span> <span class="py_number">0</span>
b = bool(A())
b = bool(B())</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/built-in-funcs.html">2.1 組み込み関数</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/built-in-funcs.html#l2h-12">bool([x])</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/ref/specialnames.html">3.4 特殊メソッド名</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/customization.html">3.4.1 基本的なカスタマイズ</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/customization.html#l2h-200">__nonzero__(self)</a></li>
</ul>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-59162808454024797672009-10-27T16:48:00.002+09:002009-12-14T15:55:37.264+09:00属性値アクセスをカスタマイズする特殊メソッド __getattr__ __setattr__ __delattr__<br/>
をクラスに定義すると属性値アクセスをカスタマイズできる<br/>
<br/>
<pre class="pg"><span class="py_keyword">class</span> A:
dic = {}
<span class="py_keyword">def</span> __getattr__(self, name):
<span class="py_keyword">return</span> self.dic[name]
<span class="py_keyword">def</span> __setattr__(self, name, value):
self.dic[name] = value
<span class="py_keyword">def</span> __delattr__(self, name):
<span class="py_keyword">del</span> self.dic[name]
a = A()
a.x = <span class="py_number">1</span>
<span class="py_keyword">print</span> a.x
<span class="py_keyword">del</span> a.x</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/ref/specialnames.html">3.4 特殊メソッド名</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/attribute-access.html">3.4.2 属性値アクセスをカスタマイズする</a></li>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-56552708977176576952009-10-27T14:45:00.039+09:002009-10-27T17:28:00.463+09:00PyGTKでウィンドウを表示するWindowを表示する
<pre class="pg"><span class="py_keyword">import</span> gtk
<span class="py_keyword">def</span> win_destroy_cb(window, data=None):
gtk.main_quit()
win = gtk.Window()
win.connect(<span class="py_string">"destroy"</span>, win_destroy_cb)
win.show_all()
gtk.main()</pre>
<p>
実行すると<br/>
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga7qbGlRmvbnq0_peAWwoIvwGDFe9unEf6owUSdyXqtaxnkbkVal6uDOjwOGdZicL9aXTxUDZKc_XFUb4tL06xM2ByoxgKhD53flO2gJir4OnPfD55vhkquXGXA5kpSwq8jmEA_6T5slrx/s1600-h/pygtk_demo01.png"><img style="cursor:pointer; cursor:hand;width: 184px; height: 200px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga7qbGlRmvbnq0_peAWwoIvwGDFe9unEf6owUSdyXqtaxnkbkVal6uDOjwOGdZicL9aXTxUDZKc_XFUb4tL06xM2ByoxgKhD53flO2gJir4OnPfD55vhkquXGXA5kpSwq8jmEA_6T5slrx/s200/pygtk_demo01.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5397173891985257154" /></a>
</p>
WindowにButtonを追加し<br/>
Buttonがクリックされたらprintするようにする
<pre class="pg"><span class="py_keyword">import</span> gtk
<span class="py_keyword">def</span> b_clicked_cb(button, data=None):
<span class="py_keyword">print</span> <span class="py_string">"clicked"</span>
win = gtk.Window()
win.connect(<span class="py_string">"destroy"</span>, gtk.main_quit)
b = gtk.Button(<span class="py_string">"button"</span>)
b.connect(<span class="py_string">"clicked"</span>, b_clicked_cb)
win.add(b)
win.show_all()
gtk.main()</pre>
<p>
実行すると<br/>
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_sBrE2hz45tC-JIGodsyleAkcDyIC1WTUFsdezn4YNvLe3Ieu4KCXsE9uWeXRUmwCjPIROqHAcfT1hj6C17G46EUn5EHT07ksY5n_K8J5TT2_GW3oYowfeKXBKvr1vWHftDewYI85Xd6l/s1600-h/pygtk_demo_02.png"><img style="cursor:pointer; cursor:hand;width: 64px; height: 56px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_sBrE2hz45tC-JIGodsyleAkcDyIC1WTUFsdezn4YNvLe3Ieu4KCXsE9uWeXRUmwCjPIROqHAcfT1hj6C17G46EUn5EHT07ksY5n_K8J5TT2_GW3oYowfeKXBKvr1vWHftDewYI85Xd6l/s200/pygtk_demo_02.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5397179467883517362" /></a>
</p>
WindowにVBoxを追加し<br/>
VBoxにLabelを3つ追加する<br/>
<pre class="pg"><span class="py_keyword">import</span> gtk
win = gtk.Window()
win.connect(<span class="py_string">"destroy"</span>, gtk.main_quit)
vbox = gtk.VBox()
vbox.pack_start(gtk.Label(<span class="py_string">"label1"</span>))
vbox.pack_start(gtk.Label(<span class="py_string">"label2"</span>))
vbox.pack_start(gtk.Label(<span class="py_string">"label3"</span>))
win.add(vbox)
win.show_all()
gtk.main()</pre>
<p>
実行すると<br/>
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbsZjO3TlqAjkPVhfRjM0RaleoD0HI-gM0lapkGd_BUIHydpwpX8gumrYvuJ4Ovm3iH9JaxNuMybkYg7Zj5uV1N6z1fVsnmd8i22ZxdiEZhyqBXWPJ84hbtCH8dLh6QVrcJXyPbdXLda0k/s1600-h/pygtk_demo_03.png"><img style="cursor:pointer; cursor:hand;width: 52px; height: 76px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbsZjO3TlqAjkPVhfRjM0RaleoD0HI-gM0lapkGd_BUIHydpwpX8gumrYvuJ4Ovm3iH9JaxNuMybkYg7Zj5uV1N6z1fVsnmd8i22ZxdiEZhyqBXWPJ84hbtCH8dLh6QVrcJXyPbdXLda0k/s200/pygtk_demo_03.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5397177346590246018" /></a>
</p>
<ul class="dl">
<li><a href="http://library.gnome.org/devel/pygtk/stable/">PyGTK 2.0 Reference Manual</a></li>
<ul>
<li><a href="http://library.gnome.org/devel/pygtk/stable/gtk-class-reference.html">The gtk Class Reference</a></li>
<ul>
<li><a href="http://library.gnome.org/devel/pygtk/stable/class-gtkwindow.html">gtk.Window</a></li>
<li><a href="http://library.gnome.org/devel/pygtk/stable/class-gtkbutton.html">gtk.Button</a></li>
<li><a href="http://library.gnome.org/devel/pygtk/stable/class-gtkvbox.html">gtk.VBox</a></li>
<li><a href="http://library.gnome.org/devel/pygtk/stable/class-gtklabel.html">gtk.Label</a></li>
</ul>
<li><a href="http://library.gnome.org/devel/pygtk/stable/gtk-functions.html">gtk Functions</a></li>
<ul>
<li><a href="http://library.gnome.org/devel/pygtk/stable/gtk-functions.html#function-gtk--main-quit">gtk.main_quit</a></li>
</ul>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-50133714977381769202009-10-26T23:04:00.047+09:002010-01-07T15:11:31.557+09:00C言語で書いた関数をPythonで使うまずはC言語のプログラムを書く<br/>
/home/yoshi/python/cfunc.c
<pre class="pg">
#include <Python.h>
static PyObject *cprint(PyObject *self, PyObject *args) {
char *s;
if(!PyArg_ParseTuple(args, "s", &s)) {
return NULL;
}
printf(s, "");
return Py_None;
}
static PyObject *add(PyObject *self, PyObject *args) {
int i1, i2;
if(!PyArg_ParseTuple(args, "ii", &i1, &i2)) {
return NULL;
}
return Py_BuildValue("i", i1 + i2);
}
static PyObject *get_list(PyObject *self, PyObject *args) {
PyObject *list;
int i, n;
if(!PyArg_ParseTuple(args, "i", &n)) {
return NULL;
}
list = PyList_New(0);
for(i = 0; i < n; i++) {
PyList_Append(list, PyInt_FromLong(i));
}
return list;
}
/* メソッドテーブル */
static PyMethodDef methods[] = {
{"cprint", cprint, METH_VARARGS, "cprint(str)"},
{"add", add, METH_VARARGS, "int add(int, int)"},
{"get_list", get_list, METH_VARARGS, "list get_list(int)"},
{NULL, NULL, 0, NULL}
};
/*
初期化関数
変数名initcfuncはinitのあとに任意の名前をつける
この場合 cfunc なので initcfunc になる
*/
PyMODINIT_FUNC initcfunc(void) {
(void) Py_InitModule("cfunc", methods);
}</pre>
<br/>
cfunc.cをコンパイルするのに<br/>
Pythonのdistutilsパッケージを使いプログラムを書く<br/>
/home/yoshi/python/setup.py
<pre class="pg"><span class="py_keyword">from</span> distutils.core <span class="py_keyword">import</span> setup, Extension
module1 = Extension(<span class="py_string">"cfunc"</span>, sources=[<span class="py_string">"cfunc.c"</span>])
setup(name=<span class="py_string">'cfunc'</span>, version=<span class="py_string">'1.0'</span>,
description=<span class="py_string">'This is a demo package'</span>,
ext_modules=[module1])</pre>
<br/>
ディレクトリを移動する
<pre class="tm">$ cd /home/yoshi/python</pre>
setup.pyを実行しcfunc.cをコンパイルする
<pre class="tm">$ python setup.py build</pre>
<br/>
2つのファイルが生成される<br/>
1. /home/yoshi/python/build/lib.linux-i686-2.6/cfunc.so<br/>
2. /home/yoshi/python/build/temp.linux-i686-2.6/cfunc.o<br/>
<br/>
cfunc.soを/home/yoshi/pythonディレクトリにコピーする<br/>
<br/>
使ってみる<br/>
/home/yoshi/python/test.py
<pre class="pg"><span class="py_keyword">import</span> cfunc
cfunc.cprint(<span class="py_string">"hello\n"</span>)
<span class="py_keyword">print</span> cfunc.add(<span class="py_number">1</span>, <span class="py_number">2</span>)
<span class="py_keyword">print</span> cfunc.get_list(<span class="py_number">10</span>)
<span class="py_keyword">print</span> cfunc.cprint.__doc__
<span class="py_keyword">print</span> cfunc.add.__doc__
<span class="py_keyword">print</span> cfunc.get_list.__doc__</pre>
<br/>
実行すると
<pre class="tm">hello
3
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
cprint(str)
int add(int, int)
list get_list(int)</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/ext/ext.html">Python インタプリタの拡張と埋め込み</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ext/intro.html">1. C や C++ による Python の拡張</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ext/buildValue.html">1.9 任意の値を構築する</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/ext/building.html">3. distutils による C および C++ 拡張モジュールのビルド</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/api/utilities.html">5. ユーティリティ関数</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/api/arg-parsing.html">5.5 引数の解釈と値の構築</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/lib/module-distutils.html">30.12 distutils -- Python モジュールの構築とインストール</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-55843961984373902512009-10-26T14:56:00.011+09:002009-12-14T15:56:23.175+09:00ezPyCryptoで暗号化する<a href="http://www.freenet.org.nz/ezPyCrypto/">ezPyCrypto</a>はPyCryptoを簡単に扱えるようにしたもの<br/>
PyCryptoとezPyCryptoをインストールしないと使えない<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> ezPyCrypto
<span class="py_comment"># 鍵を生成する</span>
k = ezPyCrypto.key()
pubkey = k.exportKey()
privkey = k.exportKeyPrivate()
<span class="py_comment"># 暗号化する</span>
k = ezPyCrypto.key()
k.importKey(pubkey)
enc = k.encString(<span class="py_string">"hello"</span>)
<span class="py_keyword">print</span> <span class="py_string">"encString:"</span>, enc
<span class="py_comment"># 復号する</span>
k = ezPyCrypto.key(privkey)
dec = k.decString(enc)
<span class="py_keyword">print</span> <span class="py_string">"decString:"</span>, dec</pre>
<br/>
実行すると
<pre class="tm">encString: �(U RSAq(cCrypto.PublicKey.RSA
RSAobj_c
q oq }q (U eqL65537L
U nq L1748257469805572554674750845059940095475640794384397204969961481079828542998637460419267681338662752072214299796666797142576819714338050059429762247351L
ubtq.B ? �c��= �!b/Ue� ����"[�]�g<��$n� i�}O�!� te��1X ����P`fɟ�B ?��+s� f�����t�N~ �NG��Q VI8xVod\s*���>�'�x�
� gc� ��$B "�� B ? .9�ġ� � �@ �
&�# � ~�z��G��N����/�� �< ��DW��� ��p
Yz
,��|2_(O�,���
decString: hello</pre>
<br/>
<a href="http://www.freenet.org.nz/ezPyCrypto/detail/index.html">ezPyCrypto Documentation</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-5777205278331821542009-10-25T16:48:00.063+09:002009-12-14T15:57:16.267+09:00PyCryptoで暗号化する<a href="http://www.amk.ca/python/code/crypto.html">PyCrypto</a>を使うとAESやRSAなどで暗号化、復号できる<br/>
<br/>
<b>インストール方法1</b> (READMEファイルに書いてある)<br/>
<ol type="1">
<li><a href="http://www.amk.ca/python/code/crypto.html">PyCrypto</a>からファイルをダウンロードし展開する</li>
<li>展開したディレクトリに移動する<br/>
<pre class="tm">$ cd /home/yoshi/download/pycrypto-2.0.1</pre></li>
<li>ビルドする
<pre class="tm">$ python setup.py build</pre></li>
<li>インストールする
<pre class="tm">$ sudo python setup.py install</pre></li>
<li>動くかテストする
<pre class="tm">$ python test.py</pre></li>
</ol>
<b>インストール方法2</b>
<pre class="tm">$ sudo apt-get install python-crypto</pre>
<br/>
AESとDESで暗号化
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> Crypto.Cipher.AES
<span class="py_comment"># キーは16, 24, 32バイトの長さでなければならない</span>
obj = Crypto.Cipher.AES.new(<span class="py_string">'This is a key456'</span>, Crypto.Cipher.AES.MODE_ECB)
message = <span class="py_string">"The answer is no"</span> <span class="py_comment"># 文字数は16の倍数でなければならない</span>
ciphertext = obj.encrypt(message)
obj2 = Crypto.Cipher.AES.new(<span class="py_string">'This is a key456'</span>, Crypto.Cipher.AES.MODE_ECB)
decrypt = obj2.decrypt(ciphertext)
<span class="py_keyword">print</span> <span class="py_string">"message:"</span>, message
<span class="py_keyword">print</span> <span class="py_string">"encrypt:"</span>, ciphertext
<span class="py_keyword">print</span> <span class="py_string">"decrypt:"</span>, decrypt
<span class="py_keyword">import</span> Crypto.Cipher.DES
<span class="py_comment"># "abcdefgh" がキーになる(キーは8バイトの長さでなければならない)</span>
obj = Crypto.Cipher.DES.new(<span class="py_string">"abcdefgh"</span>, Crypto.Cipher.DES.MODE_ECB)
plain = <span class="py_string">"Guido van Rossum is a space alien."</span>
<span class="py_comment"># 文字数は8の倍数でなければエラーになるのでplainに6文字結合する</span>
ciph = obj.encrypt(plain + <span class="py_string">"XXXXXX"</span>)
decrypt = obj.decrypt(ciph)
<span class="py_keyword">print</span> <span class="py_string">"plain :"</span>, plain
<span class="py_keyword">print</span> <span class="py_string">"encrypt:"</span>, ciph
<span class="py_keyword">print</span> <span class="py_string">"decrypt:"</span>, decrypt</pre>
<br/>
実行すると
<pre class="tm">message: The answer is no
encrypt: o q_{P+�Ή�=M�9
decrypt: The answer is no
plain : Guido van Rossum is a space alien.
encrypt: ,�Nq�DY�T�pA���s��,�jب���I�5w 61�dgb/
decrypt: Guido van Rossum is a space alien.XXXXXX</pre>
<br/>
RSAで暗号化
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> Crypto.PublicKey.RSA
<span class="py_keyword">import</span> Crypto.Util.randpool
pool = Crypto.Util.randpool.RandomPool()
<span class="py_comment"># RSAオブジェクトをランダムな鍵で生成する</span>
<span class="py_comment"># 40bit(5文字)までを暗号化できるようにする</span>
rsa = Crypto.PublicKey.RSA.generate(<span class="py_number">40</span>, pool.get_bytes)
<span class="py_comment"># 公開鍵を取得する</span>
pub_rsa = rsa.publickey()
<span class="py_comment"># RSAオブジェクトをタプルから生成する</span>
<span class="py_comment"># rsa.nが公開鍵、rsa.dが秘密鍵と思う</span>
priv_rsa = Crypto.PublicKey.RSA.construct((rsa.n, rsa.e, rsa.d))
<span class="py_comment"># 暗号化する</span>
enc = pub_rsa.encrypt(<span class="py_string">"hello"</span>, <span class="py_string">""</span>)
<span class="py_comment"># 復号する</span>
dec = priv_rsa.decrypt(enc)
<span class="py_keyword">print</span> <span class="py_string">"private: n=%d, e=%d, d=%d, p=%d, q=%d, u=%d"</span> % \
(rsa.n, rsa.e, rsa.d, rsa.p, rsa.q, rsa.u)
<span class="py_keyword">print</span> <span class="py_string">"public: n=%d, e=%d"</span> % (pub_rsa.n, pub_rsa.e)
<span class="py_keyword">print</span> <span class="py_string">"encrypt:"</span>, enc
<span class="py_keyword">print</span> <span class="py_string">"decrypt:"</span>, dec
<span class="py_comment"># 署名する</span>
text = <span class="py_string">"hello"</span>
signature = priv_rsa.sign(text, <span class="py_string">""</span>)
<span class="py_comment"># 文字列が変わってないか調べる</span>
<span class="py_keyword">print</span> pub_rsa.verify(text, signature)
<span class="py_keyword">print</span> pub_rsa.verify(text+<span class="py_string">"a"</span>, signature)</pre>
<br/>
実行すると
<pre class="tm">private: n=593139068983, e=65537, d=308700828273, p=593951, q=998633, u=854285
public: n=593139068983, e=65537
encrypt: ('\x82A\x85\x0bv',)
decrypt: hello
True
False</pre>
<br/>
<a href="http://www.dlitz.net/software/pycrypto/">PyCrypto</a><br/>
<a href="http://www.dlitz.net/software/pycrypto/apidoc/">ドキュメント</a><br/>
<a href="http://www.dlitz.net/software/pycrypto/doc/">General overview of PyCrypto</a>Unknownnoreply@blogger.com25tag:blogger.com,1999:blog-1892806509743758128.post-75132558375084683982009-10-20T22:06:00.020+09:002009-12-14T15:58:20.816+09:00PsycoでPythonをちょっと速くする<a href="http://psyco.sourceforge.net/">psyco</a>モジュールを使うとPythonをちょっとだけ速くできる<br/>
<br/>
Ubuntu9.04の場合はインストールしなくても<br/>
psycoモジュールを使えたが<br/>
使えない場合はインストールしなければならない<br/>
<br/>
psyco.full 関数と psyco.bind 関数を使う
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> psyco
<span class="py_keyword">import</span> time
<span class="py_comment"># モジュール全てを高速化する</span>
<span class="py_comment"># psyco.full()</span>
<span class="py_keyword">def</span> func(n):
s = time.time()
<span class="py_keyword">for</span> i <span class="py_keyword">in</span> range(n):
<span class="py_keyword">pass</span>
<span class="py_keyword">print</span> time.time() - s, <span class="py_string">"秒"</span>
func(<span class="py_number">10000000</span>)
<span class="py_comment"># 引数に渡したオブジェクトを高速化する</span>
psyco.bind(func)
func(<span class="py_number">10000000</span>)
<span class="py_comment"># バインドされたオブジェクトを解除する</span>
psyco.unbind(func)
func(<span class="py_number">10000000</span>)</pre>
<br/>
実行すると
<pre class="tm">1.99553894997 秒
0.0189538002014 秒
1.05434322357 秒</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-36383490150220366472009-10-20T14:14:00.005+09:002009-10-21T00:01:38.707+09:00クラスのスーパークラスを取得する<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> inspect
<span class="py_keyword">class</span> A:
<span class="py_keyword">pass</span>
<span class="py_keyword">class</span> B(A):
<span class="py_keyword">pass</span>
<span class="py_keyword">class</span> C():
<span class="py_keyword">pass</span>
<span class="py_keyword">class</span> D(C, B):
<span class="py_keyword">pass</span>
<span class="py_comment"># クラスのスーパークラスをタプルで取得する</span>
<span class="py_keyword">print</span> D.__bases__
<span class="py_comment"># クラスが継承しているクラス(自身も含め)をタプルで取得する</span>
<span class="py_keyword">print</span> inspect.getmro(D)
<span class="py_comment"># インスタンスが属しているクラスを取得する</span>
<span class="py_keyword">print</span> D().__class__</pre>
<br/>
実行すると
<pre class="tm">(<class __main__.C at 0xb7bed1dc>, <class __main__.B at 0xb7bed1ac>)
(<class __main__.D at 0xb7bed20c>, <class __main__.C at 0xb7bed1dc>, <class __main__.B at 0xb7bed1ac>, <class __main__.A at 0xb7cbc59c>)
__main__.D</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/specialattrs.html">3.12 特殊な属性</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/specialattrs.html#l2h-337">__bases__</a></li>
<li><a href="http://www.python.jp/doc/release/lib/specialattrs.html#l2h-336">__class__</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/lib/module-inspect.html">26.10 inspect -- 使用中オブジェクトの情報を取得する</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/inspect-classes-functions.html">26.10.3 クラスと関数</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/inspect-classes-functions.html#l2h-5272">getmro(cls)</a></li>
</ul>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-58451695581302676982009-10-19T23:48:00.007+09:002009-12-14T15:59:38.930+09:00一時ファイルを作成するtempfileモジュールのTemporaryFile関数などで作成する
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> tempfile
<span class="py_comment"># 一時ファイルを作成する</span>
<span class="py_comment"># ファイルが閉じられると自動的に削除される</span>
<span class="py_keyword">with</span> tempfile.TemporaryFile() <span class="py_keyword">as</span> f:
f.write(<span class="py_string">"hello"</span>)
f.seek(<span class="py_number">0</span>)
<span class="py_keyword">print</span> f.read()
<span class="py_comment"># 一時ファイルの保存場所を取得する</span>
<span class="py_keyword">print</span> tempfile.gettempdir()</pre>
<br/>
実行すると
<pre class="tm">hello
/tmp</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-tempfile.html">11.6 tempfile -- 一時的なファイルやディレクトリの生成</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/module-tempfile.html#l2h-2256">TemporaryFile([mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]])</a></li>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-53400766781762057062009-10-19T20:40:00.009+09:002009-12-14T16:00:23.674+09:00ファイル操作os, shutil, stat モジュールなどを使う<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> os
<span class="py_keyword">import</span> shutil
<span class="py_keyword">import</span> stat
<span class="py_comment"># ディレクトリを作成する</span>
os.mkdir(<span class="py_string">"path"</span>)
os.makedirs(<span class="py_string">"aaa/bbb"</span>) <span class="py_comment"># 再帰的に作成する</span>
<span class="py_comment"># ファイルをコピーする</span>
shutil.copy(<span class="py_string">"src"</span>, <span class="py_string">"dst"</span>)
shutil.copytree(<span class="py_string">"src"</span>, <span class="py_string">"dst"</span>)
<span class="py_comment"># ファイルを移動する</span>
shutil.move(<span class="py_string">"src"</span>, <span class="py_string">"dst"</span>)
<span class="py_comment"># ファイルを削除する</span>
os.remove(<span class="py_string">"path"</span>)
<span class="py_comment"># ディレクトリを削除する</span>
os.rmdir(<span class="py_string">"path"</span>) <span class="py_comment"># 空でないと削除できない</span>
shutil.rmtree(<span class="py_string">"path"</span>) <span class="py_comment"># ディレクトリが空で無くても削除できる</span>
<span class="py_comment"># ファイルの名前を変更する</span>
os.rename(<span class="py_string">"src"</span>, <span class="py_string">"dst"</span>)
<span class="py_comment"># ファイルの更新日を変更する 第2引数(アクセス日時,修正日時)</span>
os.utime(<span class="py_string">"path"</span>, (<span class="py_number">1</span>, <span class="py_number">10000</span>))
<span class="py_comment"># ファイル権限を変更する</span>
os.chmod(<span class="py_string">"path"</span>, stat.S_IREAD | stat.S_IWRITE)
<span class="py_comment"># ファイルの詳細情報を取得する</span>
st = os.stat(<span class="py_string">"path"</span>)
<span class="py_comment"># 作業ディレクトリを変更する</span>
os.chdir(<span class="py_string">"/"</span>)
<span class="py_comment"># 作業ディレクトリを取得する</span>
cwd = os.getcwd()</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-os.html">14.1 os -- 雑多なオペレーティングシステムインタフェース</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/os-file-dir.html">14.1.4 ファイルとディレクトリ</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/lib/module-shutil.html">11.10 shutil -- 高レベルなファイル操作</a></li>
<li><a href="http://www.python.jp/doc/release/lib/module-stat.html">11.3 stat -- stat() の返す内容を解釈する</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-33062218471598321362009-10-19T11:40:00.075+09:002009-12-14T16:00:53.584+09:00gettextgettextモジュールを使う<br/>
<br/>
<span id="mo-0">/home/yoshi/python/hello.py</span>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> gettext
<span class="py_comment"># /home/yoshi/python/ja/LC_MESSAGES/messages.mo ファイルがないといけない</span>
gettext.bindtextdomain(<span class="py_string">"messages"</span>, <span class="py_string">"/home/yoshi/python"</span>)
_ = gettext.gettext
<span class="py_keyword">print</span> _(<span class="py_string">"hello"</span>)</pre>
<br/>
実行すると
<pre class="tm">ハロー</pre>
<br/>
<h3>messages.moファイルの生成方法</h3>
<ol type="1">
<li><a href="#mo-1">pygetextコマンドでhello.pyからmessages.potファイルを生成する</a></li>
<li><a href="#mo-2">messages.potをmessages.poにリネームしファイルの内容を変更する</a></li>
<li><a href="#mo-3">msgfmtコマンドでmessages.poからmessages.moファイルを生成する</a></li>
</ol>
<h4 id="mo-1">1. pygetextコマンドでhello.pyからmessages.potファイルを生成する</h4>
作業ディレクトリを移動<br>
<div class="tm">$ cd /home/yoshi/python</div>
pygettextコマンドで<a href="#mo-0">hello.py</a>からmessages.potを生成する
<div class="tm">$ pygettext hello.py</div>
/home/yoshi/python/messages.pot が生成される
<pre class="pg"># SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2009-10-19 22:08+JST\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: ENCODING\n"
"Generated-By: pygettext.py 1.5\n"
#: hello.py:10
msgid "hello"
msgstr ""</pre>
<h4 id="mo-2">2. messages.potをmessages.poにリネームしファイルの内容を変更する</h4>
ファイル名を変更する
<pre class="tm">mv messages.pot messages.po</pre>
/home/yoshi/python/messages.po 変更した部分は赤字
<pre class="pg"># SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2009-10-19 22:08+JST\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=<span style="color: rgb(255,0,0)">UTF-8</span>\n"
"Content-Transfer-Encoding: ENCODING\n"
"Generated-By: pygettext.py 1.5\n"
#: hello.py:10
msgid "hello"
msgstr "<span style="color: rgb(255,0,0)">ハロー</span>"</pre>
<h4 id="mo-3">3. msgfmtコマンドでmessages.poからmessages.moファイルを生成する</h4>
msgfmtコマンドでmessages.poからmessages.moを生成する<br/>
<div class="tm">$ msgfmt messages.po</div>
messages.moを移動するディレクトリを作成する<br/>
ディレクトリ名は決まっている(jaはjapanese)<br/>
<div class="tm">$ mkdir -p ja/LC_MESSAGES</div>
messages.moを移動する<br/>
<div class="tm">$ mv messages.mo ja/LC_MESSAGES</div>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-gettext.html">21.1 gettext -- 多言語対応に関する国際化サービス</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-59635694976950525432009-10-19T02:20:00.004+09:002009-12-14T16:01:11.930+09:00URLからソースを取得するurllibモジュールを使う<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> urllib
filehandle = urllib.urlopen(<span class="py_string">"http://www.python.jp/doc/release/lib/module-urllib.html"</span>)
<span class="py_keyword">for</span> i <span class="py_keyword">in</span> range(<span class="py_number">19</span>):
<span class="py_keyword">print</span> filehandle.readline().decode(<span class="py_string">"euc-jp"</span>),</pre>
<br/>
実行すると
<pre class="tm"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="lib.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python ドキュメントインデクス' />
<link rel="first" href="lib.html" title='Python ライブラリリファレンス' />
<link rel='contents' href='contents.html' title="Contents" />
<link rel='index' href='genindex.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="module-urllib2.html" />
<link rel="prev" href="module-wsgiref.html" />
<link rel="parent" href="internet.html" />
<link rel="next" href="urlopener-objs.html" />
<meta http-equiv="Content-Type" content="text/html; charset=EUC-JP" />
<meta name='aesop' content='information' />
<title>18.5 urllib -- URL による任意のリソースへのアクセス</title>
</head></pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-urllib.html">18.5 urllib -- URL による任意のリソースへのアクセス</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/module-urllib.html#l2h-3877">urlopen(url[, data[, proxies]])</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/lib/module-urllib2.html">18.6 urllib2 -- URL を開くための拡張可能なライブラリ</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-74923732743296464102009-10-19T01:51:00.004+09:002009-12-14T16:01:32.834+09:00Webブラウザを開くwebbrowserモジュールを使う<br/>
<br/>
<pre class="pg"><span class="py_keyword">import</span> webbrowser
webbrowser.open(<span class="py_string">"http://www.python.jp/doc/release/lib/module-webbrowser.html"</span>)</pre>
<br/>
実行するとWebブラウザが開く<br/>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-webbrowser.html">18.1 webbrowser -- 便利なウェブブラウザコントローラー</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/module-webbrowser.html#l2h-3781">open(url[, new=0[, autoraise=1]])</a></li>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-54486566165628128022009-10-19T01:27:00.003+09:002009-12-14T16:01:54.648+09:00ソケット通信socketモジュールを使う<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> socket
<span class="py_keyword">def</span> server(host, port):
s = socket.socket()
s.bind((host, port))
s.listen(<span class="py_number">1</span>)
conn, addr = s.accept() <span class="py_comment"># クライアントの接続を待つ</span>
data = conn.recv(<span class="py_number">1024</span>) <span class="py_comment"># クライアントからのデータを受信する</span>
<span class="py_keyword">print</span> <span class="py_string">"server: receive '%s'"</span> % data
conn.send(data.upper()) <span class="py_comment"># クライアントにデータを送信する</span>
conn.close()
s.close()
<span class="py_keyword">def</span> client(host, port):
s = socket.socket()
s.connect((host, port))
s.send(<span class="py_string">"hello"</span>) <span class="py_comment"># サーバにデータを送信する</span>
data = s.recv(<span class="py_number">1024</span>) <span class="py_comment"># サーバからのデータを受信する</span>
<span class="py_keyword">print</span> <span class="py_string">"client: receive '%s'"</span> % data
s.close()
<span class="py_comment"># 実行してみる</span>
<span class="py_keyword">import</span> threading
<span class="py_keyword">class</span> Server(threading.Thread):
<span class="py_keyword">def</span> run(self):
server(<span class="py_string">""</span>, <span class="py_number">50007</span>)
s = Server()
s.start()
client(<span class="py_string">""</span>, <span class="py_number">50007</span>)</pre>
<br/>
実行すると
<pre class="tm">server: receive 'hello'
client: receive 'HELLO'</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-socket.html">17.2 socket -- 低レベルネットワークインターフェース</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/socket-objects.html">17.2.1 socket オブジェクト</a></li>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-74767733589037234402009-10-18T01:08:00.008+09:002009-10-21T00:01:38.711+09:00キーボードから文字列を読み込む<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> sys
<span class="py_comment"># 1行読み込む</span>
<span class="py_keyword">print</span> sys.stdin.readline()
<span class="py_comment"># 複数行を読み込む、終了はEOF</span>
<span class="py_comment"># linuxの場合 Ctrl + D</span>
<span class="py_comment"># Windowの場合 Ctrl + Z ? で終了</span>
<span class="py_keyword">print</span> sys.stdin.read()</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-sys.html">26.1 sys -- システムパラメータと関数</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/module-sys.html#l2h-5161">stdin</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/lib/bltin-file-objects.html">3.9 ファイルオブジェクト</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/bltin-file-objects.html#l2h-302">readline([size])</a></li>
<li><a href="http://www.python.jp/doc/release/lib/bltin-file-objects.html#l2h-301">read([size])</a></li>
</ul>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-42245144753670945482009-10-17T18:12:00.008+09:002009-10-21T00:01:38.711+09:00コンテナ<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_comment"># 特殊メソッド __getitem__ __setitem__ __delitem__</span>
<span class="py_comment"># を定義すると添字表記が出来るようになる</span>
<span class="py_keyword">class</span> A:
<span class="py_keyword">def</span> __getitem__(self, index):
<span class="py_keyword">return</span> <span class="py_string">"get item %d"</span> % index
<span class="py_keyword">def</span> __setitem__(self, index, value):
<span class="py_keyword">print</span> <span class="py_string">"set item"</span>, index, value
<span class="py_keyword">def</span> __delitem__(self, index):
<span class="py_keyword">print</span> <span class="py_string">"del item"</span>, index
<span class="py_comment"># 特殊メソッド __setslice__ __getslice__ を定義すると</span>
<span class="py_comment"># スライスが出来るようになる</span>
<span class="py_keyword">class</span> B(A):
<span class="py_keyword">def</span> __setslice__(self, i, j, sequence):
<span class="py_keyword">print</span> <span class="py_string">"set slice"</span>, i, j, sequence
<span class="py_keyword">def</span> __getslice__(self, i, j):
<span class="py_keyword">return</span> <span class="py_string">"get slice %d %d"</span> % (i, j)
b = B()
<span class="py_keyword">print</span> b[<span class="py_number">0</span>]
b[<span class="py_number">1</span>] = <span class="py_string">"123"</span>
<span class="py_keyword">del</span> b[<span class="py_number">2</span>]
b[<span class="py_number">0</span>:<span class="py_number">1</span>] = <span class="py_string">"abc"</span>
<span class="py_keyword">print</span> b[<span class="py_number">2</span>:<span class="py_number">4</span>]</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/ref/specialnames.html">3.4 特殊メソッド名</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/sequence-types.html">3.4.5 コンテナをエミュレートする</a></li>
<li><a href="http://www.python.jp/doc/release/ref/sequence-methods.html">3.4.6 シーケンス型エミュレーションで使われるその他のメソッド</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/ref/subscriptions.html">5.3.2 添字表記 (subscription)</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-5925718309930482152009-10-17T17:11:00.006+09:002009-12-14T16:02:28.148+09:00演算子のオーバーロードクラスに特殊メソッドを定義する<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">class</span> A:
<span class="py_comment"># 二項算術演算</span>
<span class="py_keyword">def</span> __add__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> + i
<span class="py_keyword">def</span> __sub__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> - i
<span class="py_keyword">def</span> __mul__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> * i
<span class="py_keyword">def</span> __div__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> / i
<span class="py_keyword">def</span> __truediv__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> / i
<span class="py_keyword">def</span> __floordiv__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> // i
<span class="py_keyword">def</span> __mod__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> % i
<span class="py_keyword">def</span> __divmod__(self, i):
<span class="py_keyword">return</span> (<span class="py_number">10</span> / i, <span class="py_number">10</span> % i)
<span class="py_keyword">def</span> __pow__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> ** i
<span class="py_keyword">def</span> __lshift__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> << i
<span class="py_keyword">def</span> __rshift__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> >> i
<span class="py_keyword">def</span> __and__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> & i
<span class="py_keyword">def</span> __xor__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> ^ i
<span class="py_keyword">def</span> __or__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> | i
<span class="py_comment"># 単項算術演算</span>
<span class="py_keyword">def</span> __neg__(self):
<span class="py_keyword">return</span> -<span class="py_number">10</span>
<span class="py_keyword">def</span> __pos__(self):
<span class="py_keyword">return</span> +<span class="py_number">10</span>
<span class="py_keyword">def</span> __abs__(self):
<span class="py_keyword">return</span> abs(<span class="py_number">10</span>)
<span class="py_keyword">def</span> __invert__(self):
<span class="py_keyword">return</span> ~<span class="py_number">10</span>
<span class="py_comment"># 比較演算</span>
<span class="py_keyword">def</span> __lt__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> < i
<span class="py_keyword">def</span> __le__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> <= i
<span class="py_keyword">def</span> __eq__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> == i
<span class="py_keyword">def</span> __ne__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> != i
<span class="py_keyword">def</span> __gt__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> > i
<span class="py_keyword">def</span> __ge__(self, i):
<span class="py_keyword">return</span> <span class="py_number">10</span> >= i
a = A()
<span class="py_keyword">print</span> a + <span class="py_number">2</span>
<span class="py_keyword">print</span> -a
<span class="py_keyword">print</span> a < <span class="py_number">4</span>
<span class="py_comment"># 2 + a</span>
<span class="py_comment"># 逆を出来るようにするには r をつけた特殊メソッドを定義する</span>
<span class="py_comment"># __radd__, __rsub__, __rmul__, __rdiv__, __rtruediv__</span>
<span class="py_comment"># __rfloordiv__, __rmod__, __rdivmod__, __rpow__, __rlshift__</span>
<span class="py_comment"># __rrshift__, __rand__, __rxor__, __ror__</span>
<span class="py_comment"># a += 2</span>
<span class="py_comment"># += などを出来るようにするには i をつけた特殊メソッドを定義する</span>
<span class="py_comment"># __iadd__, __isub__, __imul__, __idiv__, __itruediv__</span>
<span class="py_comment"># __ifloordiv__, __imod__, __ipow__, __ilshift__</span>
<span class="py_comment"># __irshift__, __iand__, __ixor__, __ior__</span></pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/ref/specialnames.html">3.4 特殊メソッド名</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/numeric-types.html">3.4.7 数値型をエミュレーションする</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/ref/customization.html">3.4.1 基本的なカスタマイズ</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-19833764834093899922009-10-16T11:51:00.014+09:002009-12-14T16:03:10.104+09:00オブジェクトが呼び出し可能オブジェクトか調べる呼び出し可能オブジェクトとは<br/>
int() のように末尾に括弧をつけることのできるオブジェクトのこと<br/>
関数やメソッドなどは呼び出し可能オブジェクトである<br/>
<br/>
<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_comment"># 呼び出し可能オブジェクトか調べる</span>
b = callable(int)
<span class="py_comment"># クラスに特殊メソッド __call__ を定義すると</span>
<span class="py_comment"># 呼び出し可能オブジェクトを模倣できる</span>
<span class="py_keyword">class</span> A:
<span class="py_keyword">def</span> __call__(self, a, b):
<span class="py_keyword">return</span> a + b
a = A()
i = a(<span class="py_number">1</span>, <span class="py_number">2</span>)</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/built-in-funcs.html">2.1 組み込み関数</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/lib/built-in-funcs.html#l2h-14">callable(object)</a></li>
</ul>
<li><a href="http://www.python.jp/doc/release/ref/specialnames.html">3.4 特殊メソッド名</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/callable-types.html">3.4.4 呼び出し可能オブジェクトをエミュレートする</a></li>
<ul>
<li><a href="http://www.python.jp/doc/release/ref/callable-types.html#l2h-219">__call__(self[, args...])</a></li>
</ul>
</ul>
<li><a href="http://www.python.jp/doc/release/ref/calls.html">5.3.4 呼び出し (call)</a></li>
</ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1892806509743758128.post-36272201331178963932009-10-16T11:39:00.030+09:002009-10-21T00:01:38.714+09:00DOMでXMLを解析する<pre class="pg"><span class="py_comment"># -*- coding: utf-8 -*-</span>
<span class="py_keyword">import</span> xml.dom.minidom
s = <span class="py_string">'<?xml version="1.0"?>\
<parent id="top">\
<child name="paul">Text goes here</child>\
<child name="fred">More text</child>\
</parent>'</span>
<span class="py_keyword">def</span> print_parent(emt):
tup = (emt.tagName, emt.getAttribute(<span class="py_string">"id"</span>))
<span class="py_keyword">print</span> <span class="py_string">"['%s', {'id': '%s'}]"</span> % tup
<span class="py_keyword">def</span> print_child(emt):
tup = (emt.tagName, emt.getAttribute(<span class="py_string">"name"</span>),
emt.childNodes[0].data)
<span class="py_keyword">print</span> <span class="py_string">"['%s', {'name': '%s'}, '%s']"</span> % tup
<span class="py_comment"># 文字列からdomオブジェクトを生成</span>
dom = xml.dom.minidom.parseString(s)
<span class="py_comment"># ファイルからdomオブジェクトを生成する場合
# dom = xml.dom.minidom.parse("file.xml")</span>
<span class="py_comment"># dom から要素を取得する</span>
parent_emt = dom.getElementsByTagName(<span class="py_string">"parent"</span>)[<span class="py_number">0</span>]
child_emt_list = parent_emt.getElementsByTagName(<span class="py_string">"child"</span>)
<span class="py_comment"># プリントする</span>
print_parent(parent_emt)
<span class="py_keyword">for</span> child_emt <span class="py_keyword">in</span> child_emt_list:
print_child(child_emt)
<span class="py_comment"># parent_emt に要素を追加する</span>
new_emt = dom.createElement(<span class="py_string">"child"</span>)
new_emt.setAttribute(<span class="py_string">"name"</span>, <span class="py_string">"yoshi"</span>)
new_emt.appendChild(dom.createTextNode(<span class="py_string">"hello"</span>))
parent_emt.appendChild(new_emt)
<span class="py_comment"># DOMオブジェクトを文字列にする</span>
ds = dom.toprettyxml(<span class="py_string">" "</span>)
<span class="py_keyword">print</span>
<span class="py_keyword">print</span> ds
<span class="py_comment"># DOMオブジェクトをファイルに保存する</span>
<span class="py_keyword">with</span> open(<span class="py_string">"xml-file.xml"</span>, <span class="py_string">"w"</span>) <span class="py_keyword">as</span> f:
dom.writexml(f, <span class="py_string">""</span>, <span class="py_string">"\t"</span>, <span class="py_string">"\n"</span>)</pre>
<br/>
実行すると
<pre class="tm">['parent', {'id': 'top'}]
['child', {'name': 'paul'}, 'Text goes here']
['child', {'name': 'fred'}, 'More text']
<?xml version="1.0" ?>
<parent id="top">
<child name="paul">
Text goes here
</child>
<child name="fred">
More text
</child>
<child name="yoshi">
hello
</child>
</parent>
</pre>
<br/>
詳細はドキュメントで
<ul class="dl">
<li><a href="http://www.python.jp/doc/release/lib/module-xml.dom.minidom.html">8.7 xml.dom.minidom -- 軽量な DOM 実装</a></li>
<li><a href="http://www.python.jp/doc/release/lib/module-xml.dom.html">8.6 xml.dom -- 文書オブジェクトモデル (DOM) API</a></li>
</ul>Unknownnoreply@blogger.com0