subprocess报错FileNotFoundError: [WinError 2] 系统找不到指定的文件

0x00 环境

名称
OS系统windows 7 64bit
编程语言python 3.7

0x01 问题

使用subprocess.Popen执行命令报错,错误信息如下:

Traceback (most recent call last):
  File "xxx.py", line 4, in addLabel
    output = Popen('dir',stdout=PIPE)
  File "D:\Program Files\Python3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "D:\Program Files\Python3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] 系统找不到指定的文件。

源码如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE
output = Popen('dir',stdout=PIPE)

0x02 原因

dir 命令是cmd.exe 或者powershell.exe才能理解的命令。在Windows环境下subprocess.Popen默认是不会调用cmd.exe的。所以需要指定。

subprocess.Popen(["cmd", "/c", "dir", "c:\\Users"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

0x03 扩展

------2020/08/28 更新

在执行部分命令是,会提示错误“文件名,目录名称或卷标签语法不正确”。
这个问题是目录中含有空格时,命令执行失败。
错误的写法是:

subprocess.Popen(["cmd", "/c", "dir", r'"c:\Users\new world"'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

正确的写法:

subprocess.Popen(["cmd", "/c", "dir", r'c:\Users\new world'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

0x04 参考链接

https://stackoverflow.com/questions/49018413/filenotfounderror-subprocess-popendir-windows-7

  • 9
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值