GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing docs.python.org — 10. 標準ライブラリをひとめぐり 10. 標準ライブラリをひとめぐり¶10.1. オペレーティングシステムとのインターフェース¶
>>> import os >>> os.getcwd() # 現在の作業ディレクトリを返す 'C:\\Python315' >>> os.chdir('/server/accesslogs') # 現在の作業ディレクトリを変更する >>> os.system('mkdir today') # システムシェルで mkdir コマンドを実行する 0
組み込み関数 >>> import os >>> dir(os) <OSモジュールの関数すべてのリストを返す> >>> help(os) <モジュールの docstring から生成された詳細なマニュアルを返す>
>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') 'archive.db' >>> shutil.move('/build/executables', 'installdir') 'installdir' 10.2. ファイルのワイルドカード¶
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py'] 10.3. コマンドライン引数¶一般的なユーティリティスクリプトでは、コマンドライン引数を処理する必要がよくあります。
これらの引数は # ファイル demo.py import sys print(sys.argv) 以下は、コマンドライン上で ['demo.py', 'one', 'two', 'three']
import argparse parser = argparse.ArgumentParser( prog='top', description='Show top lines from each file') parser.add_argument('filenames', nargs='+') parser.add_argument('-l', '--lines', type=int, default=10) args = parser.parse_args() print(args) コマンドラインで 10.4. エラー出力のリダイレクトとプログラムの終了¶
>>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one
10.5. 文字列のパターンマッチ¶
>>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat' 最小限の機能だけが必要なら、読みやすくデバッグしやすい文字列メソッドの方がお勧めです: >>> 'tea for too'.replace('too', 'two') 'tea for two' 10.6. 数学¶
>>> import math >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # 重複なしでサンプリング [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # [0.0, 1.0) の区間内のランダムな float 0.17970987693706186 >>> random.randrange(6) # range(6) からランダムに選ばれた integer 4
>>> import statistics >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> statistics.mean(data) 1.6071428571428572 >>> statistics.median(data) 1.25 >>> statistics.variance(data) 1.3720238095238095 SciPy プロジェクト <https://scipy.org> は数値処理のための多くのモジュールを提供しています。 10.7. インターネットへのアクセス¶インターネットにアクセスしたりインターネットプロトコルを処理したりするための多くのモジュールがあります。最も単純な2つのモジュールは、 URL からデータを取得するための >>> from urllib.request import urlopen >>> with urlopen('https://docs.python.org/3/') as response: ... for line in response: ... line = line.decode() # bytes を str に変換する ... if 'updated' in line: ... print(line.rstrip()) # 末尾の改行を除く ... Last updated on Nov 11, 2025 (20:11 UTC). >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('[email protected]', '[email protected]', ... """To: [email protected] ... From: [email protected] ... ... Beware the Ides of March. ... """) >>> server.quit() (2つ目の例は localhost でメールサーバーが動いている必要があることに注意してください。) 10.8. 日付と時刻¶
>>> # 日付は簡単に作成してフォーマットできる >>> import datetime as dt >>> now = dt.date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # 日付はカレンダーに基づく計算をサポートする >>> birthday = dt.date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368 10.9. データ圧縮¶一般的なデータアーカイブと圧縮形式は、以下のようなモジュールによって直接的にサポートされます: >>> import zlib >>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979 10.10. パフォーマンスの計測¶Python ユーザの中には、同じ問題を異なったアプローチで解いた際の相対的なパフォーマンスについて知りたいという深い興味を持っている人がいます。Python は、そういった疑問に即座に答える計測ツールを提供しています。 例えば、引数の入れ替え操作に対して、伝統的なアプローチの代わりにタプルのパックやアンパックを使ってみたいと思うかもしれません。 >>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791
10.11. 品質管理¶高い品質のソフトウェアを開発するための一つのアプローチは、各関数に対して開発と同時にテストを書き、開発の過程で頻繁にテストを走らせるというものです。
def average(values): """数値のリストの算術平均を計算する。 >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # docstring に埋め込まれたテストを自動的に評価
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() # コマンドラインからこれを呼び出すとテストがすべて実行される 10.12. バッテリー同梱¶Python には「バッテリー同梱 (batteries included)」という哲学があります。 この哲学が特によく表れているのは、規模の大きなパッケージが備える洗練された堅牢な機能です。 例えば:
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |