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.

相关文章
相关标签/搜索