我是 subprocess.call 函数的新手,我尝试了同一调用的不同组合,但它不起作用。
我正在尝试执行以下命令:
cmd = 'sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout+' > '+outpath+fnameout
print cmd
如果我尝试调用我会得到一个错误:
cmd = cmd.split(" ")
print cmd
subprocess.call(cmd)
我得到的错误是:
sort: stat failed: >: No such file or directory
最佳答案
这样做,您需要 shell=True
以允许 shell 重定向工作。
subprocess.call('sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout,shell=True)
更好的方法是:
with open(outpath+fnameout,'w') as fout: #context manager is OK since `call` blocks :)
subprocess.call(cmd,stdout=fout)
这避免了一起生成 shell,并且可以免受 shell 注入(inject)类型的攻击。在这里,cmd
是您原来的列表,例如
cmd = 'sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout
cmd = cmd.split()
还应该指出,python 具有非常好的排序功能,因此我怀疑是否真的有必要通过子进程将工作传递给 sort
。
最后,与其使用 str.split
从字符串中拆分参数,不如使用 shlex.split
更好,因为它可以正确处理引用的字符串。
>>> import shlex
>>> cmd = "foo -b -c 'arg in quotes'"
>>> print cmd.split()
['foo', '-b', '-c', "'arg", 'in', "quotes'"]
>>> print shlex.split(cmd)
['foo', '-b', '-c', 'arg in quotes']
关于python - 子进程调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14386775/