python3 subprocess.Popen 报错 No such file or directory

问题描述 

在当前目录中,当os.system("ls")查找文件时正确,命令subprocess.Popen(["wc -l filename"], stdout=subprocess.PIPE)不起作用。

代码如下:

>>> import os
>>> import subprocess
>>> os.system("ls")
sorted_list.dat
0
>>> p = subprocess.Popen(["wc -l sorted_list.dat"], stdout=subprocess.PIPE)
File"<stdin>", line 1, in <module>
File"/Users/a200/anaconda/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
File"/Users/a200/anaconda/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

问题原因

发生此错误是因为您正在尝试运行名为wc -l sorted_list.dat的命令,也就是说,它正在尝试查找名为"/usr/bin/wc -l sorted dat"的文件。

解决方法

您应该将参数作为列表传递(推荐):

subprocess.Popen(["wc","-l","sorted_list.dat"], stdout=subprocess.PIPE)

否则,如果要将整个"wc -l sorted_list.dat"字符串用作命令,则需要传递shell=True(不建议这样做,可能会导致安全隐患)。

subprocess.Popen("wc -l sorted_list.dat", shell=True, stdout=subprocess.PIPE)

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值