このサイトのはてなブックマーク数の合計

www を検索 sarabande.info を検索
トップページに戻る

Python

確認環境

Windows XP+Python2.5.1+XAMPP

セットアップ

Python本体

python-2.5.1.msiとpywin32-210.win32-py2.5.exeを入手してインストールする。

インタプリタの起動と終了

起動

python

終了

exit()

もしくは

import;
sys.exit()

setuptools

http://peak.telecommunity.com/DevCenter/setuptools

Windowsの場合

wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py

Ubuntuの場合

sudo apt-get install python-setuptools

正常にインストールされたことを確認するためには

easy_install --help

MinGWのビルドを指定する

distutils.cfgファイルをC:\Python25\Lib\distutilsに作成し次のコードを追記する。

 
compiler=mingw32
 

もしくはsetup.pyからインストールする場合に次のようにオプションを追加する。

python setup.py build -f -c mingw32 install -f

pywin32

easy_install pywin32

IPython

Ubuntuの場合はapt-get install ipython、起動はipython

easy_install pyreadline
easy_install ipython

Windows版はipython-0.8.2.win32-setup.exeとpyreadline-1.5-win32-setup.exeをインストール。

コマンドプロンプトから起動させるには以下のbatファイルをC:\Python\Scriptsに設置する。

ipython.bat

@C:\Python\python.exe "C:\Python\scripts\ipython" %*

これでコマンドプロンプトからipythonを入力すればIPythonが起動する。pyshを起動させるには次のようにオプションを追加する。

ipython -p sh

scipyを使えるようにするには以下の通り。

easy_install matplotlib
easy_install scipy

上記のbatファイルを作成しているのであれば次のコマンドから起動できる

ipython -pylab -p scipy

Matplotlib

easy_install matplotlib
easy_install numpy

上記のIPythonの導入作業でMatplotlibが導入されている。起動させるには次のコマンドを実行する。

ipython -pylab

Mercurial(バージョン管理ツール)

easy_installでインストールできる。MinGWなどのCコンパイラを設定していないとインストールが失敗することがある。

easy_install mercurial

パッケージからインストールするには以下の通り。

python setup.py build -f -c mingw32 install -f

以下のようなhg.batをC:\Python\Scriptsに設置する。

@python c:\python\Scripts\hg %*

データベース

Stormとmiddlestorm(ORM)

easy_install storm
easy_install middlestorm

Ubuntuの場合次のコマンドでもインストールできるがバージョンが少し古い。

sudo apt-get install python-storm

コードの例

 
from storm.locals import *
database = create_database("sqlite:/:memory:")
 

SQLObject

Windows

easy_install SQLObject

Ubuntuの場合は次のコマンドでもインストールできる。

sudo apt-get install python-sqlobject

データベースに接続する

 
from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite:/:memory:')
 

MySQL

データベースの作成

 
mysql -u root -p
CREATE DATABASE IF NOT EXISTS pythondb DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
GRANT CREATE, SELECT, INSERT, UPDATE, DELETE, ALTER, LOCK TABLES 
ON pythondb.* TO 'pythonuser'@'localhost' IDENTIFIED BY 'password';
\q
 

データベースへの接続と終了

 
import MySQLdb
 
host = 'localhost'
user = 'pythonuser'
passwd = 'password'
db = 'pythondb'
 
dbconn = MySQLdb.connect(host, user, passwd, db)
dbconn.close()
 

SQLite

 
import sqlite3
conn = sqlite3.connect('test.db')
conn.close()
 

psycopg2

easy_install psycopg2

Windowsの場合下記のサイトから最新のものをダウンロードする。 http://www.stickpeople.com/projects/python/psycopg/

easy_install http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.0.6.win32-py2.5-pg8.2.4-release.exe

接続テスト

 
import pycopg2
conn = psycopg2.connect("dbname=wikidb user=wikiuser password=password")
 

時間

ローカルタイムを表示する

 
>>> import time
>>> print time.localtime()
(2008, 1, 31, 2, 51, 45, 3, 31, 0)
>>> print time.localtime()[2]
31
 

PDF

Reportlab

http://www.reportlab.org/downloads.html よりReportLab_1_21_1.zipとwin32-dlls-py25.zipをダウンロードする。

Reportlab

cd reportlab_2_1/reportlab
python setup.py install

win32-dlls-py25.zipはC:\Python\DLLsにコピーしてそこで解凍する。

 
# -*- encoding: utf-8 -*-
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.lib.colors import magenta, red
 
c = canvas.Canvas("test.pdf")
font = 'HeiseiMin-W3'
 
pdfmetrics.registerFont(UnicodeCIDFont(font))
c.setFont(font, 16)
c.setFillColor(red)
c.drawString(50,800,u"日本語表示")
 
c.showPage()
c.save()
 

参考

文字列・正規表現

文字列の置換

 
import string
str = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
str = string.replace(str, 'charset=utf-8', 'charset=Shift_JIS')
print str # <meta http-equiv="Content-Type" content="text/html; Shift_JIS" />
 

文字列の分割

 
s = '1,2,3,4,5,6,7,8,9'
print s.split(',') # ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print s.split(',')[0] # 1
 

マッチした部分をすべて表示する

 
import re
f = open("html/book/19-Mastering-Symfony-s-Configuration-Files.html", "r")
r = re.compile("<pre><code>\[php\].+?</code></pre>", re.S)
print r.findall(f.read())
 

ドキュメント管理

Pygmentsでコードをハイライトする

インストール

easy_install Pygments

言語ごとにlexerを指定する必要がある(利用可能なlexerはhttp://pygments.org/docs/lexers/ を参照)。PHPの場合は以下の通り。

 
# -*- coding: utf-8 -*-
 
from pygments import highlight
from pygments.lexers import PhpLexer
from pygments.formatters import HtmlFormatter
 
code = 'print "Hello World"'
print highlight(code, PhpLexer(startinline=True), HtmlFormatter())
 

CGIから行うには以下の通り。

 
#!/Python/python
# -*- coding: utf-8 -*-
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
 
code = '''
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
print \'\'\'Content-Type: text/html\'\'\'
'''
 
print '''Content-Type: text/html'''
print '''
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">'''
print HtmlFormatter().get_style_defs('.highlight')
print '''</style>
<title>コードのハイライト</title>
</head>
'''
print highlight(code, PythonLexer(), HtmlFormatter())
print '''
<body>
</body>
</html>
'''
 

CSSの作成

コマンドラインでは以下の通り。

pygmentize -f html -S colorful -a .highlight > sample.css

コードから作成するには以下の通り。

 
from pygments.formatters import HtmlFormatter
 
f = open('sample.css', 'w')
f.write(HtmlFormatter().get_style_defs('.highlight'))
f.close()
 

docutils

http://docutils.sourceforge.net/

より最新のバージョンを入手する。

C:\Python\Scriptsに以下のようなbatファイルを作成する

rst2html.bat

@python c:\Python\Scripts\rst2html.py %*

rst2xml.bat

@python c:\Python\Scripts\rst2xml.py %*

rst2latex.bat

@python c:\Python\Scripts\rst2latex.py %*

rst2newlatexl.bat

@python c:\Python\Scripts\rst2newlatex.py %*

使い方の例

rst2html test.txt test.html

test.txt

タイトル
========

見出し
------

1) リスト1

2) リスト2

3) リスト3

test.html

<div class="document" id="id1">
<h1 class="title">タイトル</h1>
<h2 class="subtitle" id="id2">見出し</h2>
<ol class="arabic simple">
<li>リスト1</li>
<li>リスト2</li>
<li>リスト3</li>

markdown

インストール方法

easy_install markdown


[python]
# -*- coding: utf-8 -*-
import markdown

str = u"""
タイトル
======
本文"""
html = markdown.markdown(str)
print html

ファイルを読み込む例 [python] # -- coding: utf-8 -- import codecs, markdown

f = codecs.open('test.txt', 'r', 'utf-8')
text = f.read()
f.close()
print markdown.markdown(text)

参考 * Markdown in Python: Using as a Module

ファイル・ディレクトリ

ディレクトリの区切り文字

 
import os
print os.sep
 

パスの正規化

 
import os.path
path = "c:\\test/test2/test3/test4"
print os.path.normpath(path)
 

ファイルのサイズを表示する

 
import os
print os.path.getsize('svn-book-html-chunk\\index.html')
 

指定した拡張子を持つファイルの一覧

 
import glob
list = glob.glob("*.html")
for x in list:
    print x
 

入れ子のディレクトリを作成する

 
import os
os.makedirs('a/b/c/d')
 

指定したディレクトリ内のファイル一覧を表示する

 
import os
print os.listdir("C:/downloads")
 

現在のディレクトリ内のファイルを表示する

getcwd( )よりもユニコードオブジェクトのgetcwdu()が望ましい。

 
# -*- coding: utf-8 -*-
import os
print os.listdir(os.getcwdu())
 

空ファイルを作成する

 
f = open('test.txt', 'w').close()
 

日本語

エンコーディング

 
# -*- coding: utf-8 -*-
str = u'こんにちは'
print str
 
str = 'こんばんは'
str = unicode(str, 'utf-8')
 

日本語名スクリプトを実行する

スクリプトのファイル名は日本語でも実行できる。

python 日本語.py

日本語.py

 
# -*- coding: utf-8 -*-
print u"日本語"
 

日本語名ファイルを作成する(Win)

 
# -*- coding: utf-8 -*-
str = u'こんにちは.txt'.encode('cp932')
f = open(str, "w").close()
 

サポートされるエンコーディング

Python ライブラリリファレンス - 4.9.2 標準エンコーディングを参照

コマンドラインで日本語を表示する

 
# -*- coding: utf-8 -*-
print u'日本語'
print unicode('日本語', 'utf-8')
print u'日本語'.encode('cp932')
 

エンコードを指定してファイルを読み込む

 
# -*- coding: utf-8 -*-
import codecs
f = codecs.open('test.txt', 'r', 'utf-8')
print f.read()
f.close()
 

コマンドラインのエンコーディングを調べる

 
import locale
print locale.getpreferredencoding()
 

URIエンコード・デコード

 
# -*- coding: utf-8; -*-
import urllib2
str = u'日本語'.encode('utf-8')
str2 = '%E6%97%A5%E6%9C%AC%E8%AA%9E'
print urllib2.quote(str)
print urllib2.unquote(str2).decode('utf-8')
 

数値文字参照

 
str = u'君子务本'
print str.encode('latin_1', 'xmlcharrefreplace')
 

リストの連結

 
# -*- coding: utf-8 -*-
strings = ['あ', 'い', 'う', 'え', 'お']
print ''.join([unicode(str, 'utf-8') for str in strings])
 
result = ''
for str in strings:
    result = result + unicode(str, 'utf-8')
print result
 

Apache

mod_wsgi

インストール

Ubuntu

8.04(hardy)ではパッケージ(libapache2-mod-wsgi)が用意されているが7.10(gutsy)では用意されていないのでコンパイルする。 ビルドするためにはapxs2も必要なので次のライブラリをインストールする。

sudo apt-get install apache2-threaded-dev

ソースをダウンロードしてコンパイルする。

wget http://modwsgi.googlecode.com/files/mod_wsgi-2.0c4.tar.gz
tar xvfz mod_wsgi-2.0c4.tar.gz
cd mod_wsgi-2.0c4
./configure
make
sudo make install

無事コンパイルが終わると次のようなメッセージが表示される。

Libraries have been installed in:
   /usr/lib/apache2/modules

If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the -LLIBDIR' flag during linking and do at least one of the following: - add LIBDIR to theLD_LIBRARY_PATH' environment variable during execution - add LIBDIR to the LD_RUN_PATH' environment variable during linking - use the-Wl,--rpath -Wl,LIBDIR' linker flag - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages.

UbuntuにおいてApacheの追加モジュールの設定ファイルは/etc/apache2/mods-enalbedに設置される慣習に従って次の内容を持つmod_wsgi.loadファイルを作成する。

sudo nano /etc/apache2/mods-enabled/mod_wsgi.load

mod_wsgi.load

LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so

.loadファイルはモジュールの読み込みのみで同じディレクトリの.confファイルに それぞれのモジュール固有の設定内容を追記する。編集が終わったらApacheを再起動する。

sudo /etc/init.d/apache2 restart

Windows

http://code.google.com/p/modwsgi/wiki/InstallationOnWindows

からPythonとApacheに対応したmod_wsgi.soをダウンロードしてC:/xampp/apache/modulesディレクトリにコピーして http.confに以下の一行を追加してApacheを再起動させる。

LoadModule wsgi_module modules/mod_wsgi.so

テストスクリプト

Windows版XAMPPで行ったスクリプトの動作の確認例を示す。以下のようなtest.wsgiを作成し、http.confを編集する。編集が終わったらApacheを再起動させてhttp://localhost/myappにアクセスする。

test.wsgi

 
def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'
 
    response_headers = [('Content-type', 'text/plain'),
                            ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
 
    return [output]
 

http.conf

WSGIScriptAlias /myapp C:/xampp/cgi-bin/test.wsgi

もしくはcgiを許可しているディレクトリにSetHandler wsgi-scriptとOptions +ExecCGIを追加する。

<Directory "C:/xampp/cgi-bin">
    SetHandler wsgi-script
    AllowOverride None
    #Options None
    Options +ExecCGI
    Order allow,deny
    Allow from all
</Directory>

参考

mod_python

index.pyの追加。エイリアスでindex.pyを指定した方がよいのかもしれない。

http.conf

<IfModule dir_module>
DirectoryIndex index.php index.php4 index.php3 index.cgi index.pl index.py index.html index.htm index.shtml index.phtml
</IfModule>

モジュールの読み込みとディレクトリの設定

LoadModule python_module modules/mod_python.so
<Directory "C:/xampp/htdocs/labs"> 
  AddHandler mod_python .py
  PythonHandler index 
  PythonDebug On 
</Directory>

index.py

 
from mod_python import apache
 
def handler(req):
    req.content_type = "text/html"
    req.write("Hello World!")
    return apache.OK
 
 
http://localhost/labs/
 

にアクセスする。

CGIで動作させる

test.cgi(C:/xampp/htdocs/cgi-bin)

 
#!/Python/python
# -*- coding: utf-8 -*-
print "Content-Type: text/html"
print """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<head><title>タイトル</title></head>
テスト
<body>
</body>
</html>
"""
</source>
 

shebangは次のように省略できる。

#!/Python/python

http://localhost/cgi-bin/test.cgi にアクセスする。

CGIのエラーを出力する

下記の内容を持った.htaccessを設置する。

AddHandler cgi-script-debug .cgi

フォーマット

JSON

インストール方法は以下の通り。

easy_install demjson

コードのサンプル

 
import demjson
tel = {'jack': 4098, 'sape': 4139, 'guido': 4127}
f = open('test.txt', 'w')
f.write(demjson.encode(tel))
f.close()
 

テキストファイルを読み込む場合

 
import demjson
f = open('test.txt', 'r')
json = demjson.decode(f.read())
print json['jack']
 

YAML

インストール方法

easy_install PySyck

コードの例

 
from syck import *
 
yml = [ 'abc', 'def', 'xyz']
yml2 = '''
---
- abc
- def
- xyz
'''
 
print dump(yml)
print load(yml2)
 

インストール方法

easy_install PyYAML

コードの例

 
# -*- coding: utf-8 -*-
import yaml
 
yml = [ 'abc', 'def', 'xyz']
yml2 = '''
---
- abc
- def
- xyz
'''
 
print yaml.dump(yml)
print yaml.load(yml2)
 

データ型

辞書型を値でソート

 
import glob, os
t = glob.glob("svn-book-html-chunk\\*.html")
dic = {}
 
for x in t:
    dic[os.path.basename(x)] = os.path.getsize(x)
 
result = sorted(dic.items(), lambda x, y:cmp(x[1], y[1]), reverse=True)
 
print result
 

辞書

 
tel = {'jack': 4098, 'sape': 4139, 'guido': 4127}
print tel['jack']
 

リストの要素の個数

 
a =[1, 3, 5, 7, 9]
print len(a)
 

入れ子のリスト

 
 
p = [[2, 4], [6, 8], [10, 12]]
print p[1][0] #6
 

その他

ラムダ式によるリストの変換

 
# -*- coding: utf-8 -*-
list = [1, 3, 5, 7, 9, 11]
list = map(lambda x: x*3, list)
print list
 

importとfrom

モジュールを呼び出すにはimport文を使う。モジュール名を省略するにはfrom文を使う。以下のようなhello.pyを設置する。

hello.py

 
# hello
 
def greeting():
    return 'Hello'
 

import文を使う場合

 
>>> import hello
>>> hello.greeting()
'Hello'
 

from文を使う場合

 
>>> from hello import *
>>> greeting()
'Hello'
 

マニュアル・総合情報

トップページに戻る