1

Using the command command in the following python script is not successful:

import subprocess

subprocess.run(["command", "-v", "yes"])

and results in

Traceback (most recent call last):
  File "command_test.py", line 3, in <module>
    subprocess.run(["command", "-v", "yes"])
  File "/usr/lib/python3.5/subprocess.py", line 383, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'command'

In the shell (zsh) this is working as expected:

$ command -v yes         
/usr/bin/yes

How can I use command in a python subprocess? Do I have to install some additional packages?

Environment:

Debian 9 (stretch) with Python 3.5.3 and zsh 5.3.1

3 Answers 3

4

command is a shell builtin so not an own object in the file system.

See man bash/man zsh or help command.

$ python3 -c 'import subprocess ; subprocess.run(["bash","-c","command -v yes"])'
/usr/bin/yes

May be a solution (I have no zsh installed, so my example uses bash instead).

1
  • This is working, thanks. Additionally I found the shell flag for the run command subprocess.run(["command -v yes"], shell=True) which also solves the problem. Commented Mar 10, 2018 at 10:36
1

If you're using Python 3.5, you don't need to use command -v to get the path of an executable. There's shutil.which() (available from 3.3, I think).

import shutil
yes_path = shutil.which('yes')

Example:

$ python3 -c 'import shutil; print(shutil.which("yes"))'
/usr/bin/yes
0
import subprocess
subprocess.run(['command', executable='/bin/bash',shell=True])
2
  • 1
    Hello Nisha. To make this a good answer, rather than just providing code it would be help to explain (to future readers, even if not to the OP) why this would resolve the issue described. You don't need excruciating detail; just a sentence might be sufficient. (I would guess the downvote is because either it doesn't address the issue as described, or there's nothing describing why this answer should be useful.) Commented Nov 16, 2018 at 10:14
  • Shell = True does really stops the error, but just fix the ["command", "-v", ....], executable=......) Commented Jun 16, 2022 at 18:57

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.