format.py 792 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/env python
  2. import subprocess
  3. import sys
  4. import os
  5. def run_yapf(target):
  6. if os.path.isfile(target):
  7. files = [target]
  8. else:
  9. files = [os.path.join(root, file) for root, _, files in os.walk(target) for file in files if file.endswith('.py')]
  10. for file in files:
  11. try:
  12. command = ["yapf", "-i", file]
  13. subprocess.run(command, check=True, capture_output=True, text=True)
  14. print(f"Formatted: {file}")
  15. except subprocess.CalledProcessError as e:
  16. print(f"Error formatting {file}: {e.stderr}")
  17. def main():
  18. if len(sys.argv) < 2:
  19. print("Usage: python3 format.py <directory_or_file> e.g. python3 format.py ./exo")
  20. sys.exit(1)
  21. target = sys.argv[1]
  22. run_yapf(target)
  23. print("Formatting completed.")
  24. if __name__ == "__main__":
  25. main()