Python 標準ライブラリー

Python 標準ライブラリー

OSへのインタフェース

os モジュールは、オペレーティングシステムと対話するための多くの関数を提供しています

  • os.environ
  • os.getenv(key, default=None)
  • os.get_exec_path(env=None)

  • os.getlogin()

  • os.getpid()
  • os.getppid()
  • os.strerror(code)

  • os.chdir(path)

  • os.getcwd()

組み込み関数 dir() および help() は、 os のような大規模なモジュールで作業をするときに、対話的な操作上の助けになります.

In [ ]:
import os

print(os.getcwd())      # Return the current working directory
os.chdir('C:/Users/904PP4148/Documents')      # Change current working directory
print(os.getcwd()) 
os.system('mkdir today')   # Run the command mkdir in the system shell

dir(os)
help(os)
 

shutil --- 高水準のファイル操作

ファイルやディレクトリの日常的な管理作業のために、より簡単に使える高水準のインタフェースが shutil モジュールで提供されています.

  • shutil.copyfile(src, dst, *, follow_symlinks=True)
  • shutil.copy(src, dst, *, follow_symlinks=True)
  • shutil.copy2(src, dst, *, follow_symlinks=True) 
    copy2() はファイルの全てのメタデータを保持しようとすることを除けば copy() と等価です。
  • shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False) 
    src をルートにしたディレクトリツリー全体をコピーして、コピー先ディレクトリを返します。
  • shutil.rmtree(path, ignore_errors=False, onerror=None) 
    ディレクトリツリー全体を削除します。
  • shutil.move(src, dst, copy_function=copy2) 
    ファイルまたはディレクトリ (src) を再帰的に別の場所 (dst) に移動して、移動先を返します。
  • shutil.disk_usage(path) 
    指定されたパスについて、ディスクの利用状況を、名前付きタプル (named tuple) で返します。
In [ ]:
import shutil

shutil.copyfile('fileA', 'fileB')
shutil.move('/build/executables', 'installdir')
 

ファイルのワイルドカード表記

glob モジュールでは、 
ディレクトリのワイルドカード検索からファイルのリストを生成するための関数を提供しています.

In [ ]:
import glob

glob.glob('*.py')
 

コマンドライン引数

In [ ]:
import sys
print(sys.argv)
 

エラー出力のリダイレクトとプログラムの終了

  • sys モジュールには、 stdin, stdout, stderr を表す属性も存在します。 
    stderr は、警告やエラーメッセージを出力して、 
    stdout がリダイレクトされた場合でも読めるようにするために便利です。

  • sys.exit() は、スクリプトを終了させるもっとも直接的な方法です。

In [ ]:
sys.stderr.write('Warning, log file not found starting a new one\n')
 

文字列のパターンマッチング

re モジュールでは、より高度な文字列処理のための正規表現を提供しています。 
正規表現は複雑な一致検索や操作に対して簡潔で最適化された解決策を提供します。

In [31]:
import re
rst = re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
print(rst)
rst = re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
print(rst)
 
['foot', 'fell', 'fastest']
cat in the hat
 

最小限の機能だけが必要なら、読みやすくデバッグしやすい文字列メソッドの方がお勧めです。

In [32]:
rst = 'tea for too'.replace('too', 'two')
print(rst)
 
tea for two
 

数学

  • math モジュールは、浮動小数点演算のための C 言語ライブラリ関数にアクセスする手段を提供しています
In [33]:
import math

print(math.cos(math.pi / 4))
print(math.log(1024, 2))
 
0.7071067811865476
10.0
 
  • random モジュールは、乱数に基づいた要素選択のためのツールを提供しています
In [38]:
import random
print(random.choice(['apple', 'pear', 'banana']))
print(random.sample(range(100), 10))    # sampling without replacement
print(random.random())    # random float
print(random.randrange(6))    # random integer chosen from range(6)
 
pear
[32, 11, 21, 86, 92, 1, 55, 65, 18, 84]
0.8716232430159375
2
 
  • statistics モジュールは数値データの基礎的な統計的特性(平均、中央値、分散等)を計算します
In [39]:
import statistics
data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.variance(data))
 
1.6071428571428572
1.25
1.3720238095238095
 
  • SciPy プロジェクト https://scipy.org は数値処理のための多くのモジュールを提供しています。
 

インターネットへのアクセス

インターネットにアクセスしたりインターネットプロトコルを処理したりするための多くのモジュールがあります。 
最も単純な2つのモジュールは、 
URL からデータを取得するための urllib.request と、 
メールを送るための smtplib です。

In [43]:
from urllib.request import urlopen
with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
    for line in response:
        line = line.decode('utf-8')  # Decoding the binary data to text.
        if 'EST' in line or 'EDT' in line:  # look for Eastern Time
            print(line)
 
<BR>Jun. 25, 10:42:47 PM EDT		Eastern Time

 
ProxyHandler --- urllibプロキシ設定
In [1]:
import urllib

proxy = urllib.request.ProxyHandler({'http': '127.0.0.1'})
opener = urllib.request.build_opener(proxy)
urllib.request.install_opener(opener)
 

localhost でメールサーバーが動いている必要がある

In [ ]:
import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
    """To: jcaesar@example.org
       From: soothsayer@example.org

       Beware the Ides of March.
    """)
server.quit()
 

日付と時刻

datetime モジュールは、日付や時刻を操作するためのクラスを、単純な方法と複雑な方法の両方で提供しています

In [49]:
from datetime import date
now = date.today()
print(now)
print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B."))

birthday = date(1964, 7, 31)
age = now - birthday
print(age.days)
 
2018-06-26
06-26-18. 26 Jun 2018 is a Tuesday on the 26 day of June.
19688
 

データ圧縮

一般的なデータアーカイブと圧縮形式は、以下のようなモジュールによって直接的にサポートされます:

In [53]:
import zlib
s = b'witch which has which witches wrist watch'
print(len(s))
t = zlib.compress(s)
print(t)
print(len(t))
print(zlib.decompress(t))
print(zlib.crc32(s))
 
41
b'x\x9c+\xcf,I\xceP(\xcf\xc8\x04\x92\x19\x89\xc5PV9H4\x15\xc8+\xca,.Q(O\x04\xf2\x00D?\x0f\x89'
37
b'witch which has which witches wrist watch'
226805979
 

パフォーマンスの計測

timeit では小さい粒度を提供しているのに対し、 
profile や pstats モジュールではより大きなコードブロックにおいて 
律速となる部分を判定するためのツールを提供しています。

In [54]:
from timeit import Timer
t1 = Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
print(t1)
t2 = Timer('a,b = b,a', 'a=1; b=2').timeit()
print(t2)
 
0.13873595824864515
0.0672354037715018
 

品質管理

  • doctest モジュールでは、モジュールを検索してプログラムの docstring 
    に埋め込まれたテストの評価を行うためのツールを提供しています。
  • unittest モジュールは、より網羅的なテストセットを別のファイルで管理することができます
In [56]:
def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
doctest.testmod()   # automatically validate the embedded tests
Out[56]:
TestResults(failed=0, attempted=1)
In [ ]:
import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20, 30, 70)

unittest.main()  # Calling from the command line invokes all tests