subprocess.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. import subprocess
  16. from ....utils.logging import info
  17. __all__ = ["run_cmd", "CompletedProcess"]
  18. def run_cmd(
  19. cmd,
  20. env=None,
  21. silent=True,
  22. cwd=None,
  23. timeout=None,
  24. echo=False,
  25. pipe_stdout=False,
  26. pipe_stderr=False,
  27. blocking=True,
  28. async_run=False,
  29. text=True,
  30. ):
  31. """Wrap around `subprocess.Popen` to execute a shell command."""
  32. # TODO: Limit argument length
  33. cfg = dict(env=env, cwd=cwd)
  34. async_run = async_run and not blocking
  35. if blocking:
  36. cfg["timeout"] = timeout
  37. if silent:
  38. cfg["stdout"] = (
  39. subprocess.DEVNULL if not async_run else asyncio.subprocess.DEVNULL
  40. )
  41. cfg["stderr"] = (
  42. subprocess.STDOUT if not async_run else asyncio.subprocess.STDOUT
  43. )
  44. if not async_run and (pipe_stdout or pipe_stderr):
  45. cfg["text"] = True
  46. if pipe_stdout:
  47. cfg["stdout"] = subprocess.PIPE if not async_run else asyncio.subprocess.PIPE
  48. if pipe_stderr:
  49. cfg["stderr"] = subprocess.PIPE if not async_run else asyncio.subprocess.PIPE
  50. if echo:
  51. info(str(cmd))
  52. if blocking:
  53. return subprocess.run(cmd, **cfg, check=False)
  54. else:
  55. if async_run:
  56. return asyncio.create_subprocess_exec(cmd[0], *cmd[1:], **cfg)
  57. else:
  58. if text:
  59. cfg.update(dict(bufsize=1, text=True))
  60. else:
  61. cfg.update(dict(bufsize=0, text=False))
  62. return subprocess.Popen(cmd, **cfg)
  63. class CompletedProcess(object):
  64. """CompletedProcess"""
  65. __slots__ = ["args", "returncode", "stdout", "stderr", "_add_attrs"]
  66. def __init__(self, args, returncode, stdout=None, stderr=None):
  67. super().__init__()
  68. self.args = args
  69. self.returncode = returncode
  70. self.stdout = stdout
  71. self.stderr = stderr
  72. self._add_attrs = dict()
  73. def __getattr__(self, name):
  74. try:
  75. val = self._add_attrs[name]
  76. return val
  77. except KeyError:
  78. raise AttributeError
  79. def __setattr__(self, name, val):
  80. try:
  81. super().__setattr__(name, val)
  82. except AttributeError:
  83. self._add_attrs[name] = val
  84. def __repr__(self):
  85. args = [f"args={repr(self.args)}", f"returncode={repr(self.returncode)}"]
  86. if self.stdout is not None:
  87. args.append(f"stdout={repr(self.stdout)}")
  88. if self.stderr is not None:
  89. args.append(f"stderr={repr(self.stderr)}")
  90. return f"{self.__class__.__name__}({', '.join(args)})"