子进程调用 [英] subprocess.call

查看:31
本文介绍了子进程调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 subprocess.call 函数的新手,我尝试了同一个调用的不同组合,但它不起作用.

我正在尝试执行以下命令:

cmd = 'sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout+' >'+outpath+fnameout打印命令

如果我尝试调用,我会收到一个错误:

cmd = cmd.split(" ")打印命令subprocess.call(cmd)

我得到的错误是:

sort: stat failed: >: 没有那个文件或目录

解决方案

这样做,你需要 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 因为`call` 块:)subprocess.call(cmd,stdout=fout)

这避免了一起生成 shell 并且可以安全地免受 shell 注入类型的攻击.此处,cmd 是原始列表中的列表,例如

cmd = 'sort -k1,1 -k4,4n -k5,5n'+outpath+fnametempoutcmd = cmd.split()

还应该说明的是,python 具有非常好的排序功能,因此我怀疑是否真的有必要通过子进程将作业传递给 sort.

<小时>

最后,与其使用 str.split 从字符串中拆分参数,不如使用 shlex.split 因为这样可以正确处理带引号的字符串.

<预><代码>>>>进口shlex>>>cmd = "foo -b -c 'arg in引号'">>>打印 cmd.split()['foo', '-b', '-c', "'arg", 'in', "quotes'"]>>>打印 shlex.split(cmd)['foo', '-b', '-c', 'arg in引号']

I am new to the subprocess.call function and I have tried different combinations of the same call but it is not working.

I am trying to execute the following command:

cmd = 'sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout+' > '+outpath+fnameout
print cmd

If I try the call I get an error:

cmd = cmd.split(" ")
print cmd
subprocess.call(cmd)

the error I get is:

sort: stat failed: >: No such file or directory

解决方案

Doing it this way, you need shell=True to allow the shell redirection to work.

subprocess.call('sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout,shell=True)

A better way is:

with open(outpath+fnameout,'w') as fout: #context manager is OK since `call` blocks :)
    subprocess.call(cmd,stdout=fout)

which avoids spawning a shell all-together and is safe from shell injection type attacks. Here, cmd is a list as in your original, e.g.

cmd = 'sort -k1,1 -k4,4n -k5,5n '+outpath+fnametempout
cmd = cmd.split()

It should also be stated that python has really nice sorting facilities and so I doubt that it is actually necessary to pass the job off to sort via a subprocess.


Finally, rather than using str.split to split the arguments, from a string, it's probably better to use shlex.split as that will properly handle quoted strings.

>>> 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']

这篇关于子进程调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆