Python3子进程模块在Windows上运行“dir”时抛出错误

2024-04-26 07:15:45 发布

您现在位置:Python中文网/ 问答频道 /正文

{}中的这个简单程序会抛出错误。原因可能是什么?这个问题是在我安装/重新安装Python 3.5/3.6之后出现的。另外Python 2.7安装在我的电脑(windows 10计算机)上

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

错误消息:

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


Tags: inpy程序outputwindowslibcheck错误
3条回答

它不是可执行文件,而是shell的built-in。Python子流程模块找不到它,因此出现错误

如果您想使用子流程模块,请使用一些现有的二进制文件,例如pythonnotepadping。 如果您需要列出文件夹内容,请使用^{}^{}

似乎“dir”不在您的路径中。我不知道此可执行文件在Windows上的完整路径,但也许您应该将dir替换为c:\windwos\system\dir

或者,最好的解决方案是使用操作系统模块中的函数列出目录:

os.listdir(path)

除了@grundic

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

如果确实要执行cmd内置命令,则必须在本例中执行cmd.exe /c COMMAND_HERE

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

/c表示执行后cmd.exe关闭

相关问题 更多 >