subprocess.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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(cmd,
  19. env=None,
  20. silent=True,
  21. cwd=None,
  22. timeout=None,
  23. echo=False,
  24. pipe_stdout=False,
  25. pipe_stderr=False,
  26. blocking=True,
  27. async_run=False,
  28. text=True):
  29. """Wrap around `subprocess.Popen` to execute a shell command."""
  30. # TODO: Limit argument length
  31. cfg = dict(env=env, cwd=cwd)
  32. async_run = async_run and not blocking
  33. if blocking:
  34. cfg['timeout'] = timeout
  35. if silent:
  36. cfg['stdout'] = subprocess.DEVNULL if not async_run else asyncio.subprocess.DEVNULL
  37. cfg['stderr'] = subprocess.STDOUT if not async_run else asyncio.subprocess.STDOUT
  38. if not async_run and (pipe_stdout or pipe_stderr):
  39. cfg['text'] = True
  40. if pipe_stdout:
  41. cfg['stdout'] = subprocess.PIPE if not async_run else asyncio.subprocess.PIPE
  42. if pipe_stderr:
  43. cfg['stderr'] = subprocess.PIPE if not async_run else asyncio.subprocess.PIPE
  44. if echo:
  45. info(str(cmd))
  46. if blocking:
  47. return subprocess.run(cmd, **cfg, check=False)
  48. else:
  49. if async_run:
  50. return asyncio.create_subprocess_exec(cmd[0], *cmd[1:], **cfg)
  51. else:
  52. if text:
  53. cfg.update(dict(bufsize=1, text=True))
  54. else:
  55. cfg.update(dict(bufsize=0, text=False))
  56. return subprocess.Popen(cmd, **cfg)
  57. class CompletedProcess(object):
  58. """ CompletedProcess """
  59. __slots__ = ['args', 'returncode', 'stdout', 'stderr', '_add_attrs']
  60. def __init__(self, args, returncode, stdout=None, stderr=None):
  61. super().__init__()
  62. self.args = args
  63. self.returncode = returncode
  64. self.stdout = stdout
  65. self.stderr = stderr
  66. self._add_attrs = dict()
  67. def __getattr__(self, name):
  68. try:
  69. val = self._add_attrs[name]
  70. return val
  71. except KeyError:
  72. raise AttributeError
  73. def __setattr__(self, name, val):
  74. try:
  75. super().__setattr__(name, val)
  76. except AttributeError:
  77. self._add_attrs[name] = val
  78. def __repr__(self):
  79. args = [
  80. f"args={repr(self.args)}", f"returncode={repr(self.returncode)}"
  81. ]
  82. if self.stdout is not None:
  83. args.append(f"stdout={repr(self.stdout)}")
  84. if self.stderr is not None:
  85. args.append(f"stderr={repr(self.stderr)}")
  86. return f"{self.__class__.__name__}({', '.join(args)})"