cmd.py 932 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import os
  2. import subprocess
  3. def run_cmd(cmd: str, cwd: str | None = None) -> str | None:
  4. """Run a command and return the output.
  5. If the command succeeds, return None. If the command fails, return the stdout.
  6. """
  7. process = subprocess.Popen(
  8. cmd.split(),
  9. cwd=cwd,
  10. stdout=subprocess.PIPE,
  11. stderr=subprocess.STDOUT,
  12. encoding='utf-8',
  13. errors='replace',
  14. )
  15. stdout, _ = process.communicate()
  16. if process.returncode == 0:
  17. return None
  18. return stdout
  19. def check_tool_installed(tool_name: str) -> bool:
  20. """Check if a tool is installed."""
  21. try:
  22. subprocess.run(
  23. [tool_name, '--version'],
  24. check=True,
  25. cwd=os.getcwd(),
  26. stdout=subprocess.PIPE,
  27. stderr=subprocess.PIPE,
  28. )
  29. return True
  30. except (subprocess.CalledProcessError, FileNotFoundError):
  31. return False