tag:crieit.net,2005:https://crieit.net/tags/%E5%AD%A6%E7%BF%92/feed 「学習」の記事 - Crieit Crieitでタグ「学習」に投稿された最近の記事 2022-02-11T20:11:36+09:00 https://crieit.net/tags/%E5%AD%A6%E7%BF%92/feed tag:crieit.net,2005:PublicArticle/18054 2022-02-11T20:11:36+09:00 2022-02-11T20:11:36+09:00 https://crieit.net/posts/python-standard-library-abc Python 標準ライブラリ abc 抽象基底クラス <p>Python標準のabcクラスを使用すると抽象基底クラスを表現できる。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <p>デコレータ<code>@abstractmethod</code>をメソッドの一番内側につけることで、<br /> 抽象メソッドやプロパティを定義できる。</p> <pre><code class="python">from abc import ABC, abstractmethod class SampleABC(ABC): @abstractmethod def sample_abstract_method(self): pass @classmethod @abstractmethod def sample_abstract_classmethod(cls): pass @staticmethod @abstractmethod def sample_abstract_staticmethod(): pass @property @abstractmethod def sample_abstract_property(self): pass @sample_abstract_property.setter @abstractmethod def sample_abstract_property(self, val): pass @abstractmethod def _get_prop(self): pass @abstractmethod def _set_prop(self, val): pass def _get_prop2(self): pass def _set_prop2(self, val): pass def concrete_method(): print('hello') prop = property(_get_prop, _set_prop) prop2 = property(_get_prop2, _set_prop2) </code></pre> <p><code>@abstractmethod</code>を実装せずに継承したクラスを定義し、インスタンス化すると例外が発生する。</p> <pre><code class="python">class ExtendSampleABC(SampleABC): pass esabc = ExtendSampleABC() # TypeError: Can't instantiate abstract class ExtendSampleABC with # abstract methods _get_prop, _set_prop, prop, # sample_abstract_classmethod, sample_abstract_method, # sample_abstract_property, sample_abstract_staticmethod </code></pre> <p>以下のように実装を行うと例外は発生しない。</p> <pre><code class="python">class ConcreteSampleABC(SampleABC): def __init__(self): self._property = 0 self._prop = '' def sample_abstract_method(self): pass @classmethod def sample_abstract_classmethod(cls): pass @staticmethod def sample_abstract_staticmethod(): pass @property def sample_abstract_property(self): return self._property @sample_abstract_property.setter def sample_abstract_property(self, value): self._property = value def _get_prop(self): return self._prop def _set_prop(self, value): self._prop = value prop = property(_get_prop, _set_prop) csabc = ConcreteSampleABC() </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/abc.py">cpython/abc.py at 3.10 · python/cpython</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/abc.html">abc --- 抽象基底クラス — Python 3</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/18053 2022-02-11T20:08:59+09:00 2022-02-11T20:08:59+09:00 https://crieit.net/posts/python-standard-library-contextlib Python 標準ライブラリ contextlib with文用コンテキスト <p>Python標準のライブラリcontextlibを使うと、with文に対応したコンテキストを表現できます。</p> <h2 id="デコレータでコンテキストマネージャーを使用"><a href="#%E3%83%87%E3%82%B3%E3%83%AC%E3%83%BC%E3%82%BF%E3%81%A7%E3%82%B3%E3%83%B3%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%83%9E%E3%83%8D%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%BC%E3%82%92%E4%BD%BF%E7%94%A8">デコレータでコンテキストマネージャーを使用</a></h2> <p>ContextDecoratorを継承してクラスを宣言することで、コンテキストマネージャーとしてデコレータで使えるようになる。<br /> 非同期版のAsyncContextDecoratorもある。</p> <pre><code class="python">from contextlib import ContextDecorator class SampleContext(ContextDecorator): def __enter__(self): print('__enter__') return self def __exit__(self, *args): print('__exit__') return False @SampleContext() def sample_function(): print('sample_function') sample_function() </code></pre> <pre><code class="tex">__enter__ sample_function __exit__ </code></pre> <h2 id="with文から抜ける時にcloseしてくれるコンテキストマネージャー"><a href="#with%E6%96%87%E3%81%8B%E3%82%89%E6%8A%9C%E3%81%91%E3%82%8B%E6%99%82%E3%81%ABclose%E3%81%97%E3%81%A6%E3%81%8F%E3%82%8C%E3%82%8B%E3%82%B3%E3%83%B3%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%83%9E%E3%83%8D%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%BC">with文から抜ける時にcloseしてくれるコンテキストマネージャー</a></h2> <p><code>closing</code>で指定したクラスのcloseメソッドを終了時に呼び出してくれるコンテキストマネージャーを取得できる。<br /> 非同期版はaclosingを使用する。</p> <pre><code class="python">from contextlib import closing class SampleClass: def close(self): print('close') def hello(self): print('hello') with closing(SampleClass()) as c: c.hello() </code></pre> <pre><code class="text">hello close </code></pre> <h2 id="関数をコンテキストマネージャーとして使えるようにする"><a href="#%E9%96%A2%E6%95%B0%E3%82%92%E3%82%B3%E3%83%B3%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%83%9E%E3%83%8D%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%BC%E3%81%A8%E3%81%97%E3%81%A6%E4%BD%BF%E3%81%88%E3%82%8B%E3%82%88%E3%81%86%E3%81%AB%E3%81%99%E3%82%8B">関数をコンテキストマネージャーとして使えるようにする</a></h2> <p><code>@contextmanager</code>デコレーを付与することで、関数をコンテキストマネージャーとして使えるようにできる。<br /> 関数はyieldを返す必要がある。<br /> 非同期版は<code>@asynccontextmanager</code>。</p> <pre><code class="python">from contextlib import contextmanager @contextmanager def sample_context(): print('create sample context') try: yield 'yield here' finally: print('exit sample context') with sample_context() as sc: print(sc) </code></pre> <pre><code class="text">create sample context yield here exit sample context </code></pre> <h2 id="コンテキストマネージャーが取得できない場合"><a href="#%E3%82%B3%E3%83%B3%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%83%9E%E3%83%8D%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%BC%E3%81%8C%E5%8F%96%E5%BE%97%E3%81%A7%E3%81%8D%E3%81%AA%E3%81%84%E5%A0%B4%E5%90%88">コンテキストマネージャーが取得できない場合</a></h2> <p>openに失敗した場合なども含め、with文で統一して処理を記述したいような時に<code>nullcontext</code>を使うことができる。</p> <pre><code class="python">import contextlib def get_context_or_nullcontext(): f = None try: f = open('./sample.txt') except Exception as e: print(e) finally: if f is None: f = contextlib.nullcontext('enter_result') return f with get_context_or_nullcontext() as c: print(c) # TextIOWrapper or 'enter_result' </code></pre> <h2 id="標準出力先を変更"><a href="#%E6%A8%99%E6%BA%96%E5%87%BA%E5%8A%9B%E5%85%88%E3%82%92%E5%A4%89%E6%9B%B4">標準出力先を変更</a></h2> <p><code>redirect_stdout</code>で標準出力先を変更できる。<br /> 以下はprintで標準出力ではなくsample.txtに内容が書き込まれる。</p> <pre><code class="python">with open('./sample.txt', 'w') as f: with contextlib.redirect_stdout(f) as a: print('write!') </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/contextlib.py">cpython/contextlib.py at 3.10 · python/cpython</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/contextlib.html">contextlib --- with 文コンテキスト用ユーティリティ — Python 3</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/18052 2022-02-11T20:06:38+09:00 2022-02-11T20:06:38+09:00 https://crieit.net/posts/python-standard-library-builtins Python 標準ライブラリ builtins 組み込みオブジェクト <p>builtinsライブラリを使うとPythonの標準に用意されている<br /> <a target="_blank" rel="nofollow noopener" href="https://marusankakusikaku.jp/python/grammer/built-in-functions/">組み込みの関数</a>や<br /> <a target="_blank" rel="nofollow noopener" href="https://marusankakusikaku.jp/python/grammer/built-in-constants/">定数</a>や<br /> にアクセスできます。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <p>以下のように<a target="_blank" rel="nofollow noopener" href="https://marusankakusikaku.jp/python/built-in-types/list/">list()</a>にアクセスできます。</p> <pre><code class="python">items = builtins.list() items # => </code></pre> <p>アクセスできる関数・定数は以下の通り。</p> <pre><code class="python">[print(x) for x in dir(builtins) if not str(x).startswith('_') ] </code></pre> <pre><code class="text">ArithmeticError AssertionError AttributeError BaseException BlockingIOError BrokenPipeError BufferError BytesWarning ChildProcessError ConnectionAbortedError ConnectionError ConnectionRefusedError ConnectionResetError DeprecationWarning EOFError Ellipsis EnvironmentError Exception False FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt LookupError MemoryError ModuleNotFoundError NameError None NotADirectoryError NotImplemented NotImplementedError OSError OverflowError PendingDeprecationWarning PermissionError ProcessLookupError RecursionError ReferenceError ResourceWarning RuntimeError RuntimeWarning StopAsyncIteration StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TimeoutError True TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning WindowsError ZeroDivisionError abs all any ascii bin bool breakpoint bytearray bytes callable chr classmethod compile complex copyright credits delattr dict dir display divmod enumerate eval exec filter float format frozenset get_ipython getattr globals hasattr hash help hex id input int isinstance issubclass iter len license list locals map max memoryview min next object oct open ord pow print property range repr reversed round set setattr slice sorted staticmethod str sum super tuple type vars zip </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/builtins.html">builtins --- 組み込みオブジェクト — Python 3</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/18051 2022-02-11T20:02:35+09:00 2022-02-11T20:02:35+09:00 https://crieit.net/posts/python-standard-library-sysconfig Python 標準ライブラリ sysconfig Python構成情報 <p>Pythonの構成情報を取得する。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <pre><code class="python">import sysconfig sysconfig.get_python_version() # =&gt; 3.9 sysconfig.get_platform() # =&gt; 'win-amd64' sysconfig.get_scheme_names() # =&gt; ('nt', # 'nt_user', # 'osx_framework_user', # 'posix_home', # 'posix_prefix', # 'posix_user') sysconfig.get_path_names() # =&gt; ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', 'scripts', 'data') sysconfig.get_paths() # =&gt; {'stdlib': 'C:\\Users\\testuser\\AppData\\Local\\Programs\\Python\\Python39\\Lib', # 'platstdlib': 'c:\\home\\workspace\\sample\\Lib', # 'purelib': 'c:\\home\\workspace\\sample\\Lib\\site-packages', # 'platlib': 'c:\\home\\workspace\\sample\\Lib\\site-packages', # 'include': 'C:\\Users\\testuser\\AppData\\Local\\Programs\\Python\\Python39\\Include', # 'platinclude': 'C:\\Users\\testuser\\AppData\\Local\\Programs\\Python\\Python39\\Include', # 'scripts': 'c:\\home\\workspace\\sample\\Scripts', # 'data': 'c:\\home\\workspace\\sample'} </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/sysconfig.py">cpython/sysconfig.py at 3.10 · python/cpython</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/sysconfig.html">sysconfig --- Python の構成情報にアクセスする — Python 3</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/18050 2022-02-11T19:58:56+09:00 2022-02-11T19:58:56+09:00 https://crieit.net/posts/Python-http-client-HTTP Python 標準ライブラリ http.client HTTPクライアント <p>Pythonの標準のHTTPクライアントライブラリhttp.clientは<a target="_blank" rel="nofollow noopener" href="https://marusankakusikaku.jp/python/standard-library/urllib.request/">urllib.request</a>で使われている。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <p>以下のようにHTTP要求を投げることができる。</p> <pre><code class="python">import http.client connection = http.client.HTTPSConnection("example.jp") connection.request("GET", "/") response = connection.getresponse() connection.close() print(response.getheaders()) print(response.getheader('Content-Length')) print(response.headers) print(response.msg) print(response.closed) # => True print(response.reason) # => OK print(response.status) # => 200 print(response.version) # => 11 print(response.read()) </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/http/client.py">cpython/client.py at 3.10 · python/cpython</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/http.client.html">http.client --- HTTP プロトコルクライアント — Python 3</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/18049 2022-02-11T19:50:46+09:00 2022-02-11T19:50:46+09:00 https://crieit.net/posts/python-standard-library-http Python 標準ライブラリ http HTTP <p>http.HTTPStatusには各種HTTPステータスコードの列挙が登録されている。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <p>HTTPStatus.OK(200)やHTTPStatus.NOT_FOUND(404)等、HTTPステータスコードにアクセスできる。</p> <pre><code class="python">from http import HTTPStatus HTTPStatus.OK HTTPStatus.NOT_FOUND HTTPStatus.NOT_FOUND.name # => 'Not Found' HTTPStatus.NOT_FOUND.phrase # => 'Not Found' HTTPStatus.NOT_FOUND.value # => 404 </code></pre> <h2 id="HTTPステータスの列挙"><a href="#HTTP%E3%82%B9%E3%83%86%E3%83%BC%E3%82%BF%E3%82%B9%E3%81%AE%E5%88%97%E6%8C%99">HTTPステータスの列挙</a></h2> <p>HTTPステータスコード全体はforで列挙できる。</p> <pre><code class="python">for status in HTTPStatus: print(f"{status.name}|{status.value}|{status.phrase}|{status.description}") </code></pre> <pre><code class="text">CONTINUE|100|Continue|Request received, please continue SWITCHING_PROTOCOLS|101|Switching Protocols|Switching to new protocol; obey Upgrade header PROCESSING|102|Processing| EARLY_HINTS|103|Early Hints| OK|200|OK|Request fulfilled, document follows CREATED|201|Created|Document created, URL follows ACCEPTED|202|Accepted|Request accepted, processing continues off-line NON_AUTHORITATIVE_INFORMATION|203|Non-Authoritative Information|Request fulfilled from cache NO_CONTENT|204|No Content|Request fulfilled, nothing follows RESET_CONTENT|205|Reset Content|Clear input form for further input PARTIAL_CONTENT|206|Partial Content|Partial content follows MULTI_STATUS|207|Multi-Status| ALREADY_REPORTED|208|Already Reported| IM_USED|226|IM Used| MULTIPLE_CHOICES|300|Multiple Choices|Object has several resources -- see URI list MOVED_PERMANENTLY|301|Moved Permanently|Object moved permanently -- see URI list FOUND|302|Found|Object moved temporarily -- see URI list SEE_OTHER|303|See Other|Object moved -- see Method and URL list NOT_MODIFIED|304|Not Modified|Document has not changed since given time USE_PROXY|305|Use Proxy|You must use proxy specified in Location to access this resource TEMPORARY_REDIRECT|307|Temporary Redirect|Object moved temporarily -- see URI list PERMANENT_REDIRECT|308|Permanent Redirect|Object moved permanently -- see URI list BAD_REQUEST|400|Bad Request|Bad request syntax or unsupported method UNAUTHORIZED|401|Unauthorized|No permission -- see authorization schemes PAYMENT_REQUIRED|402|Payment Required|No payment -- see charging schemes FORBIDDEN|403|Forbidden|Request forbidden -- authorization will not help NOT_FOUND|404|Not Found|Nothing matches the given URI METHOD_NOT_ALLOWED|405|Method Not Allowed|Specified method is invalid for this resource NOT_ACCEPTABLE|406|Not Acceptable|URI not available in preferred format PROXY_AUTHENTICATION_REQUIRED|407|Proxy Authentication Required|You must authenticate with this proxy before proceeding REQUEST_TIMEOUT|408|Request Timeout|Request timed out; try again later CONFLICT|409|Conflict|Request conflict GONE|410|Gone|URI no longer exists and has been permanently removed LENGTH_REQUIRED|411|Length Required|Client must specify Content-Length PRECONDITION_FAILED|412|Precondition Failed|Precondition in headers is false REQUEST_ENTITY_TOO_LARGE|413|Request Entity Too Large|Entity is too large REQUEST_URI_TOO_LONG|414|Request-URI Too Long|URI is too long UNSUPPORTED_MEDIA_TYPE|415|Unsupported Media Type|Entity body in unsupported format REQUESTED_RANGE_NOT_SATISFIABLE|416|Requested Range Not Satisfiable|Cannot satisfy request range EXPECTATION_FAILED|417|Expectation Failed|Expect condition could not be satisfied IM_A_TEAPOT|418|I'm a Teapot|Server refuses to brew coffee because it is a teapot. MISDIRECTED_REQUEST|421|Misdirected Request|Server is not able to produce a response UNPROCESSABLE_ENTITY|422|Unprocessable Entity| LOCKED|423|Locked| FAILED_DEPENDENCY|424|Failed Dependency| TOO_EARLY|425|Too Early| UPGRADE_REQUIRED|426|Upgrade Required| PRECONDITION_REQUIRED|428|Precondition Required|The origin server requires the request to be conditional TOO_MANY_REQUESTS|429|Too Many Requests|The user has sent too many requests in a given amount of time ("rate limiting") REQUEST_HEADER_FIELDS_TOO_LARGE|431|Request Header Fields Too Large|The server is unwilling to process the request because its header fields are too large UNAVAILABLE_FOR_LEGAL_REASONS|451|Unavailable For Legal Reasons|The server is denying access to the resource as a consequence of a legal demand INTERNAL_SERVER_ERROR|500|Internal Server Error|Server got itself in trouble NOT_IMPLEMENTED|501|Not Implemented|Server does not support this operation BAD_GATEWAY|502|Bad Gateway|Invalid responses from another server/proxy SERVICE_UNAVAILABLE|503|Service Unavailable|The server cannot process the request due to a high load GATEWAY_TIMEOUT|504|Gateway Timeout|The gateway server did not receive a timely response HTTP_VERSION_NOT_SUPPORTED|505|HTTP Version Not Supported|Cannot fulfill request VARIANT_ALSO_NEGOTIATES|506|Variant Also Negotiates| INSUFFICIENT_STORAGE|507|Insufficient Storage| LOOP_DETECTED|508|Loop Detected| NOT_EXTENDED|510|Not Extended| NETWORK_AUTHENTICATION_REQUIRED|511|Network Authentication Required|The client needs to authenticate to gain network access </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/http/__init__.py">cpython/<strong>init</strong>.py at 3.10 · python/cpython</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/http.html">http --- HTTP モジュール群 — Python 3</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/18016 2022-02-10T00:25:47+09:00 2022-02-10T00:25:47+09:00 https://crieit.net/posts/python-standard-library-urllib-parse Python 標準ライブラリ urllib.parse URLの解析 <p>標準ライブラリurllib.parseには、URLの解析をするための関数が用意されている。</p> <h2 id="URLの解析"><a href="#URL%E3%81%AE%E8%A7%A3%E6%9E%90">URLの解析</a></h2> <pre><code class="python">import urllib.parse url = urllib.parse.urlparse('http://www.example.jp:80/test/path?q=some value&r=http://[email protected]/&search=a+b,c;$') # =&gt; ParseResult(scheme='http', netloc='www.example.jp:80', path='/test/path', params='', query='q=some value&r=http://[email protected]/&search=a+b,c;$', fragment='') urllib.parse.urlsplit('http://www.example.jp:80/test/path?q=some value&r=http://[email protected]/&search=a+b,c;$') # =&gt; SplitResult(scheme='http', netloc='www.example.jp:80', path='/test/path', query='q=some value&r=http://[email protected]/&search=a+b,c;$', fragment='') </code></pre> <h2 id="URLクエリーの解析"><a href="#URL%E3%82%AF%E3%82%A8%E3%83%AA%E3%83%BC%E3%81%AE%E8%A7%A3%E6%9E%90">URLクエリーの解析</a></h2> <pre><code class="python">urllib.parse.parse_qs('key1=value1&key2=&test%3Da%26da%20a a=xyz') # =&gt; {'key1': ['value1'], 'test=a&da a a': ['xyz']} urllib.parse.parse_qs('key1=value1&key2=&test%3Da%26da%20a a=xyz', keep_blank_values=True) # =&gt; {'key1': ['value1'], 'key2': [''], 'test=a&da a a': ['xyz']} urllib.parse.parse_qsl('key1=value1&key2=&test%3Da%26da%20a a=xyz') # =&gt; [('key1', 'value1'), ('test=a&da a a', 'xyz')] urllib.parse.parse_qsl('key1=value1&key2=&test%3Da%26da%20a a=xyz', keep_blank_values=True) # =&gt; [('key1', 'value1'), ('key2', ''), ('test=a&da a a', 'xyz')] </code></pre> <h2 id="URLの要素からURLを組み立てる"><a href="#URL%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%8B%E3%82%89URL%E3%82%92%E7%B5%84%E3%81%BF%E7%AB%8B%E3%81%A6%E3%82%8B">URLの要素からURLを組み立てる</a></h2> <pre><code class="python">urllib.parse.urlunparse(('http', 'www.example.jp:80', '/test/path', '', 'q=some value&r=http://user@ex # =&gt; 'http://www.example.jp:80/test/path?q=some value&r=http://[email protected]/&search=a+b,c;$' urllib.parse.urlunsplit(('http', 'www.example.jp:80', '/test/path', '', 'q=some value&r=http://[email protected]/&search=a+b,c;$')) # =&gt; 'http://www.example.jp:80/test/path#q=some value&r=http://[email protected]/&search=a+b,c;$' </code></pre> <h2 id="URLの結合"><a href="#URL%E3%81%AE%E7%B5%90%E5%90%88">URLの結合</a></h2> <pre><code class="python">urllib.parse.urljoin('https://www.example.jp/a/b/c.txt','/x/y.txt') # =&gt; 'https://www.example.jp/x/y.txt' urllib.parse.urljoin('https://www.example.jp/a/b/c.txt','x/y.txt') # =&gt; 'https://www.example.jp/a/b/x/y.txt' </code></pre> <h2 id="辞書からクエリーパラメータを構成"><a href="#%E8%BE%9E%E6%9B%B8%E3%81%8B%E3%82%89%E3%82%AF%E3%82%A8%E3%83%AA%E3%83%BC%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E3%82%92%E6%A7%8B%E6%88%90">辞書からクエリーパラメータを構成</a></h2> <pre><code class="python">data = {} data['key1'] = 'value1' data['key2'] = 'value2' urllib.parse.urlencode(data) # => key1=value1&key2=value2 </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/urllib/parse.py">cpython/parse.py at 3.10 · python/cpython · GitHub</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/urllib.parse.html">urllib.parse --- URL を解析して構成要素にする</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/18015 2022-02-10T00:25:05+09:00 2022-02-10T00:25:05+09:00 https://crieit.net/posts/python-standard-library-urllib-request Python 標準ライブラリ urllib.request URLのリクエスト <p>Python標準のライブラリurllib.requestを使うとURLをリクエストして結果を取得することができます。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <p>以下のようにURLを指定して結果を取得できます。</p> <pre><code class="python">import urllib.request with urllib.request.urlopen('https://example.jp/') as response: html = response.read() url = response.geturl() info = response.info() </code></pre> <p>HTTPSでSSL認証のエラーが発生する場合、以下を指定することで回避できる。</p> <pre><code class="python">import ssl ssl._create_default_https_context = ssl._create_unverified_context </code></pre> <h2 id="HTTP レスポンスをファイルに保存"><a href="#HTTP+%E3%83%AC%E3%82%B9%E3%83%9D%E3%83%B3%E3%82%B9%E3%82%92%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AB%E4%BF%9D%E5%AD%98">HTTP レスポンスをファイルに保存</a></h2> <p>リクエストした結果をファイルに保存する場合<br /> <a target="_blank" rel="nofollow noopener" href="https://marusankakusikaku.jp/python/standard-library/shutil/">shutil.copyfileobj</a><br /> が使えます。</p> <pre><code class="python">import shutil with urllib.request.urlopen('https://example.jp/') as response: with open('./request_out.html', mode="bw") as f: shutil.copyfileobj(response, f) </code></pre> <h2 id="エラーを想定した記載"><a href="#%E3%82%A8%E3%83%A9%E3%83%BC%E3%82%92%E6%83%B3%E5%AE%9A%E3%81%97%E3%81%9F%E8%A8%98%E8%BC%89">エラーを想定した記載</a></h2> <p>要求の応答でエラーがある場合は、HTTPErrorやURLErrorでその内容を取得できる。</p> <pre><code class="python">html = '' try: with urllib.request.urlopen('https://example.jp') as response: html = response.read() except urllib.error.HTTPError as e: print(e) print(e.code) print(e.reason) except urllib.error.URLError as e: print(e) print(e.code) print(e.reason) else: print(html) </code></pre> <h2 id="リクエストパラメータを含む要求"><a href="#%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E3%82%92%E5%90%AB%E3%82%80%E8%A6%81%E6%B1%82">リクエストパラメータを含む要求</a></h2> <h3 id="Getの要求"><a href="#Get%E3%81%AE%E8%A6%81%E6%B1%82">Getの要求</a></h3> <p>Getの要求は直接クエリーパラメータをURLに指定できる。</p> <pre><code class="python">with urllib.request.urlopen('https://example.jp/sample?key=value') as response: html = response.read() </code></pre> <p><a target="_blank" rel="nofollow noopener" href="https://marusankakusikaku.jp/python/standard-library/urllib.parse/">urllib.parse</a>のurlencodeを使うと、<br /> マッピング型のオブジェクトからURLエンコードされたクエリーパラメータを取得できます。</p> <pre><code class="python">data = {} data['key1'] = 'value1' data['key2'] = 'value2' query = urllib.parse.urlencode(data) print(query) # => key1=value1&key2=value2 with urllib.request.urlopen('https://example.jp/sample?' + query) as response: html = response.read() </code></pre> <h3 id="Postの要求"><a href="#Post%E3%81%AE%E8%A6%81%E6%B1%82">Postの要求</a></h3> <p>第2引数(data)を指定するとPOSTで要求が行われます。</p> <pre><code class="python">data = {} data['key1'] = 'value1' data['key2'] = 'value2' data_string = urllib.parse.urlencode(data) data_string = data_string.encode('ascii') print(data_string) # => b'key1=value1&key2=value2' with urllib.request.urlopen('https://example.jp/sample',data=data_string) as response: html = response.read() </code></pre> <h2 id="Requestを使った要求"><a href="#Request%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%9F%E8%A6%81%E6%B1%82">Requestを使った要求</a></h2> <p>urlopenには、リクエスト型のパラメータを指定することもできます。</p> <pre><code class="python">req = urllib.request.Request('https://example.jp/') with urllib.request.urlopen(req) as response: html = response.read() </code></pre> <p>Requestの第2引数を指定し、それをurlopenに渡すことでPOSTの要求ができる。</p> <pre><code class="python">data = {} data['key1'] = 'value1' data['key2'] = 'value2' data_string = urllib.parse.urlencode(data) data_string = data_string.encode('ascii') print(data_string) # => b'key1=value1&key2=value2' req = urllib.request.Request('https://example.jp/sample', data_string) with urllib.request.urlopen(req) as response: html = response.read() </code></pre> <h2 id="UA(ユーザーエージェント)を指定した要求"><a href="#UA%28%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%BC%E3%82%A8%E3%83%BC%E3%82%B8%E3%82%A7%E3%83%B3%E3%83%88%29%E3%82%92%E6%8C%87%E5%AE%9A%E3%81%97%E3%81%9F%E8%A6%81%E6%B1%82">UA(ユーザーエージェント)を指定した要求</a></h2> <pre><code class="python">user_agent = "Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/_BuildID_) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36" req = urllib.request.Request('https://example.jp/search?q=test', headers={'User-Agent': user_agent}, method='GET') with urllib.request.urlopen(req) as response: html = response.read() </code></pre> <h2 id="URLとパス名の変換"><a href="#URL%E3%81%A8%E3%83%91%E3%82%B9%E5%90%8D%E3%81%AE%E5%A4%89%E6%8F%9B">URLとパス名の変換</a></h2> <p>ファイルパスとURLパスを相互に変換するための関数が用意されている。</p> <pre><code class="python">urllib.request.pathname2url('/path/to/a=b+c&d=e f/[email protected]/x,y/;$/') # =&gt; '/path/to/a%3Db%2Bc%26d%3De%20f/user%40example.com/x%2Cy/%3B%24/' urllib.request.url2pathname('/path/to/a%3Db%2Bc%26d%3De%20f/user%40example.com/x%2Cy/%3B%24/') # =&gt; '\\path\\to\\a=b+c&d=e f\\[email protected]\\x,y\\;$\\' </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/urllib/request.py">cpython/request.py at 3.10 · python/cpython · GitHub</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/urllib.request.html">urllib.request --- URL を開くための拡張可能なライブラリ</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/howto/urllib2.html">urllib パッケージを使ってインターネット上のリソースを取得するには</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17977 2022-02-05T19:57:40+09:00 2022-02-05T19:57:40+09:00 https://crieit.net/posts/python-standard-library-xml-etree-ElementTree Python 標準ライブラリ xml.etree.ElementTree XMLのパース <p>Pythonの標準にあるXMLの解析で使えるライブラリxml.etree.ElementTreeの使い方です。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <p>XML文字列を読み込んで、内容を解析(パース)した結果に以下のようにアクセスできる。</p> <pre><code class="python">import xml.etree.ElementTree as ET xml_string = '''\ <?xml version="1.0"?> <rootTag attribute_sample="123"> <person some_attribute="AAA"> <name>Taro</name> <birthDate>2000-01-01</birthDate> </person> <person some_attribute="BBB"> <name>Jiro</name> <birthDate>2003-10-12</birthDate> <items> <item> <name>X001</name> <size>12.3</size> </item> <item> <name>X002</name> <size>23.4</size> </item> </items> </person> <person some_attribute="CCC"> <name>Hanako</name> <birthDate>2001-07-10</birthDate> </person> </rootTag> ''' root = ET.fromstring(xml_string) # Element root.tag # => 'rootTag' root.attrib # => {'attribute_sample': '123'} for child in root: print(f"{child.tag} {child.attrib}") # person {'some_attribute': 'AAA'} # person {'some_attribute': 'BBB'} # person {'some_attribute': 'CCC'} </code></pre> <p>ElementTreeはXML要素全体に対応するオブジェクトで、<br /> ElementはXMLの要素1つに対応するオブジェクトとなっている。</p> <p>上記はXML文字列からXML要素(Element)を取得する例になっている。</p> <h2 id="XML要素 Elementの読み込み"><a href="#XML%E8%A6%81%E7%B4%A0+Element%E3%81%AE%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF">XML要素 Elementの読み込み</a></h2> <p>xml.etree.ElementTree.parse(XMLファイルのパス)を使うとElementTreeのオブジェクトを取得できる。</p> <pre><code class="python">tree = ET.parse('sample.xml') # xml.etree.ElementTree.ElementTree object root = tree.getroot() # Element </code></pre> <p>引数にはファイルオブジェクトも指定可能。</p> <pre><code class="python">with open('./sample.xml', mode='r', encoding='utf-8') as f: tree = ET.parse(f) # xml.etree.ElementTree.ElementTree object root = tree.getroot() # Element </code></pre> <h2 id="XML要素 Element"><a href="#XML%E8%A6%81%E7%B4%A0+Element">XML要素 Element</a></h2> <h3 id="子要素のイテレータ"><a href="#%E5%AD%90%E8%A6%81%E7%B4%A0%E3%81%AE%E3%82%A4%E3%83%86%E3%83%AC%E3%83%BC%E3%82%BF">子要素のイテレータ</a></h3> <p>Elementは子要素をイテレートする。</p> <pre><code class="python">for child in root: print(f"{child.tag} {child.attrib}") # person {'some_attribute': 'AAA'} # person {'some_attribute': 'BBB'} # person {'some_attribute': 'CCC'} </code></pre> <h3 id="フィールド"><a href="#%E3%83%95%E3%82%A3%E3%83%BC%E3%83%AB%E3%83%89">フィールド</a></h3> <pre><code class="python"># タグの名称 root.tag # => 'rootTag' # 属性の辞書 root.attrib # => {'attribute_sample': '123'} # テキスト要素 root.text # => '\n ' </code></pre> <h3 id="メソッド"><a href="#%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89">メソッド</a></h3> <p>タグの名称やxPathでの要素取得は以下のように行う。</p> <pre><code class="python"># 子要素(複数の場合最初の1つ) root.find('person') # Element root.find('person/items') # Element root.find('person/items/item') # Element root.find('items') # None ## 子要素の全て root.findall('person') # Element root.findall('name') # [] ## テキスト root.findtext('person/name') # 'Taro' </code></pre> <p>子孫までを繰り返しての取得は次のように行える。</p> <pre><code class="python">for name_element in root.iter('name'): print(f"{name_element.text}") # Taro Jiro X001 X002 Hanako </code></pre> <p>iterfindはrootに対して条件を指定して要素を取得する。</p> <pre><code class="python">list(root.iterfind('name')) # => [] for name_element in root.iterfind('person/name'): print(f"{name_element.text}") # Taro Jiro Hanako </code></pre> <p>指定した要素以下のすべてのテキストノードはitertextで取得できる。</p> <pre><code class="python">list(root.find('person').itertext()) ['\n ', 'Taro', '\n ', '2000-01-01', '\n '] </code></pre> <p>属性の設定と取得は以下の様に行う。</p> <pre><code class="python">root.get('attribute_sample') # => '123' root.set('attribute_sample','321') root.items() # => [('attribute_sample', '321')] root.keys() # => ['attribute_sample'] </code></pre> <p>要素の変更は次のメソッドを使用する。</p> <pre><code class="python">element = ET.fromstring('<root><A>aaa</A></root>') # 新規要素作成 b_item = ET.Element('B') sub_item = ET.SubElement(b_item,'sub') sub_item.text = 'SS' # 要素の追加 element.append(b_item) ET.tostring(element) # => b'<root><A>aaa</A><B><sub>SS</sub></B></root>' # 要素の削除 element.remove(b_item) ET.tostring(element) # => b'<root><A>aaa</A></root>' # 新規要素作成 new_items = list() for i in range(3): sub = ET.Element('item') sub.text = str(i+1) new_items.append(sub) # 要素の複数追加 element.extend(new_items) ET.tostring(element) # => b'<root><A>aaa</A><item>1</item><item>2</item><item>3</item></root>' # 2つ目のitem要素 item_second = element.find('item[2]') # 指定位置に要素を挿入 c_item = ET.Element('C') element.insert(3, c_item) ET.tostring(element) # => b'<root><A>aaa</A><item>1</item><item>2</item><C /><item>3</item></root>' # 要素のクリア element.clear() ET.tostring(element) # => b'<root />' </code></pre> <h2 id="XMLツリー ElementTree"><a href="#XML%E3%83%84%E3%83%AA%E3%83%BC+ElementTree">XMLツリー ElementTree</a></h2> <h3 id="メソッド"><a href="#%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89">メソッド</a></h3> <pre><code class="python"># ルート要素の取得 tree.getroot() # => <Element 'rootTag' at 0x000001BD56DB2EA0 # 指定した名称・XPathで取得(最初の1つのみ) tree.find('person') # => <Element 'person' at …> # 指定した名称・XPathで取得 tree.findall('person') # => [<Element 'person' at …>, <Element 'person' at …>, <Element 'person' at …>] # 指定した名称・XPathのテキストノードを取得 tree.findtext('person') # => '\n ' for element in tree.iter(): print(f"{element.tag} {element.text}") # => 全タグについて出力 for element in tree.iter('name'): print(f"{element.text}") # Taro Jiro X001 X002 Hanako # 指定した全パスについて出力 for element in tree.iterfind'person/name'): print(f"{element.text}") # Taro Jiro Hanako # ルートからみた指定したパスについて出力 list(tree.iterfind('name')) # => [] </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <p><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/xml/etree/ElementTree.py">cpython/ElementTree.py at 3.10 · python/cpython · GitHub</a><br /> <a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/xml.etree.elementtree.html">xml.etree.ElementTree --- ElementTree XML API</a></p> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17859 2021-12-16T01:26:20+09:00 2021-12-16T01:26:20+09:00 https://crieit.net/posts/python-standard-library-base64 Python 標準ライブラリ base64 <p>Pythonの標準ライブラリbase64を使うとバイト列とbase64エンコード列の変換を行える。</p> <h2 id="バイト列→base64エンコード列"><a href="#%E3%83%90%E3%82%A4%E3%83%88%E5%88%97%E2%86%92base64%E3%82%A8%E3%83%B3%E3%82%B3%E3%83%BC%E3%83%89%E5%88%97">バイト列→base64エンコード列</a></h2> <pre><code class="python">import base64 base64.b64encode(b'ab?123') # => b'YWI/MTIz' base64.b64encode('あいうえお🐍'.encode()) # => b'44GC44GE44GG44GI44GK8J+QjQ==' </code></pre> <p>URLで問題になる可能性がある<code>/</code>や<code>+</code>の文字は第2引数を指定すると代替文字で置き換えられる。</p> <pre><code class="python">base64.b64encode(b'ab?123', b'-_') # => b'YWI_MTIz' base64.b64encode('あいうえお🐍'.encode(), b'-_') # => b'44GC44GE44GG44GI44GK8J-QjQ==' </code></pre> <h2 id="base64エンコード列→バイト列"><a href="#base64%E3%82%A8%E3%83%B3%E3%82%B3%E3%83%BC%E3%83%89%E5%88%97%E2%86%92%E3%83%90%E3%82%A4%E3%83%88%E5%88%97">base64エンコード列→バイト列</a></h2> <pre><code class="python">base64.b64decode(b'YWI/MTIz') # => b'ab?123' base64.b64decode(b'44GC44GE44GG44GI44GK8J+QjQ==').decode() # =>'あいうえお🐍' </code></pre> <p>代替文字を指定している場合、第2引数を指定してエンコードを行う。</p> <pre><code class="python">base64.b64decode(b'YWI_MTIz', b'-_') # => b'ab?123' base64.b64decode(b'44GC44GE44GG44GI44GK8J-QjQ==', b'-_').decode() # =>'あいうえお🐍' </code></pre> <p>第1引数はバイト列ではなく文字列も指定できる。</p> <pre><code class="python">base64.b64decode('YWI/MTIz') # => b'ab?123' base64.b64decode('44GC44GE44GG44GI44GK8J+QjQ==').decode() # =>'あいうえお🐍' base64.b64decode('YWI_MTIz', '-_') # => b'ab?123' base64.b64decode('44GC44GE44GG44GI44GK8J-QjQ==', '-_').decode() # =>'あいうえお🐍' </code></pre> <h2 id="標準的なbase64変換"><a href="#%E6%A8%99%E6%BA%96%E7%9A%84%E3%81%AAbase64%E5%A4%89%E6%8F%9B">標準的なbase64変換</a></h2> <p>標準的なbase64変換には、<code>standard_b64encode</code>と<code>standard_b64decode</code>が用意されている。</p> <pre><code class="python">base64.standard_b64encode(b'ab?123') # => b'YWI/MTIz' base64.standard_b64encode('あいうえお🐍'.encode()) # => b'44GC44GE44GG44GI44GK8J+QjQ==' base64.standard_b64decode(b'YWI/MTIz') # => b'ab?123' base64.standard_b64decode(b'44GC44GE44GG44GI44GK8J+QjQ==').decode() # =>'あいうえお🐍' </code></pre> <p>こちらも<code>standard_b64decode</code>には文字列も指定可能。</p> <pre><code class="python">base64.standard_b64decode('YWI/MTIz') # => b'ab?123' base64.standard_b64decode('44GC44GE44GG44GI44GK8J+QjQ==').decode() # =>'あいうえお🐍' </code></pre> <h2 id="URLセーフなbase64変換"><a href="#URL%E3%82%BB%E3%83%BC%E3%83%95%E3%81%AAbase64%E5%A4%89%E6%8F%9B">URLセーフなbase64変換</a></h2> <p><code>/</code>(スラッシュ)を<code>_</code>(アンダースコア)に、<br /> <code>+</code>(プラス)を<code>-</code>(ハイフン)の文字(記号)に変換する<br /> URLセーフなbase64変換用にも関数が用意されている。</p> <pre><code class="python">base64.urlsafe_b64encode(b'ab?123') # => b'YWI_MTIz' base64.urlsafe_b64encode('あいうえお🐍'.encode()) # => b'44GC44GE44GG44GI44GK8J-QjQ==' base64.urlsafe_b64decode(b'YWI_MTIz') # => b'ab?123' base64.urlsafe_b64decode(b'44GC44GE44GG44GI44GK8J-QjQ==').decode() # => 'あいうえお🐍' base64.urlsafe_b64decode('YWI_MTIz') # => b'ab?123' base64.urlsafe_b64decode('44GC44GE44GG44GI44GK8J-QjQ==').decode() # => 'あいうえお🐍' </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/base64.html">base64 --- Base16, Base32, Base64, Base85 データの符号化</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/base64.py">cpython/base64.py at 3.10 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17858 2021-12-16T01:22:44+09:00 2021-12-16T01:22:44+09:00 https://crieit.net/posts/python-standard-library-json Python 標準ライブラリ json JSONエンコーダ・デコーダ <p>標準に用意されているjsonライブラリを使うと、<br /> PythonオブジェクトのJSON化(直列化、シリアライズ、JSONエンコーディング)、および、<br /> JSONからPythonオブジェクトへの変換(デシリアライズ、JSONデコーディング)を行える。</p> <h2 id="JSON文字列と辞書dictの変換"><a href="#JSON%E6%96%87%E5%AD%97%E5%88%97%E3%81%A8%E8%BE%9E%E6%9B%B8dict%E3%81%AE%E5%A4%89%E6%8F%9B">JSON文字列と辞書dictの変換</a></h2> <h3 id="JSON文字列 → Pythonオブジェクト(辞書dict)"><a href="#JSON%E6%96%87%E5%AD%97%E5%88%97+%E2%86%92+Python%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%28%E8%BE%9E%E6%9B%B8dict%29">JSON文字列 → Pythonオブジェクト(辞書dict)</a></h3> <p>文字列でJSONを渡して、辞書dictで取得する。</p> <pre><code class="python">python_object = json.loads('{"name": "Taro", "age": 20, "items": [1.1, 2.2, 3.3]}') print(python_object) # =&gt; {'name': 'Taro', 'age': 20, 'items': [1.1, 2.2, 3.3]} print(type(python_object)) # =&gt; &lt;class 'dict'&gt; </code></pre> <h3 id="Pythonオブジェクト(辞書dict) → JSON文字列"><a href="#Python%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%28%E8%BE%9E%E6%9B%B8dict%29+%E2%86%92+JSON%E6%96%87%E5%AD%97%E5%88%97">Pythonオブジェクト(辞書dict) → JSON文字列</a></h3> <p>先程とは逆に辞書dictを、文字列JSONに変換する。</p> <pre><code class="python">python_object = { 'name':'Taro', 'age':20, 'items':[1.1,2.2,3.3]} json_string = json.dumps(python_object) print(json_string) # =&gt; {&quot;name&quot;: &quot;Taro&quot;, &quot;age&quot;: 20, &quot;items&quot;: [1.1, 2.2, 3.3]} print(type(json_string)) # =&gt; &lt;class 'str'&gt; </code></pre> <h2 id="ファイルオブジェクトを使ったJSONの変換"><a href="#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%9FJSON%E3%81%AE%E5%A4%89%E6%8F%9B">ファイルオブジェクトを使ったJSONの変換</a></h2> <p>文字列ではなく、ファイルオブジェクトへの書き込み・読み込みを行うための関数も用意されている。</p> <pre><code class="python"># 辞書オブジェクトをJSONにしてファイルに書き込み with open('./sample.txt', mode='w', encoding='utf-8') as f: python_object = { 'name':'Taro', 'age':20, 'items':[1.1,2.2,3.3]} json.dump(python_object, f) # ファイルに書き込んだ文字列の確認 with open('./sample.txt', mode='r', encoding='utf-8') as f: json_string = f.read() print(json_string) # => {"name": "Taro", "age": 20, "items": [1.1, 2.2, 3.3]} # ファイルを読み込んで辞書オブジェクトに変換 with open('./sample.txt', mode='r', encoding='utf-8') as f: po = json.load(f) print(po) # => {"name": "Taro", "age": 20, "items": [1.1, 2.2, 3.3]} print(type(po)) # <class 'dict'> </code></pre> <h2 id="JSON変換の引数"><a href="#JSON%E5%A4%89%E6%8F%9B%E3%81%AE%E5%BC%95%E6%95%B0">JSON変換の引数</a></h2> <p>loads/loadやdumps/dumpは変換の詳細を引数で指定できる。</p> <h3 id="loads/loadの引数 文字列またはファイルオブジェクト→辞書dict"><a href="#loads%2Fload%E3%81%AE%E5%BC%95%E6%95%B0+%E6%96%87%E5%AD%97%E5%88%97%E3%81%BE%E3%81%9F%E3%81%AF%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E2%86%92%E8%BE%9E%E6%9B%B8dict">loads/loadの引数 文字列またはファイルオブジェクト→辞書dict</a></h3> <pre><code class="python">json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) </code></pre> <ul> <li>cls カスタマイズしたデコーダを使う場合に指定</li> <li>object_hook デコードした結果をに対して呼び出すフック関数</li> <li>parse_float 不動小数点文字列に使用されるパーサ</li> <li>parse_int 整数文字列に使用されるパーサ</li> <li>parse_constant 特定文字('Infinity', 'NaN', 'null', 'true'等)のパーサ</li> <li>object_pairs_hook デコードした結果をに対して呼び出すフック関数</li> </ul> <h3 id="dumps/dumpの引数 辞書dict→文字列またはファイルオブジェクト"><a href="#dumps%2Fdump%E3%81%AE%E5%BC%95%E6%95%B0+%E8%BE%9E%E6%9B%B8dict%E2%86%92%E6%96%87%E5%AD%97%E5%88%97%E3%81%BE%E3%81%9F%E3%81%AF%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88">dumps/dumpの引数 辞書dict→文字列またはファイルオブジェクト</a></h3> <pre><code class="python">json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) </code></pre> <ul> <li>skipkeys Trueにすると基本型以外の辞書のキーの処理を飛ばす</li> <li>ensure_ascii Trueの場合非ASCII文字をエスケープ</li> <li>check_circular Falseの場合循環参照のチェックを行わない</li> <li>allow_nan Trueの場合、nan,inf,-infを変換する</li> <li>cls カスタマイズしたエンコードを使う場合に指定</li> <li>indent 数値や文字列でインデントを指定</li> <li>separators 項目とキーの分割文字のタプル<code>(',', ':')</code></li> <li>default 直列化で使う変換の関数</li> <li>sort_keys Trueの場合辞書順でキーを出力</li> </ul> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/json.html">json --- JSON エンコーダおよびデコーダ</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.10/Lib/json/__init__.py">cpython/<strong>init</strong>.py at 3.10 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17851 2021-12-14T00:38:38+09:00 2021-12-14T00:38:38+09:00 https://crieit.net/posts/python-standard-library-platform Python 標準ライブラリ platform プラットフォーム <p>Python標準のライブラリplatformを使うとOS等のプラットフォームの情報取得を行える。<br /> (以下はWindows環境の場合のサンプルです)</p> <h2 id="platformのサンプル"><a href="#platform%E3%81%AE%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB">platformのサンプル</a></h2> <h3 id="Pythonインタープリタのアーキテクチャ情報"><a href="#Python%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%83%97%E3%83%AA%E3%82%BF%E3%81%AE%E3%82%A2%E3%83%BC%E3%82%AD%E3%83%86%E3%82%AF%E3%83%81%E3%83%A3%E6%83%85%E5%A0%B1">Pythonインタープリタのアーキテクチャ情報</a></h3> <pre><code class="python">import platform platform.architecture() # =&gt; ('64bit', 'WindowsPE') </code></pre> <h3 id="指定した実行ファイルのアーキテクチャ情報"><a href="#%E6%8C%87%E5%AE%9A%E3%81%97%E3%81%9F%E5%AE%9F%E8%A1%8C%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E3%82%A2%E3%83%BC%E3%82%AD%E3%83%86%E3%82%AF%E3%83%81%E3%83%A3%E6%83%85%E5%A0%B1">指定した実行ファイルのアーキテクチャ情報</a></h3> <pre><code class="python">platform.architecture('notepad.exe') # =&gt; ('64bit', '') </code></pre> <h3 id="機種"><a href="#%E6%A9%9F%E7%A8%AE">機種</a></h3> <pre><code class="python">platform.machine() # =&gt; 'AMD64' </code></pre> <h3 id="コンピュータのネットワーク名"><a href="#%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF%E3%81%AE%E3%83%8D%E3%83%83%E3%83%88%E3%83%AF%E3%83%BC%E3%82%AF%E5%90%8D">コンピュータのネットワーク名</a></h3> <pre><code class="python">platform.node() # =&gt; 'MACHINE-NAME' </code></pre> <h3 id="実行中プラットフォームを示す文字列"><a href="#%E5%AE%9F%E8%A1%8C%E4%B8%AD%E3%83%97%E3%83%A9%E3%83%83%E3%83%88%E3%83%95%E3%82%A9%E3%83%BC%E3%83%A0%E3%82%92%E7%A4%BA%E3%81%99%E6%96%87%E5%AD%97%E5%88%97">実行中プラットフォームを示す文字列</a></h3> <pre><code class="python">platform.platform() # =&gt; 'Windows-10-10.0.19041-SP0' </code></pre> <h3 id="プロセッサ名"><a href="#%E3%83%97%E3%83%AD%E3%82%BB%E3%83%83%E3%82%B5%E5%90%8D">プロセッサ名</a></h3> <pre><code class="python">platform.processor() # =&gt; 'Intel64 Family 6 Model 78 Stepping 3, GenuineIntel' </code></pre> <h3 id="Pythonのビルド番号と日付"><a href="#Python%E3%81%AE%E3%83%93%E3%83%AB%E3%83%89%E7%95%AA%E5%8F%B7%E3%81%A8%E6%97%A5%E4%BB%98">Pythonのビルド番号と日付</a></h3> <pre><code class="python">platform.python_build() # =&gt; ('tags/v3.9.2:1a79785', 'Feb 19 2021 13:44:55') </code></pre> <h3 id="Pythonコンパイラ"><a href="#Python%E3%82%B3%E3%83%B3%E3%83%91%E3%82%A4%E3%83%A9">Pythonコンパイラ</a></h3> <pre><code class="python">platform.python_compiler() # =&gt; 'MSC v.1928 64 bit (AMD64)' </code></pre> <h3 id="Pythonのgitブランチ"><a href="#Python%E3%81%AEgit%E3%83%96%E3%83%A9%E3%83%B3%E3%83%81">Pythonのgitブランチ</a></h3> <pre><code class="python">platform.python_branch() # =&gt; 'tags/v3.9.2' </code></pre> <h3 id="Python実装の文字列('CPython', 'IronPython', 'Jython', 'PyPy')"><a href="#Python%E5%AE%9F%E8%A3%85%E3%81%AE%E6%96%87%E5%AD%97%E5%88%97%28%27CPython%27%2C+%27IronPython%27%2C+%27Jython%27%2C+%27PyPy%27%29">Python実装の文字列('CPython', 'IronPython', 'Jython', 'PyPy')</a></h3> <pre><code class="python">platform.python_implementation() # =&gt; 'CPython' </code></pre> <h3 id="Python実装のgitタグ"><a href="#Python%E5%AE%9F%E8%A3%85%E3%81%AEgit%E3%82%BF%E3%82%B0">Python実装のgitタグ</a></h3> <pre><code class="python">platform.python_version() # =&gt; '3.9.2' </code></pre> <h3 id="OS・システム名 ('Linux', 'Darwin', 'Java', 'Windows')"><a href="#OS%E3%83%BB%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0%E5%90%8D+%28%27Linux%27%2C+%27Darwin%27%2C+%27Java%27%2C+%27Windows%27%29">OS・システム名 ('Linux', 'Darwin', 'Java', 'Windows')</a></h3> <pre><code class="python">platform.system() # =&gt; 'Windows' </code></pre> <h3 id="Pythonのバージョン"><a href="#Python%E3%81%AE%E3%83%90%E3%83%BC%E3%82%B8%E3%83%A7%E3%83%B3">Pythonのバージョン</a></h3> <pre><code class="python">platform.version() # =&gt; '10.0.19041' </code></pre> <h3 id="Pythonバージョンのタプル (major, minor, patchlevel)"><a href="#Python%E3%83%90%E3%83%BC%E3%82%B8%E3%83%A7%E3%83%B3%E3%81%AE%E3%82%BF%E3%83%97%E3%83%AB+%28major%2C+minor%2C+patchlevel%29">Pythonバージョンのタプル (major, minor, patchlevel)</a></h3> <pre><code class="python">platform.python_version_tuple() # =&gt; ('3', '9', '2') </code></pre> <h3 id="環境情報(system, node, release, version, machine, processor)"><a href="#%E7%92%B0%E5%A2%83%E6%83%85%E5%A0%B1%28system%2C+node%2C+release%2C+version%2C+machine%2C+processor%29">環境情報(system, node, release, version, machine, processor)</a></h3> <pre><code class="python">platform.uname() # =&gt; uname_result(system='Windows', node='MACHINE-NAME', release='10', version='10.0.19041', machine='AMD64') </code></pre> <h3 id="Jython バージョン情報"><a href="#Jython+%E3%83%90%E3%83%BC%E3%82%B8%E3%83%A7%E3%83%B3%E6%83%85%E5%A0%B1">Jython バージョン情報</a></h3> <pre><code class="python">platform.java_ver() # =&gt; ('', '', ('', '', ''), ('', '', '')) </code></pre> <h3 id="Windowsレジストリの追加バージョン情報 (release, version, csd, ptype)"><a href="#Windows%E3%83%AC%E3%82%B8%E3%82%B9%E3%83%88%E3%83%AA%E3%81%AE%E8%BF%BD%E5%8A%A0%E3%83%90%E3%83%BC%E3%82%B8%E3%83%A7%E3%83%B3%E6%83%85%E5%A0%B1+%28release%2C+version%2C+csd%2C+ptype%29">Windowsレジストリの追加バージョン情報 (release, version, csd, ptype)</a></h3> <pre><code class="python">platform.win32_ver() # =&gt; ('10', '10.0.19041', 'SP0', 'Multiprocessor Free') </code></pre> <h3 id="Windows のエディションの文字列表現"><a href="#Windows+%E3%81%AE%E3%82%A8%E3%83%87%E3%82%A3%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AE%E6%96%87%E5%AD%97%E5%88%97%E8%A1%A8%E7%8F%BE">Windows のエディションの文字列表現</a></h3> <pre><code class="python">platform.win32_edition() # =&gt; 'Professional' </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/platform.html">platform --- 実行中プラットフォームの固有情報を参照する</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/platform.py">cpython/platform.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17850 2021-12-14T00:16:21+09:00 2021-12-14T00:16:21+09:00 https://crieit.net/posts/python-standard-library-logging Python 標準ライブラリ logging ロギング <p>Pythonでのログ出力は標準で用意されているライブラリloggingを使うことで行なえます。</p> <h2 id="ログ出力サンプル"><a href="#%E3%83%AD%E3%82%B0%E5%87%BA%E5%8A%9B%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB">ログ出力サンプル</a></h2> <h3 id="ファイルへのログ出力"><a href="#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%B8%E3%81%AE%E3%83%AD%E3%82%B0%E5%87%BA%E5%8A%9B">ファイルへのログ出力</a></h3> <p>日付名称のファイルへのログ出力</p> <pre><code class="python">import logging import time logging.basicConfig(filename=time.strftime('%Y%m%d.log'), encoding='utf-8', format='[%(asctime)s][%(levelname)s]%(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.DEBUG) logging.debug('デバッグログ') logging.info('情報ログ') logging.warning('警告ログ') logging.error('エラーログ') </code></pre> <pre><code class="text">[2021/08/20 23:36:27][DEBUG]デバッグログ [2021/08/20 23:36:27][INFO]情報ログ [2021/08/20 23:36:27][WARNING]警告ログ [2021/08/20 23:36:27][ERROR]エラーログ </code></pre> <h3 id="複数対象へのログ出力"><a href="#%E8%A4%87%E6%95%B0%E5%AF%BE%E8%B1%A1%E3%81%B8%E3%81%AE%E3%83%AD%E3%82%B0%E5%87%BA%E5%8A%9B">複数対象へのログ出力</a></h3> <p>警告以上のログをファイルに、全てのログをコンソールに出力。</p> <pre><code class="python">import logging import time logger = logging.getLogger('LoggerName') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(time.strftime('%Y%m%d.log'),encoding='utf-8') fh.setLevel(logging.WARN) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s][%(levelname)s]%(message)s', datefmt='%Y/%m/%d %H:%M:%S') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) logger.debug('デバッグログ') logger.info('情報ログ') logger.warning('警告ログ') logger.error('エラーログ') </code></pre> <pre><code class="text">20210820.log [2021/08/20 23:36:27][WARNING]警告ログ [2021/08/20 23:36:27][ERROR]エラーログ </code></pre> <pre><code class="text">コンソール [2021/08/20 23:36:27][DEBUG]デバッグログ [2021/08/20 23:36:27][INFO]情報ログ [2021/08/20 23:36:27][WARNING]警告ログ [2021/08/20 23:36:27][ERROR]エラーログ </code></pre> <h2 id="書式と追加キーワードでの出力例"><a href="#%E6%9B%B8%E5%BC%8F%E3%81%A8%E8%BF%BD%E5%8A%A0%E3%82%AD%E3%83%BC%E3%83%AF%E3%83%BC%E3%83%89%E3%81%A7%E3%81%AE%E5%87%BA%E5%8A%9B%E4%BE%8B">書式と追加キーワードでの出力例</a></h2> <p>第2引数以降で指定した変数をログ出力できる。<br /> <code>extra</code>で指定した辞書の値はフォーマットで参照できる。</p> <pre><code class="python">logger = logging.getLogger('LoggerSample') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s][%(levelname)s][%(string)s][%(number)s]%(message)s', datefmt='%Y/%m/%d %H:%M:%S') ch.setFormatter(formatter) logger.addHandler(ch) d = {'string':'AAA', 'number':777 } logger.debug('ログテスト %s %s','Test',123,extra=d) </code></pre> <pre><code class="text">[2021/08/20 23:42:16][DEBUG][AAA][777]ログテスト Test 123 </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/logging.html">logging --- Python 用ロギング機能</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/logging/__init__.py">cpython/<strong>init</strong>.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17607 2021-08-19T01:47:37+09:00 2021-08-19T01:47:37+09:00 https://crieit.net/posts/python-standard-library-time Python 標準ライブラリ time 時刻 <p>時刻(日時)の取得や変換はtimeモジュールに用意されている関数を使って行うことができます。</p> <h2 id="概要"><a href="#%E6%A6%82%E8%A6%81">概要</a></h2> <p>時刻(日時)は以下の形式で表現されます。</p> <ul> <li>文字列('Wed Aug 18 23:54:50 2021'や'2021-08-19 23:54:50'等)</li> <li>エポック(epoch 1970/01/01 00:00:00)からの経過秒数</li> <li>struct_time型(年、月、秒等の値を持った型)</li> </ul> <h2 id="文字列形式で時刻(日時)を取得"><a href="#%E6%96%87%E5%AD%97%E5%88%97%E5%BD%A2%E5%BC%8F%E3%81%A7%E6%99%82%E5%88%BB%28%E6%97%A5%E6%99%82%29%E3%82%92%E5%8F%96%E5%BE%97">文字列形式で時刻(日時)を取得</a></h2> <h3 id="エポック秒 → 文字列"><a href="#%E3%82%A8%E3%83%9D%E3%83%83%E3%82%AF%E7%A7%92+%E2%86%92+%E6%96%87%E5%AD%97%E5%88%97">エポック秒 → 文字列</a></h3> <pre><code class="python"># 現在日時を取得 time.ctime() # => 'Wed Aug 18 23:52:55 2021' # 指定したエポックからの秒数の日時を取得 time.ctime(time.time()) # => 'Wed Aug 18 23:54:50 2021' time.ctime(1628778159) # => 'Thu Aug 12 23:22:39 2021' # 上記は以下と同様 # time.asctime(time.localtime(1628778159)) # =&gt; 'Thu Aug 12 23:22:39 2021' </code></pre> <h3 id="struct_time → 文字列"><a href="#struct_time+%E2%86%92+%E6%96%87%E5%AD%97%E5%88%97">struct_time → 文字列</a></h3> <pre><code class="python"># 現在日時を取得 time.asctime() # => 'Wed Aug 18 23:51:44 2021' # 指定したstruct_timeの日時を取得 time.asctime(time.localtime()) # => 'Wed Aug 18 23:54:15 2021' </code></pre> <p><code>strftime(format[, t])</code>を使うと、指定した形式で文字列の取得ができる。<br /> 第2引数はstruct_timeで省略した場合は現在時刻の<code>localtime()</code>が指定される。</p> <pre><code class="python"># 年月日時分秒とタイムゾーン time.strftime('%Y/%m/%d %H:%M:%S%z') # => '2021/08/19 00:47:44+0900' # 午前午後の文字列と12時間表記時刻 time.strftime('%p %I時') # => 'AM 12時' # 曜日 time.strftime('%a') # => 'Thu' time.strftime('%A') # => 'Thursday' time.strftime('%w') # => '4' (0:日曜日,…6:土曜日) # 月 time.strftime('%b') # => 'Aug' time.strftime('%B') # => 'August' # ロケールでの表示 time.strftime('%c') # => 'Thu Aug 19 00:39:38 2021' # 年月日 time.strftime('%x') # => '08/19/21' # 時分秒 time.strftime('%X') # => '00:46:11' # 2桁年数 time.strftime('%y') # => '21' # 週数と日数 time.strftime('第%U週(日曜起算) 第%W週(月曜起算) 第%j日目') # => '第33週(日曜起算) 第33週(月曜起算) 第231日目' # タイムゾーン名称 time.strftime('%Z') # => '東京 (標準時)' </code></pre> <h2 id="エポック秒数で時刻を取得"><a href="#%E3%82%A8%E3%83%9D%E3%83%83%E3%82%AF%E7%A7%92%E6%95%B0%E3%81%A7%E6%99%82%E5%88%BB%E3%82%92%E5%8F%96%E5%BE%97">エポック秒数で時刻を取得</a></h2> <h3 id="エポックからの現在秒数"><a href="#%E3%82%A8%E3%83%9D%E3%83%83%E3%82%AF%E3%81%8B%E3%82%89%E3%81%AE%E7%8F%BE%E5%9C%A8%E7%A7%92%E6%95%B0">エポックからの現在秒数</a></h3> <pre><code class="python"># 秒 time.time() # => 1629302004.3049362 # ナノ秒 time.time_ns() # => 1629302009858687200 </code></pre> <h3 id="struct_time → エポック秒"><a href="#struct_time+%E2%86%92+%E3%82%A8%E3%83%9D%E3%83%83%E3%82%AF%E7%A7%92">struct_time → エポック秒</a></h3> <pre><code class="python"># struct_time(ローカル時間)から取得 time.mktime(time.localtime()) # => 1629299532.0 time.mktime(time.localtime(1629299532.0)) # => 1629299532.0 </code></pre> <h2 id="struct_timeで時刻(日時)を取得"><a href="#struct_time%E3%81%A7%E6%99%82%E5%88%BB%28%E6%97%A5%E6%99%82%29%E3%82%92%E5%8F%96%E5%BE%97">struct_timeで時刻(日時)を取得</a></h2> <h3 id="文字列 → struct_time"><a href="#%E6%96%87%E5%AD%97%E5%88%97+%E2%86%92+struct_time">文字列 → struct_time</a></h3> <p><code>strptime(string[, format])</code>を使うと時刻を示す文字列からstruct_timeを取得できる。</p> <pre><code class="python"># 書式指定なし('%a %b %d %H:%M:%S %Y'のフォーマットで変換) time.strptime('Thu Aug 19 00:56:58 2021') # =&gt; time.struct_time(tm_year=2021, tm_mon=8, tm_mday=19, tm_hour=0, tm_min=56, tm_sec=58, tm_wday=3, tm_yday=231, tm_isdst=-1) # 年月日指定 time.strptime('2021/08/19','%Y/%m/%d') # =&gt; time.struct_time(tm_year=2021, tm_mon=8, tm_mday=19, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=231, tm_isdst=-1) # 年月日時分秒指定 time.strptime('2021/08/19 00:59:10','%Y/%m/%d %H:%M:%S') # =&gt; time.struct_time(tm_year=2021, tm_mon=8, tm_mday=19, tm_hour=0, tm_min=59, tm_sec=10, tm_wday=3, tm_yday=231, tm_isdst=-1) </code></pre> <h3 id="エポック秒 → struct_time(UTC)"><a href="#%E3%82%A8%E3%83%9D%E3%83%83%E3%82%AF%E7%A7%92+%E2%86%92+struct_time%28UTC%29">エポック秒 → struct_time(UTC)</a></h3> <pre><code class="python"># 現在日時(UTC)を取得 time.gmtime() # => time.struct_time(tm_year=2021, tm_mon=8, tm_mday=18, tm_hour=15, tm_min=5, tm_sec=4, tm_wday=2, tm_yday=230, tm_isdst=0) # 指定したエポックからの秒数の日時(UTC)を取得 time.gmtime(time.time()) # => time.struct_time(tm_year=2021, tm_mon=8, tm_mday=18, tm_hour=15, tm_min=8, tm_sec=43, tm_wday=2, tm_yday=230, tm_isdst=0) time.gmtime(1628778159) # => time.struct_time(tm_year=2021, tm_mon=8, tm_mday=12, tm_hour=14, tm_min=22, tm_sec=39, tm_wday=3, tm_yday=224, tm_isdst=0) </code></pre> <h3 id="エポック秒 → struct_time(ローカル時)"><a href="#%E3%82%A8%E3%83%9D%E3%83%83%E3%82%AF%E7%A7%92+%E2%86%92+struct_time%28%E3%83%AD%E3%83%BC%E3%82%AB%E3%83%AB%E6%99%82%29">エポック秒 → struct_time(ローカル時)</a></h3> <pre><code class="python"># 現在日時(ローカル時)を取得 time.localtime() # => time.struct_time(tm_year=2021, tm_mon=8, tm_mday=19, tm_hour=0, tm_min=5, tm_sec=6, tm_wday=3, tm_yday=231, tm_isdst=0) # 指定したエポックからの秒数の日時(ローカル時)を取得 time.localtime(time.time()) # => time.struct_time(tm_year=2021, tm_mon=8, tm_mday=19, tm_hour=0, tm_min=9, tm_sec=31, tm_wday=3, tm_yday=231, tm_isdst=0) time.localtime(1628778159) # => time.struct_time(tm_year=2021, tm_mon=8, tm_mday=12, tm_hour=23, tm_min=22, tm_sec=39, tm_wday=3, tm_yday=224, tm_isdst=0) </code></pre> <h2 id="スリープ・休止"><a href="#%E3%82%B9%E3%83%AA%E3%83%BC%E3%83%97%E3%83%BB%E4%BC%91%E6%AD%A2">スリープ・休止</a></h2> <p>指定した秒数だけスレッドの実行を停止。</p> <pre><code class="python">time.sleep(0.5) time.sleep(1) </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/time.html#time.struct_time">time --- 時刻データへのアクセスと変換</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17606 2021-08-19T01:47:02+09:00 2021-08-19T01:47:02+09:00 https://crieit.net/posts/python-standard-library-io Python 標準ライブラリ io I/Oストリーム <p>ioモジュールでファイルの書き込み・読み込みを行うストリームの機能が提供されています。</p> <h2 id="ファイルの読み書きの例"><a href="#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E8%AA%AD%E3%81%BF%E6%9B%B8%E3%81%8D%E3%81%AE%E4%BE%8B">ファイルの読み書きの例</a></h2> <p>組込関数<a target="_blank" rel="nofollow noopener" href="https://marusankakusikaku.jp/python/grammer/built-in-functions/#openfile-moder-buffering-1-encodingnone-errorsnone-newlinenone-closefdtrue-openernone-ファイルオープン">open</a>でストリームのインスタンスを作成し、ファイルの読み込み・書き込みを行うことができます。</p> <h3 id="組み込み関数open"><a href="#%E7%B5%84%E3%81%BF%E8%BE%BC%E3%81%BF%E9%96%A2%E6%95%B0open">組み込み関数open</a></h3> <pre><code class="python">with open('./sample.txt', 'w', encoding='utf-8') as f: f.write('テスト1\n') f.write('テスト2') with open('./sampl_b.txt', 'wb') as f: f.write(b'abc') with open('./sample.txt', 'r', encoding='utf-8') as f: print(f.read()) </code></pre> <p>openの第1引数はファイルのパス、第2引数は読み込み・書き込みのモードです。</p> <pre><code class="text">* r 読み込み用 * w 書き込み用(最初にファイルをクリア) * x 排他的な作成用(ファイルが存在するとエラー) * a 追記用 * b バイナリーモード * t テキストモード * '+' 読み書き用 </code></pre> <p>rとtはデフォルトで指定されます。</p> <h3 id="ioモジュールのエイリアス"><a href="#io%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AE%E3%82%A8%E3%82%A4%E3%83%AA%E3%82%A2%E3%82%B9">ioモジュールのエイリアス</a></h3> <p>ioモジュール以下に<code>open</code>のエイリアスの関数も定義されています。</p> <pre><code class="python">io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) </code></pre> <h2 id="テキストI/O"><a href="#%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88I%2FO">テキストI/O</a></h2> <h3 id="文字列によるテキストの書き込み"><a href="#%E6%96%87%E5%AD%97%E5%88%97%E3%81%AB%E3%82%88%E3%82%8B%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%81%AE%E6%9B%B8%E3%81%8D%E8%BE%BC%E3%81%BF">文字列によるテキストの書き込み</a></h3> <pre><code class="python">with open('./sample.txt', 'w', encoding='utf-8') as f: print(f.writable()) # => True 書き込み可能 print(f.tell()) # => 0 ストリーム位置 print(f.closed) # => False ストリームクローズしていない f.write('テスト1\n') f.writelines(['テスト2\n','テスト3']) print(f.tell()) # => 34 ストリーム位置 f.close() print(f.closed) # => True ストリームクローズ </code></pre> <h3 id="文字列によるテキストの読み込み"><a href="#%E6%96%87%E5%AD%97%E5%88%97%E3%81%AB%E3%82%88%E3%82%8B%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%81%AE%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF">文字列によるテキストの読み込み</a></h3> <pre><code class="python">with open('./sample.txt', 'r', encoding='utf-8') as f: print(f.readable()) # => True 読み込み可能 print(f.tell()) # => 0 ストリーム位置 print(f.closed) # => False ストリームクローズしていない print(f.readline()) # => テスト1 1行読み込み print(f.readlines()) # => ['テスト2\n', 'テスト3'] 行の配列で読み込み f.close() print(f.closed) # => True ストリームクローズ </code></pre> <h3 id="バッファ付きのストリームによるテキストの書き込みと読み込み"><a href="#%E3%83%90%E3%83%83%E3%83%95%E3%82%A1%E4%BB%98%E3%81%8D%E3%81%AE%E3%82%B9%E3%83%88%E3%83%AA%E3%83%BC%E3%83%A0%E3%81%AB%E3%82%88%E3%82%8B%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%81%AE%E6%9B%B8%E3%81%8D%E8%BE%BC%E3%81%BF%E3%81%A8%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF">バッファ付きのストリームによるテキストの書き込みと読み込み</a></h3> <pre><code class="python">with io.FileIO('./sampl_b2.txt', 'w') as f, io.TextIOWrapper(f,encoding='utf-8') as tw: tw.write('あいうえお') with io.FileIO('./sampl_b2.txt', 'r') as f, io.TextIOWrapper(f,encoding='utf-8') as tw: print(tw.read()) # => うえ </code></pre> <h3 id="インメモリーのテキストストリーム"><a href="#%E3%82%A4%E3%83%B3%E3%83%A1%E3%83%A2%E3%83%AA%E3%83%BC%E3%81%AE%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%82%B9%E3%83%88%E3%83%AA%E3%83%BC%E3%83%A0">インメモリーのテキストストリーム</a></h3> <pre><code class="python">with io.StringIO() as f: f.write('テスト\n') print(123, file=f) print(f.getvalue()) # テスト # 123 </code></pre> <h2 id="バイナリ I/O"><a href="#%E3%83%90%E3%82%A4%E3%83%8A%E3%83%AA+I%2FO">バイナリ I/O</a></h2> <h3 id="バイト列によるバイナリの書き込み"><a href="#%E3%83%90%E3%82%A4%E3%83%88%E5%88%97%E3%81%AB%E3%82%88%E3%82%8B%E3%83%90%E3%82%A4%E3%83%8A%E3%83%AA%E3%81%AE%E6%9B%B8%E3%81%8D%E8%BE%BC%E3%81%BF">バイト列によるバイナリの書き込み</a></h3> <pre><code class="python">with open('./sampl_b.txt', 'wb') as f: f.write(b'xyz') </code></pre> <h3 id="バイト列によるバイナリの読み込み"><a href="#%E3%83%90%E3%82%A4%E3%83%88%E5%88%97%E3%81%AB%E3%82%88%E3%82%8B%E3%83%90%E3%82%A4%E3%83%8A%E3%83%AA%E3%81%AE%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF">バイト列によるバイナリの読み込み</a></h3> <pre><code class="python">with open('./sampl_b.txt', 'rb') as f: f.read() </code></pre> <h3 id="io.FileIOによるバイナリの書き込みと読み込み"><a href="#io.FileIO%E3%81%AB%E3%82%88%E3%82%8B%E3%83%90%E3%82%A4%E3%83%8A%E3%83%AA%E3%81%AE%E6%9B%B8%E3%81%8D%E8%BE%BC%E3%81%BF%E3%81%A8%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF">io.FileIOによるバイナリの書き込みと読み込み</a></h3> <pre><code class="python">with io.FileIO('./sampl_b.txt', 'w') as f: f.write(b'xyz') with io.FileIO('./sampl_b.txt', 'r') as f: print(f.read()) # => b'xyz' </code></pre> <h3 id="バッファ付きのストリームによるバイナリの書き込みと読み込み"><a href="#%E3%83%90%E3%83%83%E3%83%95%E3%82%A1%E4%BB%98%E3%81%8D%E3%81%AE%E3%82%B9%E3%83%88%E3%83%AA%E3%83%BC%E3%83%A0%E3%81%AB%E3%82%88%E3%82%8B%E3%83%90%E3%82%A4%E3%83%8A%E3%83%AA%E3%81%AE%E6%9B%B8%E3%81%8D%E8%BE%BC%E3%81%BF%E3%81%A8%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%81%BF">バッファ付きのストリームによるバイナリの書き込みと読み込み</a></h3> <pre><code class="python">with io.FileIO('./sampl_b.txt', 'wb') as f,io.BufferedWriter(f) as bw: bw.write(b'112233') with io.FileIO('./sampl_b.txt', 'rb') as f,io.BufferedReader(f) as br: print(br.read()) # => b'112233' </code></pre> <h3 id="インメモリのストリーム"><a href="#%E3%82%A4%E3%83%B3%E3%83%A1%E3%83%A2%E3%83%AA%E3%81%AE%E3%82%B9%E3%83%88%E3%83%AA%E3%83%BC%E3%83%A0">インメモリのストリーム</a></h3> <pre><code class="python">with io.BytesIO(b"abc") as f: print(f.read()) #=> b'abc' </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/io.html">io --- ストリームを扱うコアツール</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/io.py">cpython/io.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17605 2021-08-19T01:45:20+09:00 2021-08-19T01:45:20+09:00 https://crieit.net/posts/python-standard-library-os Python 標準ライブラリ os OS依存の機能 <p>ライブラリosを使うと環境に依存した情報の取得やファイルを操作を行うことができます。</p> <h2 id="OSの環境変数"><a href="#OS%E3%81%AE%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0">OSの環境変数</a></h2> <pre><code class="python">os.environ # =&gt; # environ{'ALLUSERSPROFILE': 'C:\\ProgramData', # 'APPDATA': 'C:\\Users\\name\\AppData\\Roaming', # … # } os.environ['OS'] # =&gt; 'Windows_NT' </code></pre> <p>特定の環境変数は<code>getenv</code>で取得できる。<br /> 第2引数は変数が設定されていない場合のデフォルト値。</p> <pre><code class="python">os.getenv('OSXXX', 'Linux') # => Linux os.getenv('OS', 'Linux') # => Windows_NT </code></pre> <h2 id="ディレクトリの移動"><a href="#%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA%E3%81%AE%E7%A7%BB%E5%8B%95">ディレクトリの移動</a></h2> <pre><code class="python">os.getcwd() # => 'c:\\home' os.chdir('./test') os.getcwd() # => 'c:\\home\\test' </code></pre> <h2 id="実行パス"><a href="#%E5%AE%9F%E8%A1%8C%E3%83%91%E3%82%B9">実行パス</a></h2> <pre><code class="python">os.get_exec_path() </code></pre> <h2 id="ログインユーザー"><a href="#%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%BC">ログインユーザー</a></h2> <pre><code class="python">os.getlogin() </code></pre> <h2 id="ディレクトリの探索"><a href="#%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA%E3%81%AE%E6%8E%A2%E7%B4%A2">ディレクトリの探索</a></h2> <p><code>scandir(path='.')</code>で指定したディレクトリ以下の探索を行える。</p> <pre><code class="python">for o in os.scandir(): print(o.name) # ファイル名 print(o.path) # パス print(o.inode()) # inode番号 print(o.is_dir()) # ディレクトリか print(o.is_file()) # ファイルか print(o.is_symlink()) # シンボリックリンクか print(o.stat()) # ファイル情報 </code></pre> <h2 id="ディレクトリ、ファイルの操作・コピー"><a href="#%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA%E3%80%81%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E6%93%8D%E4%BD%9C%E3%83%BB%E3%82%B3%E3%83%94%E3%83%BC">ディレクトリ、ファイルの操作・コピー</a></h2> <pre><code class="python"># ディレクトリの作成 os.mkdir('./testdir/') os.makedirs('./sub/test/dir/') # 名称変更 os.rename('./testdir/','./testdir2/') os.renames('./testdir2/', './testdir4/test/dir') # ディレクト削除 os.rmdir('./testdir4/test/dir') os.removedirs('./sub/test/dir/') # ファイル削除 os.remove('./test.txt') </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/os.html">os --- 雑多なオペレーティングシステムインタフェース</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/os.py">cpython/os.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17593 2021-08-12T00:48:21+09:00 2021-08-12T00:48:21+09:00 https://crieit.net/posts/python-standard-library-secrets Python 標準ライブラリ secrets セキュリティ用途の乱数 <p>ライブラリsecretsを使うと、セキュリティトークンや認証で使うための強度のある乱数を生成できます。</p> <h2 id="ランダムな要素の選択"><a href="#%E3%83%A9%E3%83%B3%E3%83%80%E3%83%A0%E3%81%AA%E8%A6%81%E7%B4%A0%E3%81%AE%E9%81%B8%E6%8A%9E">ランダムな要素の選択</a></h2> <pre><code class="python">import secrets secrets.choice([1,2,3]) # => 1 </code></pre> <h2 id="ランダムな整数値"><a href="#%E3%83%A9%E3%83%B3%E3%83%80%E3%83%A0%E3%81%AA%E6%95%B4%E6%95%B0%E5%80%A4">ランダムな整数値</a></h2> <pre><code class="python">secrets.randbelow(3) # => 3未満のランダムな整数 secrets.randbits(8) # => ランダムな8ビット整数 </code></pre> <h2 id="トークン"><a href="#%E3%83%88%E3%83%BC%E3%82%AF%E3%83%B3">トークン</a></h2> <pre><code class="python"># バイト文字列 secrets.token_bytes(8) # => b'\xe9\xc8w\x8cDZ\xf2:' # 16進数文字列 secrets.token_hex(8) # => 5b0aa697f5c9bd2d # URLで使えるBASE64エンコード済みの文字列 secrets.token_urlsafe(8) # => '-hCSkNaBmfA' </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/secrets.html">secrets --- 機密を扱うために安全な乱数を生成する</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/secrets.py">cpython/secrets.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17592 2021-08-12T00:47:48+09:00 2021-08-12T00:47:48+09:00 https://crieit.net/posts/python-standard-library-hmac Python 標準ライブラリ hmac HMACアルゴリズムのハッシュ <p>HMACアルゴリズムのハッシュはライブリhmacで計算できます。</p> <h2 id="ダイジェスト値の計算は`sha256"><a href="#%E3%83%80%E3%82%A4%E3%82%B8%E3%82%A7%E3%82%B9%E3%83%88%E5%80%A4%E3%81%AE%E8%A8%88%E7%AE%97%E3%81%AF%60sha256">ダイジェスト値の計算は`sha256</a></h2> <p>hmac.digest(key, msg, digest)</p> <pre><code class="python">import hmac hmac.digest(b'key', b'test', 'MD5') # =&gt; b&quot;\x1dJ'C\xc0V\xe4g\xff?\t\xc9\xaf1\xde~&quot; </code></pre> <p><code>new(key, msg=None, digestmod='')</code>でhmacのインスタンを取得し、<br /> <code>update</code>でメッセージを指定してから、<code>digest()</code>で計算しても同じ結果を取得できる。</p> <pre><code class="python">md5 = hmac.new(b'key', digestmod='MD5') md5.update(b'test') md5.digest() # =&gt; b&quot;\x1dJ'C\xc0V\xe4g\xff?\t\xc9\xaf1\xde~&quot; </code></pre> <p>メッセージの指定は<code>update</code>で分けて行うこともできる。</p> <pre><code class="python">md5 = hmac.new(b'key', digestmod='MD5') md5.update(b'te') md5.update(b'st') md5.digest() # =&gt; b&quot;\x1dJ'C\xc0V\xe4g\xff?\t\xc9\xaf1\xde~&quot; </code></pre> <h2 id="ハッシュの情報"><a href="#%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%81%AE%E6%83%85%E5%A0%B1">ハッシュの情報</a></h2> <pre><code class="python">md5 = hmac.new(b'key', digestmod='MD5') md5.update(b'test') md5.hexdigest() # => ダイジェスト値16進数文字列 1d4a2743c056e467ff3f09c9af31de7e md5.digest_size # => HMAC ダイジェストのバイト数 16 md5.block_size # => ハッシュアルゴリズムのブロックのバイト数 64 md5.name # => アルゴリズムの名称 'hmac-md5' </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/hmac.html">hmac --- メッセージ認証のための鍵付きハッシュ化</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/hmac.py">cpython/hmac.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17591 2021-08-12T00:47:14+09:00 2021-08-12T00:47:14+09:00 https://crieit.net/posts/python-standard-library-hashlib Python 標準ライブラリ hashlib ハッシュアルゴリズム <p>ライブラリhashlibを使うと種々のアルゴリズムでハッシュの計算を行えます。</p> <h2 id="ダイジェスト値計算"><a href="#%E3%83%80%E3%82%A4%E3%82%B8%E3%82%A7%E3%82%B9%E3%83%88%E5%80%A4%E8%A8%88%E7%AE%97">ダイジェスト値計算</a></h2> <p>ダイジェスト値の計算は<code>sha256()</code>や<code>md5()</code>等のアルゴリズムを示すコンストラクタにデータを指定し、<br /> <code>digest()</code>、<code>hexdigest()</code>を呼び出す事で行える。</p> <p><code>digest()</code>はバイト列、<code>hexdigest()</code>は16進数文字列を返却する。</p> <pre><code class="python">import hashlib hashlib.sha256(b'test').digest() # =&gt; b'\x9f\x86\xd0\x81\x88L}e\x9a/\xea\xa0\xc5Z\xd0\x15\xa3\xbfO\x1b+\x0b\x82,\xd1]l\x15\xb0\xf0\n\x08' hashlib.sha256(b'test').hexdigest() # =&gt; '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' </code></pre> <p>アルゴリズムの指定は<code>hashlib.new(name, [data, ]*, usedforsecurity=True)</code><br /> でnameにアルゴリズムの名称を渡すことでも行える。</p> <pre><code class="python">hashlib.new('sha256',b'test').digest() # =&gt; b'\x9f\x86\xd0\x81\x88L}e\x9a/\xea\xa0\xc5Z\xd0\x15\xa3\xbfO\x1b+\x0b\x82,\xd1]l\x15\xb0\xf0\n\x08' hashlib.new('sha256',b'test').hexdigest() # =&gt; '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' </code></pre> <p>データは<code>update(data)</code>で設定できる。</p> <pre><code class="python">sha = hashlib.sha256() sha.update(b'test') sha.digest() # => b'\x9f\x86\xd0\x81\x88L}e\x9a/\xea\xa0\xc5Z\xd0\x15\xa3\xbfO\x1b+\x0b\x82,\xd1]l\x15\xb0\xf0\n\x08' sha.hexdigest() #=> '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' </code></pre> <p>updateはバイト列を分けて指定することもできる。</p> <pre><code class="python">sha = hashlib.new('sha256') sha.update(b'te') sha.update(b'st') sha.digest() # => b'\x9f\x86\xd0\x81\x88L}e\x9a/\xea\xa0\xc5Z\xd0\x15\xa3\xbfO\x1b+\x0b\x82,\xd1]l\x15\xb0\xf0\n\x08' sha.hexdigest() #=> '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' </code></pre> <h2 id="ハッシュのアルゴリズム"><a href="#%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%81%AE%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0">ハッシュのアルゴリズム</a></h2> <h3 id="hashlib.algorithms_guaranteed"><a href="#hashlib.algorithms_guaranteed">hashlib.algorithms_guaranteed</a></h3> <p>すべてのプラットフォームでサポートされるハッシュのアルゴリズム名のリスト。</p> <pre><code class="python">hashlib.algorithms_guaranteed </code></pre> <pre><code class="text">{'blake2b', 'blake2s', 'md4', 'md5', 'md5-sha1', … 'whirlpool'} </code></pre> <h3 id="hashlib.algorithms_available"><a href="#hashlib.algorithms_available">hashlib.algorithms_available</a></h3> <p>実行中の環境で利用可能なハッシュのアルゴリズム名のリスト。</p> <pre><code class="python">hashlib.algorithms_available </code></pre> <pre><code class="text">{'blake2b', 'blake2s', 'md5', … 'shake_256'} </code></pre> <h2 id="ハッシュオブジェクトのプロパティ、関数"><a href="#%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%AE%E3%83%97%E3%83%AD%E3%83%91%E3%83%86%E3%82%A3%E3%80%81%E9%96%A2%E6%95%B0">ハッシュオブジェクトのプロパティ、関数</a></h2> <pre><code class="python">algorithms = [hashlib.new(x) for x in hashlib.algorithms_available] for algorithm in algorithms: algorithm.update(b'test') print(algorithm.name) # ハッシュの正規名 print(algorithm.digest_size) # 生成されたハッシュのバイト数 print(algorithm.block_size) # ハッシュアルゴリズムのブロックのバイト数 if algorithm.name.startswith('shake'): print(algorithm.digest(10)) # ダイジェスト値 print(algorithm.hexdigest(10)) # 16進数文字列 else: print(algorithm.digest()) # ダイジェスト値 print(algorithm.hexdigest()) # 16進数文字列 </code></pre> <p><code>shake_128()</code>、<code>shake_256()</code>のダイジェスト値は長さの指定をして取得する。</p> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/hashlib.html#hashlib.blake2b">hashlib --- セキュアハッシュおよびメッセージダイジェスト</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/hashlib.py">cpython/hashlib.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku tag:crieit.net,2005:PublicArticle/17590 2021-08-12T00:46:45+09:00 2021-08-12T00:46:45+09:00 https://crieit.net/posts/python-standard-library-glob Python 標準ライブラリ glob パスのパターンマッチ <p>ライブラリglobを使うとパスのパターンマッチを行うことができる。</p> <h2 id="ファイルの準備"><a href="#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E6%BA%96%E5%82%99">ファイルの準備</a></h2> <pre><code class="python">import pathlib pathlib.Path("./test/sample1.txt").touch() pathlib.Path("./test/sample2.txt").touch() pathlib.Path("./test/sampleA.txt").touch() </code></pre> <h2 id="パターンにマッチするパスの取得"><a href="#%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%E3%81%AB%E3%83%9E%E3%83%83%E3%83%81%E3%81%99%E3%82%8B%E3%83%91%E3%82%B9%E3%81%AE%E5%8F%96%E5%BE%97">パターンにマッチするパスの取得</a></h2> <p>glob.glob(pathname, *, recursive=False)</p> <pre><code class="python">import glob list(glob.glob('./test/sample[0-9].txt')) # =&gt; ['./test\\sample1.txt', './test\\sample2.txt'] </code></pre> <h2 id="イテレータでのマッチしたパスの取得"><a href="#%E3%82%A4%E3%83%86%E3%83%AC%E3%83%BC%E3%82%BF%E3%81%A7%E3%81%AE%E3%83%9E%E3%83%83%E3%83%81%E3%81%97%E3%81%9F%E3%83%91%E3%82%B9%E3%81%AE%E5%8F%96%E5%BE%97">イテレータでのマッチしたパスの取得</a></h2> <pre><code class="python">for name in glob.iglob('./test/*.*'): print(name) # ./test\sample1.txt # ./test\sample2.txt # ./test\sampleA.txt </code></pre> <h2 id="参考"><a href="#%E5%8F%82%E8%80%83">参考</a></h2> <ul> <li><a target="_blank" rel="nofollow noopener" href="https://docs.python.org/ja/3/library/glob.html">glob --- Unix 形式のパス名のパターン展開</a></li> <li><a target="_blank" rel="nofollow noopener" href="https://github.com/python/cpython/blob/3.9/Lib/glob.py">cpython/glob.py at 3.9 · python/cpython</a></li> </ul> maru3kaku4kaku