Python subprocess.Popen 只接受 list 不接受单个 string

参考:http://stackoverflow.com/questions/901982/python-oserror-errno-2


【问题】


对 Python 的 subprocess.Popen() 和 subprocess.call() 传入一个单个的命令行,比如 'ls -lrt',执行时 Python 报错:

......
  File "Muxer.py", line 34, in dat_2_avc
    subprocess.Popen('ls -lrt')
  File "/usr/local/lib/python2.7/subprocess.py", line 709, in __init__
    errread, errwrite)
  File "/usr/local/lib/python2.7/subprocess.py", line 1326, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

【原因】


subprocess.Popen() 和 subprocess.call() 只接受 list 类型参数,如果传入单个 string,则整个 string ('ls -lrt')会被识别成 list 的第一元素,即本该执行的命令名称是 'ls',结果识别成了 'ls -lrt',于是系统找不到一个叫做 'ls -lrt' 的命令。


【解决】


传入 list,或将命令行 string 转成 list 后再传入。比如,subprocess.Popen(shlex.split('ls -lrt'))


StackOverflow 的回答摘录如下:


The problem is that your command should be split. subprocces requires that the cmd is a list, not a string. It Shoudn't be:

subprocess.call('''awk 'BEGIN {FS="\t";OFS="\n"} {a[$1]=a [$1] OFS $2 FS $3 FS $4} END
{for (i in a) {print i a[i]}}' 2_lcsorted.txt > 2_locus_2.txt''') 

That won't work. If you feed subprocess a string, it assumes that that is the path to the command you want to execute. The command needs to be a list. Check out http://www.gossamer-threads.com/lists/python/python/724330. Also, because you're using file redirection, you should use subprocess.call(cmd, shell=True). You can also use shlex.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值