如何在Python subprocess参数中正确输入Windows路径
解决Python subprocess调用Windows start命令报错FileNotFoundError的问题
问题原因
start是Windows cmd.exe的内置命令,并非独立的可执行程序。你之前的写法都是把它当作单独的可执行文件传入subprocess,导致系统找不到对应程序,抛出FileNotFoundError。
正确解决方案
方案1:通过cmd执行start命令
可以通过两种方式让subprocess调用cmd来执行start命令:
# 启用shell=True,让系统通过默认shell(cmd)执行命令 subprocess.run('start "C:\\Windows\\notepad.exe"', shell=True) # 显式调用cmd.exe,/c参数表示执行完命令后关闭cmd窗口 subprocess.run(['cmd.exe', '/c', 'start', '', 'C:\\Windows\\notepad.exe'])
注意:start命令的第一个带引号参数会被当作窗口标题,所以加一个空字符串''占位,避免路径含空格时出现异常。
方案2:直接调用目标程序(推荐)
完全不需要依赖start命令,subprocess可以直接调用notepad的可执行文件路径,更高效且不依赖shell:
# 完整路径调用 subprocess.run(['C:\\Windows\\notepad.exe']) # 简化写法(notepad在系统环境变量PATH中) subprocess.run(['notepad.exe'])
内容的提问来源于stack exchange,提问作者Xer
相关产品推荐
相关产品推荐

