3

I would like to check the result of a Bash command in a Python script. I'm using subprocess.check_output().

Before that, I checked manually the result of two commands in a shell:

user@something:~$ hostname
> something

user@something:~$ command -v apt
> /usr/bin/apt

It works as expected. Now I'm trying to run the subprocess.check_output() function in the Python interpreter:

>>> import subprocess
>>> subprocess.check_output(['hostname'], shell=True, stderr=subprocess.STDOUT)
b'something\n'
>>> subprocess.check_output(['command', '-v', 'apt'], shell=True, stderr=subprocess.STDOUT)
b''

As you can see, the first command is working as expected, but not the second (as it returns an empty string). Why is that?

EDIT

I already tried removing shell=True, it returns an error:

>>> subprocess.check_output(['command', '-v', 'apt'], stderr=subprocess.STDOUT)
Traceback (most recent call last):
[...]
FileNotFoundError: [Errno 2] No such file or directory: 'command'

1 Answers1

0

Drop shell=True from the parameters:

>>> subprocess.check_output(['command', '-v', 'apt'], stderr=subprocess.STDOUT) 
'/usr/bin/apt\n'

See Actual meaning of 'shell=True' in subprocess.

If shell is True, it is recommended to pass args as a string rather than as a sequence.

This ensures the command is properly formatted as it would if you had typed it directly in your shell:

>>> subprocess.check_output('command -v apt', shell=True, stderr=subprocess.STDOUT)
'/usr/bin/apt\n'

However, using shell is generally discouraged.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139