utils.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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_exists(path):
  34. """Vérifie l'existence d'un fichier via sudo si non accessible directement."""
  35. if os.path.exists(path):
  36. return True
  37. result = subprocess.run(
  38. ["sudo", "stat", path],
  39. capture_output=True,
  40. )
  41. return result.returncode == 0
  42. def sudo_listdir(directory):
  43. """Liste les fichiers d'un répertoire via sudo find si non accessible directement."""
  44. try:
  45. return os.listdir(directory)
  46. except OSError:
  47. result = subprocess.run(
  48. ["sudo", "find", directory, "-maxdepth", "1", "-mindepth", "1",
  49. "-printf", "%f\n"],
  50. capture_output=True, text=True,
  51. )
  52. if result.returncode == 0:
  53. return [f for f in result.stdout.strip().split("\n") if f]
  54. return []