import msgpack import sys import json def decode_bytes(obj): """ 递归地将 MessagePack 解码后的 bytes 类型转换为 string,方便阅读。 """ if isinstance(obj, bytes): try: return obj.decode('utf-8') except: return str(obj) # 如果不是utf-8,强制转换 elif isinstance(obj, list): return [decode_bytes(item) for item in obj] elif isinstance(obj, dict): return {decode_bytes(key): decode_bytes(value) for key, value in obj.items()} return obj def read_dat_file(file_path): print(f"Reading file: {file_path} ...") try: with open(file_path, 'rb') as f: # Tensile 的 dat 文件通常直接就是一个 msgpack 对象 data = msgpack.unpack(f, raw=True) # raw=True 返回 bytes,需要手动解码 readable_data = decode_bytes(data) # 内容太多,保存到文件 output_file = file_path + ".json" with open(output_file, 'w') as f_out: json.dump(readable_data, f_out, indent=2) print(f"Success! Decoded data saved to: {output_file}") # 尝试打印顶层结构 if isinstance(readable_data, list): print(f"Top level structure is a LIST with {len(readable_data)} elements.") elif isinstance(readable_data, dict): print(f"Top level keys: {list(readable_data.keys())}") except Exception as e: print(f"Error reading file: {e}") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python read_tensile.py ") else: read_dat_file(sys.argv[1])