adb logcat 写文件乱码的解决方案

139 阅读1分钟

如果在 Windows 下直接 adb logcat 写文件是会存在乱码的问题,这边建议使用 Python 脚本解决这个问题

import subprocess
import sys
from datetime import datetime

def run_adb_logcat(output_file=None):
    try:
        # 如果没有指定输出文件,使用当前时间创建文件名
        if output_file is None:
            output_file = f"logcat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        
        # 执行 adb logcat 命令
        process = subprocess.Popen(
            ['adb', 'logcat'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            encoding='utf-8',
            errors='replace'  # 处理无法解码的字符
        )
        
        # 打开文件准备写入
        with open(output_file, 'w', encoding='utf-8') as f:
            while True:
                try:
                    # 读取一行输出
                    line = process.stdout.readline()
                    if not line:
                        break
                    
                    # 写入文件
                    f.write(line)
                    # 立即刷新缓冲区
                    f.flush()
                    
                except KeyboardInterrupt:
                    print("\n停止记录日志")
                    break
                except Exception as e:
                    print(f"发生错误: {str(e)}")
                    break
        
        # 终止进程
        process.terminate()
        
    except Exception as e:
        print(f"执行出错: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    # 可以指定输出文件名,如果不指定则使用默认的时间戳文件名
    output_file = sys.argv[1] if len(sys.argv) > 1 else None
    run_adb_logcat(output_file)