Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: "FileNotFoundError" on all Subprocess calls

Using Windows 7, Python 3.5.1:

import subprocess
subprocess.check_output(['echo', 'hello'])

raises the error:

Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
    subprocess.check_output(['echo', 'hello'])
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 629, in check_output
    **kwargs).stdout
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 696, in run
    with Popen(*popenargs, **kwargs) as process:
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 1220, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified

This error occurs with all subprocess calls, such as subprocess.run, subprocess.call, and subproccess.Popen. The same error happens regardless of what command is used:

subprocess.check_output(['['D:\path\to\exe\program.exe', 'argument'])
FileNotFoundError: [WinError 2] The system cannot find the file specified

As far as I can tell, this error usually occurs when the command tries to execute a nonexistent path, but I can't determine why it would occur in these cases.

like image 687
joedeandev Avatar asked Dec 16 '17 15:12

joedeandev


1 Answers

You need to include the full path to your executable. E.g.,

import subprocess
subprocess.check_output(['/bin/echo', 'hello'])

(Not sure precisely where it is on Windows, though.)

Note: Using shell=True will also make it happen to work, but I don't recommend solving it that way because (1) your PATH resolution will effectively be a side-effect (you'll have a hidden dependency on the value of PATH at runtime), and (2) there are security concerns.

like image 85
ron rothman Avatar answered Nov 19 '22 21:11

ron rothman