Last active
October 7, 2025 02:18
-
-
Save gocha/fb78aa002dd4f596ce68b07c3ef4685a to your computer and use it in GitHub Desktop.
PostgreSQL (Windows) のインストールログの文字化けを直す
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Windows: PostgreSQL のインストールログの文字化けを直す | |
| # | |
| # %TEMP%\install-postgresql.log に出現する、 | |
| # initdb など、外部コマンドのメッセージの文字化けを修正します。 | |
| # 引数なしで起動すると、コマンドの書式が表示されます。 | |
| # | |
| # ---- | |
| # 【文字化けの解説】 | |
| # 文字化けは「文字列が強制的に cp1252 として読み取られる」ことで発生しています。 | |
| # | |
| # (本来) cp932※ → (強制的な解釈) cp1252 → (ログファイル) utf-8 | |
| # ※Windows のコードページが一般的な日本語設定の場合 | |
| # ※cp1252 は latin-1 と互換性がありますが、拡張領域が存在します | |
| # | |
| # 文字化けテキストを cp1252 に変換して保存すれば、元のバイナリが得られます。 | |
| # ただし、一般的な文字コード変換では、cp1252 では使われない値が | |
| # '?' などの文字に置き換えられてしまいます。 | |
| # ここでは、Unicode の文字コードをそのままバイト値として採用する必要があります。 | |
| # | |
| # そのため、以下のプログラムは utf-8 文字列を1文字ずつ処理し、データを復元します。 | |
| import argparse | |
| def main(): | |
| parser = argparse.ArgumentParser(description="文字化け UTF-8 ログを復元するツール") | |
| parser.add_argument("input_file", help="入力ファイルパス (文字化けを含むログ)") | |
| parser.add_argument("output_file", help="出力ファイルパス (復元後のテキスト)") | |
| args = parser.parse_args() | |
| # 入力ファイルをバイナリで読み込む | |
| with open(args.input_file, "rb") as f: | |
| data = f.read() | |
| # UTF-8 デコード | |
| text = data.decode("utf-8") | |
| # ハイブリッド復元 | |
| rebuilt_bytes = bytearray() | |
| for c in text: | |
| try: | |
| # CP1252 に存在する文字ならそれでバイト化 | |
| rebuilt_bytes.extend(c.encode("cp1252")) | |
| except UnicodeEncodeError: | |
| # それ以外は下位8ビット | |
| rebuilt_bytes.append(ord(c) & 0xFF) | |
| # 出力 | |
| with open(args.output_file, "wb") as f: | |
| f.write(rebuilt_bytes) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment