[英]Error calling subprocess on python when redirecting stdout
我试图过滤由python脚本中的函数生成的文件:
out = subprocess.check_output(["sed","-n","'s/pattern/&/p'",oldFile,">",newFile])
但是,我收到有关命令的Followong错误:
returned non-zero exit status 1
怎么了?
如devnull所述, >
由外壳程序解释。 由于最好避免使用shell=True
,请改用stdout
参数:
import subprocess
with open(newFile, 'w') as newFile:
subprocess.check_call(
["sed", "-n", "s/S/&/p", oldFile], stdout=newFile)
您正在使用>
重定向,这需要外壳程序来解释语法。
当您重定向sed
的输出时,这里没有必要使用check_output
。 请改用subprocess.call()
或subprocess.check_call()
并验证返回码。
通过外壳运行命令:
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解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.