From 645005e947c13c4a0706310a2a46112bf63cadc0 Mon Sep 17 00:00:00 2001 From: Andrey Doroschenko Date: Sun, 17 Nov 2019 17:08:31 +0300 Subject: bpo-38724: Implement subprocess.Popen.__repr__ (GH-17151) --- Lib/subprocess.py | 9 ++++++++ Lib/test/test_subprocess.py | 24 ++++++++++++++++++++++ .../2019-11-14-14-13-29.bpo-38724.T5ySfR.rst | 1 + 3 files changed, 34 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2019-11-14-14-13-29.bpo-38724.T5ySfR.rst diff --git a/Lib/subprocess.py b/Lib/subprocess.py index b5a45d9..ba6f198 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -978,6 +978,15 @@ class Popen(object): raise + def __repr__(self): + obj_repr = ( + f"<{self.__class__.__name__}: " + f"returncode: {self.returncode} args: {list(self.args)!r}>" + ) + if len(obj_repr) > 80: + obj_repr = obj_repr[:76] + "...>" + return obj_repr + @property def universal_newlines(self): # universal_newlines as retained as an alias of text_mode for API diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index 9e96a6d..97dc09c 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -1360,6 +1360,30 @@ class ProcessTestCase(BaseTestCase): self.addCleanup(p.stdin.close) p.communicate(b"x" * 2**20) + def test_repr(self): + # Run a command that waits for user input, to check the repr() of + # a Proc object while and after the sub-process runs. + code = 'import sys; input(); sys.exit(57)' + cmd = [sys.executable, '-c', code] + result = "') + ) + + proc.communicate(input='exit...\n') + proc.wait() + + self.assertIsNotNone(proc.returncode) + self.assertTrue( + repr(proc).startswith(result.format(proc.returncode)) and + repr(proc).endswith('>') + ) + def test_communicate_epipe_only_stdin(self): # Issue 10963: communicate() should hide EPIPE p = subprocess.Popen(ZERO_RETURN_CMD, diff --git a/Misc/NEWS.d/next/Library/2019-11-14-14-13-29.bpo-38724.T5ySfR.rst b/Misc/NEWS.d/next/Library/2019-11-14-14-13-29.bpo-38724.T5ySfR.rst new file mode 100644 index 0000000..a5ebfb3 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-11-14-14-13-29.bpo-38724.T5ySfR.rst @@ -0,0 +1 @@ +Add a repr for ``subprocess.Popen`` objects. Patch by Andrey Doroschenko. \ No newline at end of file -- cgit v0.12