Python

Python | with 文が使える関数を作る

with 文が使える関数をつくる yield 式のところで with ブロックの内容が実行される #with_openthebook.py from contextlib import contextmanager class Book(): def __init__(self): self.contents = '' self.isopen = False def open(self): self.isopen …

Jupyter | configure jupyter qtconsole

jupyter qtconsole をフォント指定して起動 jupyter qtconsole --ConsoleWidget.font_family="MyricaM M" --ConsoleWidget.font_size=12

Python | pdb 対話的デバッガ

対話的デバッガ デバッグしたい部分に次の一文を挿入 import pdb; pdb.set_trace() (Pdb) プロンプトのコマンド(の例) プログラムを調べるコマンド w(here) スタックトレースを表示、矢印は現在のフレームを表す u(p) スコープを関数の呼び出し元に移す (o…

Python | python コードのテスト

unittest を使う # utils.py def to_hex(integer, length, byteorder, *, signed=False): b = integer.to_bytes(length, byteorder, signed=signed) lst = ['{:02X}'.format(x) for x in b] return ''.join(lst) # test_to_hex.py from unittest import Test…

Python | 2の補数 (signed) int ⇔ bytes ⇔ str (16進文字列)

(signed) int → bytes int.to_bytes を使う >>> (-100).to_bytes(1, byteorder='little', signed=True) b'\x9c' >>> (-1000).to_bytes(2, 'little', signed=True) b'\x18\xfc' >>> (-1000).to_bytes(2, 'big', signed=True) b'\xfc\x18' struct.pack を使う …

Python | 2の補数のビットパターンを文字列で得る方法

str.format を使う >>> '{:08b}'.format(-100 & 0xff) '10011100' >>> '{:02X}'.format(-100 & 0xFF) '9C' >>> '{:02X}'.format(-1000 & 0xFFFF) 'FC18' int.to_bytes を使う >>> b = (-100).to_bytes(1, byteorder='little', signed=True) >>> b b'\x9c' >>…