_baseprocess.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # -*- test-case-name: twisted.test.test_process -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Cross-platform process-related functionality used by different
  6. L{IReactorProcess} implementations.
  7. """
  8. from typing import Optional
  9. from twisted.logger import Logger
  10. from twisted.python.deprecate import getWarningMethod
  11. from twisted.python.failure import Failure
  12. from twisted.python.reflect import qual
  13. _log = Logger()
  14. _missingProcessExited = (
  15. "Since Twisted 8.2, IProcessProtocol.processExited "
  16. "is required. %s must implement it."
  17. )
  18. class BaseProcess:
  19. pid: Optional[int] = None
  20. status: Optional[int] = None
  21. lostProcess = 0
  22. proto = None
  23. def __init__(self, protocol):
  24. self.proto = protocol
  25. def _callProcessExited(self, reason):
  26. default = object()
  27. processExited = getattr(self.proto, "processExited", default)
  28. if processExited is default:
  29. getWarningMethod()(
  30. _missingProcessExited % (qual(self.proto.__class__),),
  31. DeprecationWarning,
  32. stacklevel=0,
  33. )
  34. else:
  35. with _log.failuresHandled("while calling processExited:"):
  36. processExited(Failure(reason))
  37. def processEnded(self, status):
  38. """
  39. This is called when the child terminates.
  40. """
  41. self.status = status
  42. self.lostProcess += 1
  43. self.pid = None
  44. self._callProcessExited(self._getReason(status))
  45. self.maybeCallProcessEnded()
  46. def maybeCallProcessEnded(self):
  47. """
  48. Call processEnded on protocol after final cleanup.
  49. """
  50. if self.proto is not None:
  51. reason = self._getReason(self.status)
  52. proto = self.proto
  53. self.proto = None
  54. with _log.failuresHandled("while calling processEnded:"):
  55. proto.processEnded(Failure(reason))