0

Could someone explain this error to me:

>>> def j():
...     import subprocess
...     print(subprocess.Popen(['command', '-v', 'nmcli'],     stdout=subprocess.PIPE, stderr=subprocess.PIPE))
... 
>>> j()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in j
File "/usr/lib/python3.4/subprocess.py", line 859, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1457, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'command'

I tried as a string as a list, it does not change anything.

tripleee
  • 175,061
  • 34
  • 275
  • 318
John Doe
  • 1,570
  • 3
  • 13
  • 22
  • For the somewhat more common case of FileNotFoundErrors for commands which are not shell builtins, see https://stackoverflow.com/questions/24306205/file-not-found-error-when-launching-a-subprocess-containing-piped-commands – tripleee Oct 15 '20 at 06:53

1 Answers1

2

FileNotFoundError: [Errno 2] No such file or directory: 'command'

command is a shell builtin. subprocess.Popen does NOT run the shell by default.

To run the shell, pass shell=True:

>>> import subprocess
>>> subprocess.check_output('command -v python', shell=True)
b'/usr/bin/python\n'

To find the full path to an executable, you could use shutil.which() instead:

>>> import shutil
>>> shutil.which('python')
'/usr/bin/python'
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • I actually tried Popen with a shell set at True but it returned 2 empty 'b' strings.. And thanks for the shutil tip, I never think of this one : now I will ! Thanks again ! – John Doe Jan 29 '16 at 09:20