Command 'command' not found in python subprocess

6,721

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).

Share:
6,721

Related videos on Youtube

eee
Author by

eee

Updated on September 18, 2022

Comments

  • eee
    eee over 1 year

    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

  • eee
    eee about 6 years
    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.
  • roaima
    roaima over 5 years
    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.)