Python 入門チュートリアル | Python でよく使われる標準ライブラリの概要

Python3標準ライブラリの概要

Python の標準ライブラリは非常に大きく、幅広いコンポーネントが提供されているため、標準ライブラリを使用することでさまざまな作業を簡単に実行できます。

以下は、Python3 標準ライブラリのいくつかのモジュールです。

  • os モジュール: os モジュールは、ファイルやディレクトリの作成、移動、削除、環境変数へのアクセスなど、オペレーティング システムと対話するための多くの機能を提供します。

  • sys モジュール: sys モジュールは、インタープリターのバージョンやパス、stdin、stdout、stderr に関連する情報など、Python インタープリターとシステムに関連する機能を提供します。

  • time モジュール: time モジュールは、現在時刻の取得、日付と時刻のフォーマット、タイミングなど、時間を処理するための関数を提供します。

  • datetime モジュール: datetime モジュールは、タイム ゾーンの処理、時差の計算、日付の差の計算など、より高度な日付と時刻の処理関数を提供します。

  • ランダム モジュール: ランダム モジュールは、ランダムな整数、浮動小数点数、シーケンスなどの生成など、乱数を生成するための関数を提供します。

  • math モジュール: math モジュールは、三角関数、対数関数、指数関数、定数などの数学関数を提供します。

  • re モジュール: re モジュールは、テキスト検索、置換、セグメント化などに使用できる正規表現処理関数を提供します。

  • json モジュール: json モジュールは、Python オブジェクトを JSON 形式に変換し、JSON 形式から Python オブジェクトを解析できる JSON エンコードおよびデコード関数を提供します。

  • urllib モジュール: urllib モジュールは、Web ページにアクセスし、ファイルのダウンロード、POST リクエストの送信、Cookie の処理などの URL を処理するための機能を提供します。

オペレーティングシステムのインターフェース

os モジュールは、オペレーティング システムに関連する多くの機能を提供します。

>>> import os
>>> os.getcwd()      # 返回当前的工作目录
'C:\\Users\\Lenovo'
>>> os.chdir(r'C:\Users\Lenovo\Desktop') # 修改当前的工作目录 使用r原始字符串(raw string),可以不需要双反斜杠
>>> os.system('mkdir today') # 执行windows shell系统命令 mkdir,生成名为today的文件夹
0

「from os import *」の代わりに「import os」スタイルを使用することをお勧めします。これにより、オペレーティング システムが異なると変更される os.open() が組み込み関数 open() を上書きしないことが保証されます。

組み込みの dir() 関数と help() 関数は、OS のような大きなモジュールを操作する場合に非常に役立ちます。

>>> import os
>>> dir(os)
['DirEntry', 'EX_OK', 'F_OK', 'GenericAlias', 'Mapping', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_AddedDllDirectory', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_walk', '_wrap_close', 'abc', 'abort', 'access', 'add_dll_directory', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'unsetenv', 'urandom', 'utime', 'waitpid', 'waitstatus_to_exitcode', 'walk', 'write']
>>> help(os)
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

MODULE REFERENCE
    https://docs.python.org/3.11/library/os.html

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This exports:
      - all functions from posix or nt, e.g. unlink, stat, etc.
      - os.path is either posixpath or ntpath
      - os.name is either 'posix' or 'nt'
      - os.curdir is a string representing the current directory (always '.')
      - os.pardir is a string representing the parent directory (always '..')
      - os.sep is the (or a most common) pathname separator ('/' or '\\')
      - os.extsep is the extension separator (always '.')
      - os.altsep is the alternate pathname separator (None or '/')
      - os.pathsep is the component separator used in $PATH etc
      - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
      - os.defpath is the default search path for executables
      - os.devnull is the file path of the null device ('/dev/null', etc.)

-- More  --

毎日のファイルとディレクトリの管理タスクのために、shutilモジュールは使いやすい高レベルのインターフェイスを提供します。

C:\Users\Lenovo>cd Desktop #切换到桌面文件夹下
C:\Users\Lenovo\Desktop>python  # 进入python交互模式
Python 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil #导入shutil模块
>>> shutil.copyfile('test.txt', 'test1.txt') #复制桌面的test.txt文件并生成test1.txt
'test1.txt'
>>> shutil.move('sourceFolder', 'targetFolder') #sourceFolder文件夹移动到targetFolder文件夹下
'targetFolder\\sourceFolder'
>>>

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

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

>>> import glob #导入模块 
>>> glob.glob('*.py') #匹配当前目录下的所有文件名为.py的文件
['dog.py', 'fibo.py', 'support.py', 'support1.py', 'test.py', 'using_name.py']

コマンドラインパラメータ

一般的なツール スクリプトは、コマンド ライン引数を呼び出すことがよくあります。これらのコマンド ライン パラメーターは、リンク リストの形式でsysモジュールのargv変数に保存されます
Python では、sys.argv は、Python スクリプトを実行するときに使用されるコマンド ライン引数を含むリストです。sys.argv[0] はスクリプト (つまり、実行される .py ファイル) の名前、sys.argv[1] は最初のコマンド ライン パラメーター、sys.argv[2] は 2 番目のコマンド ライン パラメーターです。などなど。

sys.argv の使用方法を示す簡単な例を次に示します。

import sys  
  
def main(argv):  
    # argv[0] 是脚本的名字  
    print(f"脚本的名字是: {
      
      argv[0]}")  
  
    # 从 argv[1] 开始,是我们传入的命令行参数  
    for i in range(1, len(argv)):  
        print(f"参数 {
      
      i} 是: {
      
      argv[i]}")  
  
if __name__ == "__main__":  
    main(sys.argv)

このスクリプトをscript.pyとして保存し、コマンド ラインからpython script.py arg1 arg2 arg3を実行すると、次の出力が表示されます。

C:\Users\Lenovo\Desktop>python script.py arg1 arg2 arg3
脚本的名字是: script.py
参数 1 是: arg1
参数 2 是: arg2
参数 3 是: arg3

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

sys には stdin、stdout、および stderr プロパティもあります。後者は、stdout がリダイレクトされる場合でも警告メッセージとエラー メッセージを表示するために使用できます。

>>> import sys
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
47
>>>

ほとんどのスクリプトは、指示された終了に「sys.exit()」または「exit()」を使用します。

文字列の通常の一致

re モジュールは、高度な文字列処理のための正規表現機能を提供します。複雑なマッチングと処理の場合、正規表現は簡潔で最適化されたソリューションを提供します。

>>> import re #导入模块
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') #‘which foot or hand fell fastest’ 匹配字符串中的以空格和f开头的字符串
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

単純な機能のみが必要な場合は、非常にシンプルで読み取りとデバッグが簡単な文字列メソッドを最初に検討する必要があります。

>>> import re #导入模块
>>> 'tea for too'.replace('too', 'two') # 将文本中的too替换为tweo
'tea for two'

数学

mathモジュールは、浮動小数点演算のための基礎となる C ライブラリへのアクセスを提供します。

>>> import math #导入math模块
>>> math.cos(math.pi / 4) 
0.70710678118654757
>>> math.log(1024, 2) #求1024 计算以 2 为底数的对数
10.0

random は、乱数を生成するためのツールを提供します。

>>> import random #导入模块
>>> random.choice(['apple', 'pear', 'banana']) # 在集合中随机输出一个元素
'apple'
>>> random.sample(range(100), 10)   # 在0-100中随机抽取10个数字,不包含100
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # 在0-1之间随机生成一个小数
0.17970987693706186
>>> random.randrange(6)    # 在0-6中随机返回一个证书 不包含6
4

インターネットにアクセスします

インターネットにアクセスし、ネットワーク通信プロトコルを処理するためのモジュールがいくつかあります。このうち最も単純な 2 つは、 URL から受信したデータを処理するためのurllib.requestです。

>>> from urllib.request import urlopen
>>> for line in urlopen('https://www.baidu.com/'):
...     line = line.decode('utf-8')  # Decoding the binary data to text.
...     print(line)

#输出百度网页文本...

日時

datetime モジュールは、日付と時刻を処理するための単純なメソッドと複雑なメソッドの両方を提供します。

実装では、日付と時刻のアルゴリズムをサポートしながら、出力のより効率的な処理とフォーマットに重点を置いています。

>>> import datetime #导入模块
>>> current_datetime = datetime.datetime.now() #获取当前日期和时间
>>> print(current_datetime)
2023-10-04 21:35:23.999185
>>> current_date = datetime.date.today() #获取当前日期
>>> print(current_date)
2023-10-04
>>> formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S") #格式化日期
>>> print(formatted_datetime)
2023-10-04 21:35:23
>>>

このモジュールは時間処理もサポートしています。

>>> from datetime import date   #导入了 datetime 模块中的 date 类
>>> now = date.today() #当前日期
>>> now
datetime.date(2023, 10, 4)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") #格式化输出时间
'10-04-23. 04 Oct 2023 is a Wednesday on the 04 day of October.'
>>> birthday = date(1991, 9, 20) #创建了一个表示生日的日期对象
>>> age = now - birthday  # 计算两个日期之间的时间差
>>> age.days  # 变量age的days属性,表示时间差的天数
11702

データ圧縮

次のモジュールは、一般的なデータのパッケージ化と圧縮形式を直接サポートしています: zlib、gzip、bz2、zipfile、およびtarfile

>>> import zlib #导入模块
>>> s = b'witch which has which witches wrist watch'
>>> len(s) 输出长度
41
>>> zlib.crc32(s)  进行 CRC32 校验
226805979
>>> t = zlib.compress(s) #压缩文本
>>> len(t) 输出长度
37
>>> print(t)
b'x\x9c+\xcf,I\xceP(\xcf\xc8\x04\x92\x19\x89\xc5PV9H4\x15\xc8+\xca,.Q(O\x04\xf2\x00D?\x0f\x89'
>>> s=zlib.decompress(t) #解压
>>> print(s)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)  进行 CRC32 校验
226805979
>>>
  • CRC32 チェックサムは、データの整合性検証にも使用できます。たとえば、ファイルが別の場所にコピーされる場合、CRC32 チェックサムを使用して、コピーされたファイルが元のファイルと同じであることを確認できます。ファイルの CRC32 チェックサムを計算した後、チェックサムを別の場所に保存するか、ファイルと一緒に送信します。その後、ファイルの整合性を検証する必要がある場合、ファイルの CRC32 チェックサムを再計算して、元のチェックサムと比較できます。

パフォーマンス指標

一部のユーザーは、同じ問題を解決するためのさまざまなアプローチ間のパフォーマンスの違いを理解することに興味を持っています。Python は、これらの質問に直接答える測定ツールを提供します。

たとえば、要素を交換するためにタプルのラッピングとアンパックを使用することは、従来の方法を使用するよりもはるかに魅力的に思えますが、timeit は最新の方法の方が高速であることを証明しています。
aとbの値を交換します

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() #计算执行代码耗时
0.03332749998662621
>>> Timer('a,b = b,a', 'a=1; b=2').timeit() #计算执行代码耗时
0.024641399970278144 

timeitの粒度の細かさと比較してprofileおよびpstatsモジュールは、より大きなコード ブロックに対する時間測定ツールを提供します。

テストモジュール

高品質のソフトウェアを開発する 1 つの方法は、機能ごとにテスト コードを開発し、開発プロセス中に頻繁にテストすることです。

doctest モジュールは、モジュールをスキャンし、プログラムに埋め込まれた docstring に基づいてテストを実行するツールを提供します。

構成のテストは、その出力を切り取って docstring に貼り付けるだけで簡単です。

doctest は Python の組み込みモジュールで、コードに実行可能サンプルを埋め込むことで単体テストを作成できます。これらの例は、doctest モジュールによって抽出して実行でき、実際の出力と予想される出力を比較できます。2 つが一致する場合はテストに合格し、一致しない場合はテストは失敗します。

doctest を使用した簡単な例を次に示します。

def add(a, b):  
    """  
    This function adds two numbers.  
      
    >>> add(1, 2)  
    3  
    >>> add(-1, -2)  
    -3  
    """  
    return a + b  
  
if __name__ == "__main__":  
    import doctest  
    doctest.testmod()

この例では、add 関数の docstring に 2 つの doctest サンプルが含まれています。このスクリプトを実行すると、doctest.testmod() はこれらの例を見つけて実行し、実際の出力と予想される出力を比較します。

このスクリプトの出力は次のようになります。

**********************************************************************  
File "__main__", line 7, in __main__.add  
Failed example:  
    add(1, 2)  
Expected:  
    3  
Got:  
    3  
**********************************************************************  
File "__main__", line 9, in __main__.add  
Failed example:  
    add(-1, -2)  
Expected:  
    -3  
Got:  
    -3  
**********************************************************************  
2 items had failures:  
   1 of   2 in __main__.add  
   2 of   2 in __main__  
***Test Failed*** 2 failures.
  • Expected (期待される結果) と Got (実際の結果) は同じであり、テスト ケースが正しいことを示します。

Unittest モジュールは doctest モジュールほど簡単ではありませんが、より包括的なテスト セットを別のファイルで提供できます。
次のコードを含む test.py スクリプト ファイルを作成します。

import unittest

def average(values):
     return sum(values) / len(values)

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)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

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

test.py ファイルを実行すると、出力は次のようになります。

C:\Users\Lenovo\Desktop>python test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

上記で示したものは、Python3 標準ライブラリのモジュールの一部にすぎません。他にも多くのモジュールがあります。標準ライブラリの完全なドキュメントは、公式ドキュメントで参照できます: https://docs.python.org/zh-cn /3/ライブラリ/インデックス .html

おすすめ

転載: blog.csdn.net/weixin_40986713/article/details/133561965