2
votes

This simple program in Python 3 throws errors. What could be the reason? This problem arose after I installed/reinstalled Python 3.5/3.6. Also Python 2.7 is installed on my PC (windows 10 machine).

import subprocess 
out = subprocess.check_output(['dir'])

The error message:

File "C:\Python36\lib\subprocess.py", line 336, in check_output **kwargs).stdout

File "C:\Python36\lib\subprocess.py", line 403, in run with Popen(*popenargs, **kwargs) as process:

File "C:\Python36\lib\subprocess.py", line 707, in init restore_signals, start_new_session)

File "C:\Python36\lib\subprocess.py", line 990, in _execute_child startupinfo)

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

3

3 Answers

3
votes

It's not an executable, but built-in to the shell. Python subprocess module can't find it, so you got an error.

If you would like to play with subprocess module, use some existing binary, e.g. python, notepad or ping. In case you need to list folder content, please use os.listdir or os.walk.

1
votes

It seems that "dir" is not in your path. I do not know the full path of this executable on Windows but maybe you should replace dir by c:\windwos\system\dir

Or a best solution would be to use functions in the os modules to list directories:

os.listdir(path)
0
votes

In addition to @grundic

It's not an executable, but built-in to the shell. [...]

If you really want to execute cmd built in commands, you have to execute cmd.exe /c COMMAND_HERE in your case:

import subprocess 
out = subprocess.check_output(['cmd.exe', '/c', 'dir'])

/c means that cmd.exe closes after execution