p = Popen(cmd, bufsize=1024,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.stdin.close()
print p.stdout.read() #This will print the standard output from the spawned process
print p.stderr.read() #This is what you need, error output <-----
したがって、基本的にエラー出力はstderr
パイプにリダイレクトされます。
もっとリアルタイムで何かが必要な場合。つまり、生成されたプロセスがstdout or
stderr`に何かを出力するとすぐに印刷される行は、次のように実行できます。
def print_pipe(type_pipe,pipe):
for line in iter(pipe.readline, ''):
print "[%s] %s"%(type_pipe,line),
p = Popen(cmd, bufsize=1024,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
t1 = Thread(target=print_pipe, args=("stdout",p.stdout,))
t1.start()
t2 = Thread(target=print_pipe, args=("stderr",p.stderr,))
t2.start()
#optionally you can join the threads to wait till p is done. This is avoidable but it
# really depends on the application.
t1.join()
t2.join()
stdout
この場合、行がまたはに書き込まれるたびに2つのスレッドが出力されますstderr
。このパラメータは、行が印刷されるときに区別して、行がまたはtype_pipe
から来ているかどうかを認識します。stderr
stdout