不设置shell=True时,subprocess.Popen执行Windows dir命令报错
为什么不设置
shell=True时subprocess.Popen执行dir命令会报错? 问题场景
尝试用subprocess.Popen执行Windows的dir命令,不设置shell=True时报错,示例代码如下:
import subprocess import os import time input='E:\Projects\ML' command = "dir "+input+' /s /b ' os.system(command) status=subprocess.Popen(command.split(' '),shell=False,text=True,cwd=input,stdout=subprocess.PIPE) while status.wait()!=0: time.sleep(1) print(status.communicate())
使用os.system()能正常返回结果,但Popen()抛出如下错误:
Traceback (most recent call last): File "e:\Projects\ArchiveViewer\PythonR&D\EncriptionWithPopen\runLocalCMD.py", line 9, in <module> status=subprocess.Popen(command.split(' '),shell=False,text=True,cwd=input,stdout=subprocess.PIPE) File "C:\Users\nmaiya\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\nmaiya\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] The system cannot find the file specified
原因解析
dir不是独立的可执行程序,它是Windows命令提示符(cmd.exe)的内置命令,只能在cmd.exe的运行环境中被识别和执行。- 当
shell=False时,subprocess.Popen会直接把传入的第一个参数当作可执行文件路径去系统中查找,而系统里不存在名为dir的可执行文件(比如dir.exe),所以触发FileNotFoundError。 os.system()之所以能正常运行,是因为它默认会自动启动cmd.exe来解析并执行传入的命令,相当于隐式启用了shell环境。- 如果不想设置
shell=True,要执行dir命令的话,需要显式调用cmd.exe,把dir作为参数传递,示例代码:
其中status = subprocess.Popen(['cmd.exe', '/c', command], shell=False, text=True, cwd=input, stdout=subprocess.PIPE)/c参数的作用是让cmd.exe执行完指定命令后自动退出。
内容的提问来源于stack exchange,提问作者Narasimha Maiya
相关产品推荐
相关产品推荐

