subprocess: unexpected keyword argument capture_output

PythonSubprocess

Python Problem Overview


When executing subprocess.run() as given in the Python docs, I get a TypeError:

>>> import subprocess
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/subprocess.py", line 403, in run
    with Popen(*popenargs, **kwargs) as process:
TypeError: __init__() got an unexpected keyword argument 'capture_output'

I am running Python 3.6.6:

$ python3 --version
Python 3.6.6

Python Solutions


Solution 1 - Python

You inspected the wrong documentation, for [tag:Python-3.6] this parameter does not exist, as can be found in the documentation (you select the version at the top left):

> subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, > shell=False, cwd=None, timeout=None, check=False, encoding=None, > errors=None, env=None)

You can however easily "emulate" this by setting both stdout and stderr to PIPE:

from subprocess import PIPE




subprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)

subprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)

In fact, if we look at the source code of the [tag:Python-3.7] version, where the feature was introduced, we see in the source code [GitHub]:

> if capture_output: > if ('stdout' in kwargs) or ('stderr' in kwargs): > raise ValueError('stdout and stderr arguments may not be used ' > 'with capture_output.') > kwargs['stdout'] = PIPE > kwargs['stderr'] = PIPE

Solution 2 - Python

The simplest method is to use the subprocess.check_output function:

import subprocess
subprocess.check_output(["ls", "-l", "/dev/null"])

Solution 3 - Python

I ran into this error because I was calling subprocess.call (which is the old high level API) instead of subprocess.run.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTijsView Question on Stackoverflow
Solution 1 - PythonWillem Van OnsemView Answer on Stackoverflow
Solution 2 - PythonHugo SohmView Answer on Stackoverflow
Solution 3 - PythonBoris VerkhovskiyView Answer on Stackoverflow