Python 3 subprocess module throws error running “dir” on Windows

本秂侑毒 提交于 2020-11-28 02:45:29

问题


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


回答1:


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.




回答2:


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)



回答3:


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



来源:https://stackoverflow.com/questions/45282997/python-3-subprocess-module-throws-error-running-dir-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!