[Python-ideas] Add output() helper function to subprocess module

Nathaniel Smith njs at pobox.com
Thu Apr 4 05:10:50 EDT 2019

On Thu, Apr 4, 2019 at 1:59 AM Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Nathaniel Smith wrote:
> > On Thu, Apr 4, 2019 at 12:48 AM Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> >>output(args) --> (status, output)
> >
> > Isn't this already available as: run(args, stdout=PIPE)?
> Yes, but you need to do more than that to get the output
> as a string. This is the relevant part of the implementation
> of check_output():
>      process = Popen(stdout=PIPE, *popenargs, **kwargs)
>      output, unused_err = process.communicate()
>      retcode = process.poll()

>>> from subprocess import run, pipe
>>> p = run(["grep", "njs", "/etc/passwd"], stdout=PIPE)
>>> p.returncode
>>> p.stdout
b'njs:x:1000:1000:Nathaniel J. Smith,,,:/home/njs:/usr/bin/zsh\n'

I do think it's a bit weird that you write 'stdout=PIPE' to mean
'please capture stdout' – it's leaking an internal implementation
detail across an abstraction boundary. But it's documented, and run()
allows any combination of check=True/False, capturing stdout or not,
and capturing stderr or not, without having to invent 8 different


Nathaniel J. Smith -- https://vorpus.org

More information about the Python-ideas mailing list