重定向标准输出时在python上调用子进程时出错

重定向标准输出时在python上调用子进程时出错,python,subprocess,Python,Subprocess,我尝试过滤python脚本中函数生成的文件: out = subprocess.check_output(["sed","-n","'s/pattern/&/p'",oldFile,">",newFile]) 但是,我的命令有以下错误: returned non-zero exit status 1 怎么了?正如devnull所说,是由shell解释的。既然是,请改用stdout参数: import subprocess with open(newFile, 'w') as n

我尝试过滤python脚本中函数生成的文件:

out = subprocess.check_output(["sed","-n","'s/pattern/&/p'",oldFile,">",newFile])
但是,我的命令有以下错误:

returned non-zero exit status 1

怎么了?

正如devnull所说,
是由shell解释的。既然是,请改用
stdout
参数:

import subprocess
with open(newFile, 'w') as newFile:
    subprocess.check_call(
        ["sed", "-n", "s/S/&/p", oldFile], stdout=newFile)

您正在使用
重定向,这需要一个shell来解释语法

当您重定向
sed
的输出时,此处没有使用
检查输出的必要。改为使用或并验证返回代码

通过shell运行命令:

import pipes

out = subprocess.call("sed -n 's/S/&/p' {} > {}".format(
    pipes.quote(oldFile), pipes.quote(newFile), shell=True)
或使用管道:

with open(newFile, 'w') as pipetarget:
    out = subprocess.call(["sed", "-n", "s/S/&/p", oldFile],
                                  stdout=pipetarget)

请注意,当用作参数列表中的单独参数时,不应在
's/s/&/p'
字符串上使用引号;不将其传递给shell时,也不需要从shell解析中转义。

重定向运算符由shell解释。@Martijn和unutbu:I get:stdout参数不允许,它将被
check\u output
覆盖,stdout参数不允许在内部使用。改为使用Popen。或者使用
call()
check\u call()
。是的,也许check\u call最接近。请注意,在我的帖子中,
newFile
不是字符串。使用带有open(…)as newFile的
语句。