【发布时间】:2015-01-07 05:29:26
【问题描述】:
我有以下代码来执行命令并获取输出。
import os, sys, subprocess, string
def executeCommand(execstr):
print "cmd: " + execstr
p = subprocess.Popen(execstr, stdout=subprocess.PIPE, shell=True)
output = ""
(output, err) = p.communicate()
p_status = p.wait()
if (p_status != 0):
print "Unable to execute "+ execstr
return (string.strip(output))
cmd = "grep -R \"pattern\" sample.txt"
output = executeCommand(cmd)
print "output: " +output
这里从 p.wait() 返回的 p_status 为 1(非零) 在命令行中执行命令时成功。 sample.txt 是一个空文本文件。 来自 p.communicate 的错误是无。 上面的代码有什么问题。
【问题讨论】:
-
不相关:没有
stderr=PIPEerr是总是None。删除shell=True并使用shlex.split(execstr)。 -
那么,要得到err,从p.communicate(),stderr=subprocess.PIPE,需要添加到Popen命令中吗?
-
是的。它在文档中明确提及。
标签: python subprocess