utils.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. import subprocess
  3. def sudo_getsize(path):
  4. """Retourne la taille d'un fichier via sudo stat si non accessible directement."""
  5. try:
  6. return os.path.getsize(path)
  7. except OSError:
  8. result = subprocess.run(
  9. ["sudo", "stat", "--format=%s", path],
  10. capture_output=True, text=True,
  11. )
  12. if result.returncode == 0:
  13. try:
  14. return int(result.stdout.strip())
  15. except ValueError:
  16. pass
  17. return 0
  18. def sudo_getmtime(path):
  19. """Retourne le mtime d'un fichier via sudo stat si non accessible directement."""
  20. try:
  21. return os.path.getmtime(path)
  22. except OSError:
  23. result = subprocess.run(
  24. ["sudo", "stat", "--format=%Y", path],
  25. capture_output=True, text=True,
  26. )
  27. if result.returncode == 0:
  28. try:
  29. return float(result.stdout.strip())
  30. except ValueError:
  31. pass
  32. return 0.0
  33. def sudo_listdir(directory):
  34. """Liste les fichiers d'un répertoire via sudo find si non accessible directement."""
  35. try:
  36. return os.listdir(directory)
  37. except OSError:
  38. result = subprocess.run(
  39. ["sudo", "find", directory, "-maxdepth", "1", "-mindepth", "1",
  40. "-printf", "%f\n"],
  41. capture_output=True, text=True,
  42. )
  43. if result.returncode == 0:
  44. return [f for f in result.stdout.strip().split("\n") if f]
  45. return []