desc_table.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. """
  4. 查看 ODPS 表结构
  5. 使用示例:
  6. python desc_table.py loghubods.opengid_base_data
  7. python desc_table.py videoods.wx_user_wechar_detail
  8. """
  9. import argparse
  10. from pathlib import Path
  11. from lib.odps_module import ODPSClient
  12. PROJECT_ROOT = Path(__file__).parent
  13. def desc_table(table_name: str):
  14. """查看表结构,返回格式化的字符串"""
  15. # 解析 project.table 格式
  16. if '.' in table_name:
  17. project, table = table_name.split('.', 1)
  18. else:
  19. project = 'loghubods'
  20. table = table_name
  21. client = ODPSClient(project=project)
  22. t = client.odps.get_table(table)
  23. lines = []
  24. lines.append(f"表名: {project}.{table}")
  25. lines.append(f"注释: {t.comment or '(无)'}")
  26. lines.append(f"创建时间: {t.creation_time}")
  27. lines.append(f"最后修改: {t.last_data_modified_time}")
  28. lines.append("")
  29. lines.append("=" * 60)
  30. lines.append(f"{'字段名':<30} {'类型':<15} {'注释'}")
  31. lines.append("=" * 60)
  32. for col in t.table_schema.columns:
  33. comment = col.comment or ''
  34. lines.append(f"{col.name:<30} {col.type.name:<15} {comment}")
  35. if t.table_schema.partitions:
  36. lines.append("")
  37. lines.append("分区字段:")
  38. lines.append("-" * 60)
  39. for p in t.table_schema.partitions:
  40. comment = p.comment or ''
  41. lines.append(f"{p.name:<30} {p.type.name:<15} {comment}")
  42. return "\n".join(lines), project, table
  43. def save_and_print(table_name: str):
  44. """查看表结构并保存到文件"""
  45. content, project, table = desc_table(table_name)
  46. # 输出目录: tables/project/table.txt
  47. output_dir = PROJECT_ROOT / "tables" / project
  48. output_dir.mkdir(parents=True, exist_ok=True)
  49. output_file = output_dir / f"{table}.txt"
  50. # 保存文件
  51. with open(output_file, 'w', encoding='utf-8') as f:
  52. f.write(content)
  53. # 打印到终端
  54. print(content)
  55. print()
  56. print(f"已保存到: {output_file}")
  57. def main():
  58. parser = argparse.ArgumentParser(description='查看 ODPS 表结构')
  59. parser.add_argument('table', type=str, help='表名,如 loghubods.table_name')
  60. args = parser.parse_args()
  61. save_and_print(args.table)
  62. if __name__ == "__main__":
  63. main()