本日は最近私がよく使うPythonのおすすめライブラリを紹介したいと思います。
Pythonエンジニアがよく使う関数であることは間違いないし、Pythonエンジニアには必需品なライブラリです。
覚えておいて損はないです。
urlparse
URL を部分文字列に分割できるライブラリですね。
実際に使用すると、下記のような感じでURLを分割できます。
>>> from urllib.parse import urlparse >>> urlparse('http://netloc/path;parameters?query=argument#fragment') ParseResult(scheme='http', netloc='netloc', path='/path', params='parameters', query='query=argument', fragment='fragment') >>> urlparse('http://netloc/path;parameters?query=argument#fragment').scheme 'http' >>> urlparse('http://netloc/path;parameters?query=argument#fragment').netloc 'netloc' >>> urlparse('http://netloc/path;parameters?query=argument#fragment').path '/path' >>> urlparse('http://netloc/path;parameters?query=argument#fragment').params 'parameters' >>> urlparse('http://netloc/path;parameters?query=argument#fragment').query 'query=argument' >>> urlparse('http://netloc/path;parameters?query=argument#fragment').fragment 'fragment'
最近私、boto3でs3の操作コードをよく書き、バケット名とプレフィックスを分ける時にはとても便利です。
下記のような感じでs3のバケット名とプレフィックスを取得できます。
>>> urlparse('s3://test/path/to/file_name.csv') ParseResult(scheme='s3', netloc='test', path='/path/to/file_name.csv', params='', query='', fragment='') >>> urlparse('s3://test/path/to/file_name.csv').netloc # バケット名 'test' >>> urlparse('s3://test/path/to/file_name.csv').path.lstrip('/') # プレフィックス 'path/to/file_name.csv'
ちなみにもう一つ、そういったファイル操作の類で役に立つ関数が
os.path.basename()
ですね。これはファイル名のみを取得できる関数です。
>>> import os >>> os.path.basename('s3://test/path/to/file_name.csv') 'file_name.csv'
urlparseとos.path.basename()を使えば、url分割やファイルパス分割がより綺麗にかけるのではないでしょうか。
boto3
Boto3はAWS SDK for Pythonライブラリです。
要するにpythonでawsサービスを動かすことのできるライブラリです。
boto3はawsを使用するPythonユーザにはなくてはならないものですね。
boto3について書いた記事がちょくちょくあるので参考にしてください。
www.yariteparker-blog.com
https://www.yariteparker-blog.com/entry/2018/12/28/Athena%E3%81%ABBoto3%E3%81%8B%E3%82%89%E3%82%AF%E3%82%A8%E3%83%AA%E3%82%92%E6%8A%95%E3%81%92Pandas%E3%81%AB%E6%A0%BC%E7%B4%8Dwww.yariteparker-blog.com
concurrent.futures
concurrent.futuresこれはマルチスレッド, マルチプロセスを実現できるpythonユーザには欠かせないライブラリです。
特にThreadPoolExecutorとProcessPoolExecutorです。
マルチスレッドとマルチプロセスについては下記ページを参考にしてください。
qiita.com
基本的にmap関数と併用することが多いです。
- マルチスレッド
>>> import logging >>> from concurrent.futures import ThreadPoolExecutor >>> >>> def test(i: str): ... logging.debug(i) ... return None ... >>> logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') >>> with ThreadPoolExecutor(max_workers=5, thread_name_prefix="thread") as executor: ... res = executor.map(test, [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) ... 280540 thread_0 1 280540 thread_0 2 280540 thread_2 3 280541 thread_0 4 280541 thread_2 5 280541 thread_3 6 280541 thread_3 7 280541 thread_3 8 280542 thread_4 9 280542 thread_4 14 280542 thread_1 11 280542 thread_2 12 280542 thread_3 13 280542 thread_4 15 280542 thread_4 19 280543 thread_4 20 280542 thread_0 10 280542 thread_3 18 280542 thread_1 16 280542 thread_2 17
- マルチプロセス
ThreadPoolExecutorをProcessPoolExecutorに変えるだけです。
2系までは multiprocessing.Pool というライブラリが定番でしたが、3系からは新たなインタフェースとして concurrent.futures が出来たので私は
concurrent.futures をよく使ってます。
基本的にシングルコアでしか動かないpythonのパフォーマンスをあげようとしたら、マルチプロセスやマルチスレッドは欠かせないですね。
tempfile
一時ファイルの作成だとか一時ディレクトリの作成にはこれが便利ですね。
どうしても、ダウンロードをしてほったらかしにしておくとゴミが溜まるので、リソースを無駄にしないという意味では、一時ファイルや一時ディレクトリはとても大事です。
>>> import tempfile >>> import os >>> >>> s = 'new file' >>> >>> with tempfile.TemporaryDirectory() as dname: ... print(dname) ... print(os.path.exists(dname)) # True (一時ディレクトリが作成されていることがわかる) ... path = os.path.join(dname, "test.txt") ... with open(path, "w") as f: ... f.write(s) ... with open(path) as f: ... print(f.read()) ... /tmp/tmp58caqygi True 8 new file >>> print(os.path.exists(dname)) # False (一時ディレクトリが削除されていることがわかる) False
まとめ
今回は私が最近よく使う4つのpythonライブラリを紹介しました。
Pythonユーザがよく使うライブラリだと思うので覚えておいて損はないです。
このようにどんどん使えるライブラリを今後も紹介できたらと思います。
- urlparse (os.path.basename)
- boto3
- concurrent.futures
- tempfile