# -*- coding: utf-8 -*- # 戻り値は数値 # x < y なら -1, x == y なら 0, x > y なら 1 i = cmp("a", "b") # クラスに特殊メソッド __cmp__ を定義すると # 結果を変更できる class A: def __cmp__(self, x): return 1
詳細はドキュメントで
# -*- coding: utf-8 -*- # 戻り値は数値 # x < y なら -1, x == y なら 0, x > y なら 1 i = cmp("a", "b") # クラスに特殊メソッド __cmp__ を定義すると # 結果を変更できる class A: def __cmp__(self, x): return 1
# -*- coding: utf-8 -*- import os.path import os hd = os.environ["HOME"] hd = os.path.expanduser("~")
# -*- coding: utf-8 -*- def func(): print "hello" # 関数オブジェクトから関数名を取得する s = func.__name__ import __main__ # モジュールオブジェクトから関数オブジェクトを取得する f = getattr(__main__, s) f()
# -*- coding: utf-8 -*- import gtk def widget_set_cursor(widget): # 標準のカーソル widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.TOP_LEFT_ARROW)) # カーソルを消す widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.BLANK_CURSOR))
# -*- coding: utf-8 -*- import mimetypes print mimetypes.guess_type("test.py")
('text/x-python', None)
# -*- coding: utf-8 -*- import urlparse import urllib o = urlparse.urlparse("file:///home/yoshi") s = o.path # 日本語が含まれている場合 s = urllib.unquote(s) print o print s
ParseResult(scheme='file', netloc='', path='/home/yoshi', params='', query='', fragment='') /home/yoshi
# -*- coding: utf-8 -*- # 組み込み関数boolで取得できる b = bool([]) # クラスに特殊メソッド __nonzero__ __len__ # を定義すると返す値を変更できる # 二つとも定義すると __nonzero__ が優先される class A: def __nonzero__(self): return False class B: def __len__(self): return 0 b = bool(A()) b = bool(B())
class A: dic = {} def __getattr__(self, name): return self.dic[name] def __setattr__(self, name, value): self.dic[name] = value def __delattr__(self, name): del self.dic[name] a = A() a.x = 1 print a.x del a.x
import gtk def win_destroy_cb(window, data=None): gtk.main_quit() win = gtk.Window() win.connect("destroy", win_destroy_cb) win.show_all() gtk.main()WindowにButtonを追加し
import gtk def b_clicked_cb(button, data=None): print "clicked" win = gtk.Window() win.connect("destroy", gtk.main_quit) b = gtk.Button("button") b.connect("clicked", b_clicked_cb) win.add(b) win.show_all() gtk.main()WindowにVBoxを追加し
import gtk win = gtk.Window() win.connect("destroy", gtk.main_quit) vbox = gtk.VBox() vbox.pack_start(gtk.Label("label1")) vbox.pack_start(gtk.Label("label2")) vbox.pack_start(gtk.Label("label3")) win.add(vbox) win.show_all() gtk.main()
#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);
}
from distutils.core import setup, Extension module1 = Extension("cfunc", sources=["cfunc.c"]) setup(name='cfunc', version='1.0', description='This is a demo package', ext_modules=[module1])
$ cd /home/yoshi/pythonsetup.pyを実行しcfunc.cをコンパイルする
$ python setup.py build
import cfunc cfunc.cprint("hello\n") print cfunc.add(1, 2) print cfunc.get_list(10) print cfunc.cprint.__doc__ print cfunc.add.__doc__ print cfunc.get_list.__doc__
hello 3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] cprint(str) int add(int, int) list get_list(int)
# -*- coding: utf-8 -*- import ezPyCrypto # 鍵を生成する k = ezPyCrypto.key() pubkey = k.exportKey() privkey = k.exportKeyPrivate() # 暗号化する k = ezPyCrypto.key() k.importKey(pubkey) enc = k.encString("hello") print "encString:", enc # 復号する k = ezPyCrypto.key(privkey) dec = k.decString(enc) print "decString:", dec
encString: �(URSAq(cCrypto.PublicKey.RSA
RSAobj_c
qoq}q(UeqL65537L
UnqL1748257469805572554674750845059940095475640794384397204969961481079828542998637460419267681338662752072214299796666797142576819714338050059429762247351L
ubtq.B?�c��=�!b/Ue�����"[�]�g<��$n�i�}O�!�te��1X����P`fɟ�B?��+s�f�����t�N~�NG��QVI8xVod\s*���>�'�x�
�gc���$B"�� B?.9�ġ� ��@�
&�#�~�z��G��N����/���<��DW�����p
Yz
,��|2_(O�,���
decString: hello
$ cd /home/yoshi/download/pycrypto-2.0.1
$ python setup.py build
$ sudo python setup.py install
$ python test.py
$ sudo apt-get install python-crypto
# -*- coding: utf-8 -*- import Crypto.Cipher.AES # キーは16, 24, 32バイトの長さでなければならない obj = Crypto.Cipher.AES.new('This is a key456', Crypto.Cipher.AES.MODE_ECB) message = "The answer is no" # 文字数は16の倍数でなければならない ciphertext = obj.encrypt(message) obj2 = Crypto.Cipher.AES.new('This is a key456', Crypto.Cipher.AES.MODE_ECB) decrypt = obj2.decrypt(ciphertext) print "message:", message print "encrypt:", ciphertext print "decrypt:", decrypt import Crypto.Cipher.DES # "abcdefgh" がキーになる(キーは8バイトの長さでなければならない) obj = Crypto.Cipher.DES.new("abcdefgh", Crypto.Cipher.DES.MODE_ECB) plain = "Guido van Rossum is a space alien." # 文字数は8の倍数でなければエラーになるのでplainに6文字結合する ciph = obj.encrypt(plain + "XXXXXX") decrypt = obj.decrypt(ciph) print "plain :", plain print "encrypt:", ciph print "decrypt:", decrypt
message: The answer is no
encrypt: oq_{P+�Ή�=M�9
decrypt: The answer is no
plain : Guido van Rossum is a space alien.
encrypt: ,�Nq�DY�T�pA���s��,�jب���I�5w61�dgb/
decrypt: Guido van Rossum is a space alien.XXXXXX
# -*- coding: utf-8 -*- import Crypto.PublicKey.RSA import Crypto.Util.randpool pool = Crypto.Util.randpool.RandomPool() # RSAオブジェクトをランダムな鍵で生成する # 40bit(5文字)までを暗号化できるようにする rsa = Crypto.PublicKey.RSA.generate(40, pool.get_bytes) # 公開鍵を取得する pub_rsa = rsa.publickey() # RSAオブジェクトをタプルから生成する # rsa.nが公開鍵、rsa.dが秘密鍵と思う priv_rsa = Crypto.PublicKey.RSA.construct((rsa.n, rsa.e, rsa.d)) # 暗号化する enc = pub_rsa.encrypt("hello", "") # 復号する dec = priv_rsa.decrypt(enc) print "private: n=%d, e=%d, d=%d, p=%d, q=%d, u=%d" % \ (rsa.n, rsa.e, rsa.d, rsa.p, rsa.q, rsa.u) print "public: n=%d, e=%d" % (pub_rsa.n, pub_rsa.e) print "encrypt:", enc print "decrypt:", dec # 署名する text = "hello" signature = priv_rsa.sign(text, "") # 文字列が変わってないか調べる print pub_rsa.verify(text, signature) print pub_rsa.verify(text+"a", signature)
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
# -*- coding: utf-8 -*- import psyco import time # モジュール全てを高速化する # psyco.full() def func(n): s = time.time() for i in range(n): pass print time.time() - s, "秒" func(10000000) # 引数に渡したオブジェクトを高速化する psyco.bind(func) func(10000000) # バインドされたオブジェクトを解除する psyco.unbind(func) func(10000000)
1.99553894997 秒 0.0189538002014 秒 1.05434322357 秒
# -*- coding: utf-8 -*- import inspect class A: pass class B(A): pass class C(): pass class D(C, B): pass # クラスのスーパークラスをタプルで取得する print D.__bases__ # クラスが継承しているクラス(自身も含め)をタプルで取得する print inspect.getmro(D) # インスタンスが属しているクラスを取得する print D().__class__
(<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
# -*- coding: utf-8 -*- import tempfile # 一時ファイルを作成する # ファイルが閉じられると自動的に削除される with tempfile.TemporaryFile() as f: f.write("hello") f.seek(0) print f.read() # 一時ファイルの保存場所を取得する print tempfile.gettempdir()
hello /tmp
# -*- coding: utf-8 -*- import os import shutil import stat # ディレクトリを作成する os.mkdir("path") os.makedirs("aaa/bbb") # 再帰的に作成する # ファイルをコピーする shutil.copy("src", "dst") shutil.copytree("src", "dst") # ファイルを移動する shutil.move("src", "dst") # ファイルを削除する os.remove("path") # ディレクトリを削除する os.rmdir("path") # 空でないと削除できない shutil.rmtree("path") # ディレクトリが空で無くても削除できる # ファイルの名前を変更する os.rename("src", "dst") # ファイルの更新日を変更する 第2引数(アクセス日時,修正日時) os.utime("path", (1, 10000)) # ファイル権限を変更する os.chmod("path", stat.S_IREAD | stat.S_IWRITE) # ファイルの詳細情報を取得する st = os.stat("path") # 作業ディレクトリを変更する os.chdir("/") # 作業ディレクトリを取得する cwd = os.getcwd()
# -*- coding: utf-8 -*- import gettext # /home/yoshi/python/ja/LC_MESSAGES/messages.mo ファイルがないといけない gettext.bindtextdomain("messages", "/home/yoshi/python") _ = gettext.gettext print _("hello")
ハロー
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR, 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 \n" "Language-Team: LANGUAGE \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 ""
mv messages.pot messages.po/home/yoshi/python/messages.po 変更した部分は赤字
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR, 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 \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: pygettext.py 1.5\n" #: hello.py:10 msgid "hello" msgstr "ハロー"
# -*- coding: utf-8 -*- import urllib filehandle = urllib.urlopen("http://www.python.jp/doc/release/lib/module-urllib.html") for i in range(19): print filehandle.readline().decode("euc-jp"),
<!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>
import webbrowser webbrowser.open("http://www.python.jp/doc/release/lib/module-webbrowser.html")
# -*- coding: utf-8 -*- import socket def server(host, port): s = socket.socket() s.bind((host, port)) s.listen(1) conn, addr = s.accept() # クライアントの接続を待つ data = conn.recv(1024) # クライアントからのデータを受信する print "server: receive '%s'" % data conn.send(data.upper()) # クライアントにデータを送信する conn.close() s.close() def client(host, port): s = socket.socket() s.connect((host, port)) s.send("hello") # サーバにデータを送信する data = s.recv(1024) # サーバからのデータを受信する print "client: receive '%s'" % data s.close() # 実行してみる import threading class Server(threading.Thread): def run(self): server("", 50007) s = Server() s.start() client("", 50007)
server: receive 'hello' client: receive 'HELLO'
OSはUbuntu 9.04
PythonはPython 2.6.2