compat.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import io
  2. import platform
  3. def patch_psutil():
  4. """WSL's /proc/meminfo has an inconsistency where it
  5. nondeterministically omits a space after colons (after "SwapFree:"
  6. in my case).
  7. psutil then splits on spaces and then parses the wrong field,
  8. crashing on the 'int(fields[1])' expression in
  9. psutil._pslinux.virtual_memory().
  10. Workaround: We ensure there is a space following each colon.
  11. """
  12. assert (
  13. platform.system() == "Linux"
  14. and "Microsoft".lower() in platform.release().lower()
  15. )
  16. try:
  17. import psutil._pslinux
  18. except ImportError:
  19. psutil = None
  20. psutil_open_binary = None
  21. if psutil:
  22. try:
  23. psutil_open_binary = psutil._pslinux.open_binary
  24. except AttributeError:
  25. pass
  26. # Only patch it if it doesn't seem to have been patched already
  27. if psutil_open_binary and psutil_open_binary.__name__ == "open_binary":
  28. def psutil_open_binary_patched(fname, *args, **kwargs):
  29. f = psutil_open_binary(fname, *args, **kwargs)
  30. if fname == "/proc/meminfo":
  31. with f:
  32. # Make sure there's a space after colons
  33. return io.BytesIO(f.read().replace(b":", b": "))
  34. return f
  35. psutil._pslinux.open_binary = psutil_open_binary_patched