# -*- coding: utf-8 -*- import os.path import os hd = os.environ["HOME"] hd = os.path.expanduser("~")
詳細はドキュメントで
# -*- coding: utf-8 -*- import os.path import os hd = os.environ["HOME"] hd = os.path.expanduser("~")
# -*- 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
#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 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'
# -*- coding: utf-8 -*- import sys # 1行読み込む print sys.stdin.readline() # 複数行を読み込む、終了はEOF # linuxの場合 Ctrl + D # Windowの場合 Ctrl + Z ? で終了 print sys.stdin.read()
# -*- coding: utf-8 -*- import xml.dom.minidom s = '<?xml version="1.0"?>\ <parent id="top">\ <child name="paul">Text goes here</child>\ <child name="fred">More text</child>\ </parent>' def print_parent(emt): tup = (emt.tagName, emt.getAttribute("id")) print "['%s', {'id': '%s'}]" % tup def print_child(emt): tup = (emt.tagName, emt.getAttribute("name"), emt.childNodes[0].data) print "['%s', {'name': '%s'}, '%s']" % tup # 文字列からdomオブジェクトを生成 dom = xml.dom.minidom.parseString(s) # ファイルからdomオブジェクトを生成する場合 # dom = xml.dom.minidom.parse("file.xml") # dom から要素を取得する parent_emt = dom.getElementsByTagName("parent")[0] child_emt_list = parent_emt.getElementsByTagName("child") # プリントする print_parent(parent_emt) for child_emt in child_emt_list: print_child(child_emt) # parent_emt に要素を追加する new_emt = dom.createElement("child") new_emt.setAttribute("name", "yoshi") new_emt.appendChild(dom.createTextNode("hello")) parent_emt.appendChild(new_emt) # DOMオブジェクトを文字列にする ds = dom.toprettyxml(" ") print print ds # DOMオブジェクトをファイルに保存する with open("xml-file.xml", "w") as f: dom.writexml(f, "", "\t", "\n")
['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>
# -*- coding: utf-8 -*- import xml.parsers.expat def start_element(name, attrs): print 'Start element:', name, attrs def end_element(name): print 'End element:', name def char_data(data): print 'Character data:', repr(data) p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data p.Parse('<?xml version="1.0"?>\ <parent id="top">\ <child1 name="paul">Text goes here</child1>\ <child2 name="fred">More text</child2>\ </parent>') # ファイルを解析する場合 # with open("file.xml") as f: # p.ParseFile(f)
Start element: parent {u'id': u'top'}
Start element: child1 {u'name': u'paul'}
Character data: u'Text goes here'
End element: child1
Start element: child2 {u'name': u'fred'}
Character data: u'More text'
End element: child2
End element: parent
# -*- coding: utf-8 -*- import threading import time # Eventオブジェクトを生成する event = threading.Event() class A(threading.Thread): def run(self): for i in range(3): # setメソッドが呼び出されるまでスレッドを待機させる event.wait() print "hello" th = A() th.start() time.sleep(2) event.set() # 待機を解除する event.clear() # setしたままだとwaitで待機しなくなる time.sleep(2) event.set()
import threading def hello(): print "hello" timer = threading.Timer(2, hello) timer.start()
# -*- coding: utf-8 -*- import threading import time LOCK = threading.Lock() def func(): for i in range(10): time.sleep(0.1) print i, print def lock_func(): # with文を使わない場合はacquireとreleaseメソッドを使う with LOCK: func() a = threading.Thread(target=func) b = threading.Thread(target=func) print "unlock" a.start() b.start() a.join() b.join() c = threading.Thread(target=lock_func) d = threading.Thread(target=lock_func) print "lock" c.start() d.start()
unlock 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 lock 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
# -*- coding: utf-8 -*- import math # 三角関数 angle = 30 h = 50 a = math.sin(math.radians(angle)) * h b = math.cos(math.radians(angle)) * h # 数値の平方根(ルート)を取得する st = math.sqrt(2) # 数値の絶対値を取得する ab = abs(-5) # シーケンス内の最大数値を取得する mx = max(10, 20, 30) # シーケンス内の最小数値を取得する mn = min(10, 20, 30) # 商と剰余のタプルを取得する (5/2,5%2)と同じ dm = divmod(5, 2) # べき乗 (3**3 でもできる) pw = pow(3, 3) # 数値を四捨五入する rd = round(3.45, 1) s = "%0.1f" % 3.45 # シーケンス内の合計 sm = sum(range(10)) print "h:", h print "a:", a print "b:", b print print ">>> math.sqrt(2)" print st print ">>> abs(-5)" print ab print ">>> max(10, 20, 30)" print mx print ">>> min(10, 20, 30)" print mn print ">>> divmod(5, 2)" print dm print ">>> pow(3, 3)" print pw print ">>> round(3.45, 1)" print rd print ">>> sum(range(10))" print sm
h: 50 a: 25.0 b: 43.3012701892 >>> math.sqrt(2) 1.41421356237 >>> abs(-5) 5 >>> max(10, 20, 30) 30 >>> min(10, 20, 30) 10 >>> divmod(5, 2) (2, 1) >>> pow(3, 3) 27 >>> round(3.45, 1) 3.5 >>> sum(range(10)) 45
# -*- coding: utf-8 -*- import gc # ガベージコレクタを無効にする gc.disable() # ガベージコレクタを有効にする gc.enable()
# -*- coding: utf-8 -*- import datetime # 現在の日時をdatetime型で取得する today = datetime.datetime.today() # timedelta型はdatetime型などとの計算に使える timedelta = datetime.timedelta(days=3, hours=2) # todayから3日と2時間進んだdatetime型を生成する dt1 = today + timedelta # todayから3日と2時間戻ったdatetime型を生成する dt2 = today - timedelta format = "%Y/%m/%d %H:%M:%S" print "-today:", dt2.strftime(format) print " today:", today.strftime(format) print "+today:", dt1.strftime(format)
-today: 2009/10/10 22:54:46 today: 2009/10/14 00:54:46 +today: 2009/10/17 02:54:46
OSはUbuntu 9.04
PythonはPython 2.6.2