import

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(Omi Chiba)

import

Pythonoが本当に強力なのは、そのライブラリモジュールがあるからです。それらは、大規模で一貫性のあるアプリケーション・プログラム・インターフェース(API)を多くの(大抵オペレーティング・システムから独立した)システムライブラリに提供します。

The real power of Python is in its library modules. They provide a large and consistent set of Application Programming Interfaces (APIs) to many system libraries (often in a way independent of the operating system).

たとえば、乱数ジェネレーターを利用する必要がある場合、次のようにします:

For example, if you need to use a random number generator, you can do:

1.

2.

3.

>>> import random

>>> print random.randint(0, 9)

5

この例では、0から9の間のランダムな整数を表示します(ここでは5が表示されています)。randint関数はrandomモジュール内で定義されています。モジュールからオブジェクトを現在の名前空間にインポートすることも可能です:

This prints a random integer between 0 and 9 (including 9), 5 in the example. The functionrandint is defined in the module random. It is also possible to import an object from a module into the current namespace:

1.

2.

>>> from random import randint

>>> print randint(0, 9)

もしくは、モジュールからすべてのオブジェクトを現在の名前空間にインポートすることも可能です:

or import all objects from a module into the current namespace:

1.

2.

>>> from random import *

>>> print randint(0, 9)

さらに、すべてを新しく定義した名前空間にインポートすることも可能です:

or import everything in a newly defined namespace:

1.

2.

>>> import random as myrand

>>> print myrand.randint(0, 9)

本書の残りの部分では、 os、sys、datetime、time、cPickleといったモジュールに定義されたオブジェクトをよく利用します。

In the rest of this book, we will mainly use objects defined in modules os, sys, datetime, timeand cPickle.

すべてのweb2pyオブジェクトは、gluonと呼ばれるモジュールを介してアクセスすることができます。これは、後述の章にて扱います。内部的には、web2pyは多くのPythonモジュール(たとえばthreadなど)を使用しています。しかし、利用者が直接それらにアクセスする必要はほとんどないでしょう。

All of the web2py objects are accessible via a module called gluon, and that is the subject of later chapters. Internally, web2py uses many Python modules (for example thread), but you rarely need to access them directly.

以下の小節では、最も利用されるそれらのモジュールを考えます。

In the following subsections we consider those modules that are most useful.

os

このモジュールは、オペレーティング・システムAPIへのインターフェイスを提供します。例:

This module provides an interface to the operating system API. For example:

1.

2.

3.

>>> import os

>>> os.chdir('..')

>>> os.unlink('filename_to_be_deleted')

chdirのようなosのいくつかの関数は、web2pyのおいて使用しないでください。スレッドセーフではないからです。

Some of the os functions, such as chdir, MUST NOT be used in web2py because they are not thread-safe.

os.path.joinはとても便利で、OSに依存しない形でパスの連結が可能になります。

os.path.join is very useful; it allows the concatenation of paths in an OS-independent way:

1.

2.

3.

4.

>>> import os

>>> a = os.path.join('path', 'sub_path')

>>> print a

path/sub_path

システム環境変数はos.environを介してアクセスできます。

System environment variables can be accessed via:

1.

>>> print os.environ

これは読み取り専用の辞書です。

which is a read-only dictionary.

sys

sysモジュールは多くの変数と関数を持ちますが、最も利用するのはsys.pathです。これは、Pythonがモジュールを探すためのパスのリストを保持しています。モジュールをインポートしようとしたとき、Pythonはsys.path内にリストされたすべてのフォルダーをチェックします。どこかの場所において追加のモジュールをインストールして、それをPythonに探させたい場合、その場所へのパスをsys.pathに追加しなければなりません。

The sys module contains many variables and functions, but the one we use the most issys.path. It contains a list of paths where Python searches for modules. When we try to import a module, Python looks for it in all the folders listed in sys.path. If you install additional modules in some location and want Python to find them, you need to append the path to that location to sys.path.

1.

2.

>>> import sys

>>> sys.path.append('path/to/my/modules')

web2pyが実行されている時は、Pythonはメモリ内に常駐し、多くのスレッドがHTTPリクエストを処理している一方、sys.pathは1つしかありません。 メモリリークを回避するにためには、パスを追記する前に、それがすでに存在しているかを確認するのが最良です。

When running web2py, Python stays resident in memory, and there is only one sys.path, while there are many threads servicing the HTTP requests. To avoid a memory leak, it is best to check if a path is already present before appending:

1.

2.

3.

>>> path = 'path/to/my/modules'

>>> if not path in sys.path:

sys.path.append(path)

datetime

datetimeモジュールの使い方を説明するいくつかの例を紹介します。

The use of the datetime module is best illustrated by some examples:

1.

2.

3.

4.

5.

>>> import datetime

>>> print datetime.datetime.today()

2008-07-04 14:03:90

>>> print datetime.date.today()

2008-07-04

ローカルタイムではなく、UTCタイムに基づいたタイムスタンプデータが必要になるかもしれません。その場合、次のような関数を用いることができます:その場合では、次の関数を使用することができます:

Occasionally you may need to time-stamp data based on the UTC time as opposed to local time. In this case you can use the following function:

1.

2.

3.

>>> import datetime

>>> print datetime.datetime.utcnow()

2008-07-04 14:03:90

datetimeのモジュールには、date、datetime、time、timedeltaなど、さまざまなクラスが含まれています。2つのdate、2つのdatetime、2つのtimeオブジェクト間の差は、timedeltaになります:

The datetime modules contains various classes: date, datetime, time and timedelta. The difference between two date or two datetime or two time objects is a timedelta:

1.

2.

3.

4.

5.

>>> a = datetime.datetime(2008, 1, 1, 20, 30)

>>> b = datetime.datetime(2008, 1, 2, 20, 30)

>>> c = b - a

>>> print c.days

1

web2pyにおいて、dateとdatetimeは、データベースへ渡すときや戻されるときに、対応するSQLの型を格納するのに利用されます。

In web2py, date and datetime are used to store the corresponding SQL types when passed to or returned from the database.

time

timeモジュールはdateやdatetimeと異なり、(1970年から始まる)エポックからの秒数として時間を表現します。

The time module differs from date` and datetime` because it represents time as seconds from the epoch (beginning of 1970).

1.

2.

3.

>>> import time

>>> t = time.time()

1215138737.571

秒の時間とdatetimeの時間とを変換する関数についてはPythonドキュメントを参照してください。

Refer to the Python documentation for conversion functions between time in seconds and time as a datetime.

cPickle

cPickleはとても強力なモジュールです。cPickleは自己参照オブジェクトを含む、ほぼすべてのPythonオブジェクトをシリアライズすることができる関数を提供します。たとえば、次のような奇妙なオブジェクトを構築します:

This is a very powerful module. It provides functions that can serialize almost any Python object, including self-referential objects. For example, let's build a weird object:

1.

2.

3.

4.

>>> class MyClass(object): pass

>>> myinstance = MyClass()

>>> myinstance.x = 'something'

>>> a = [1 ,2, {'hello':'world'}, [3, 4, [myinstance]]]

そして以下のようにします:

and now:

1.

2.

3.

>>> import cPickle

>>> b = cPickle.dumps(a)

>>> c = cPickle.loads(b)

ここで、bはaの文字列表現で、cはbをデシリアライズして生成されたaのコピーです。

In this example, b is a string representation of a, and c is a copy of a generated by de-serializing b.

cPickleは、ファイルへシリアライズ、ファイルからデシリアライスすることも可能です:

cPickle can also serialize to and de-serialize from a file:

1.

2.

>>> cPickle.dump(a, open('myfile.pickle', 'wb'))

>>> c = cPickle.load(open('myfile.pickle', 'rb'))