我将java程序作为子进程运行,但当我将stderr重定向到管道时,程序将挂起。例如,myProcess = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
工作,但myProcess = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr=subprocess.PIPE)
挂起。
我运行的命令大致如下:
java -DSomeVals -classpath <somevals> package.Name
Stderr生成了大量的输出,我记得在某个地方读到,如果shell=True,可能会导致死锁。不幸的是,当我将shell设置为False时,我收到一条错误消息,说文件名太长。
我尝试了myProcess = subprocess.Popen(['java', args], shell=False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
,但java抱怨找不到我要运行的类。
我想通过管道发送stderr,因为它扰乱了我程序的输出。
我认为您只需要从管道中读取即可。管道缓冲区正在填充并阻塞进程。看看这个重复"HelloWorld"50000次的例子。
import subprocess
import os
def getLinesFromShellCommand(command):
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.getcwd())
lines = []
for curLine in p.stdout.readlines():
lines.append(curLine)
p.wait()
return lines
print "Starting..."
lines = getLinesFromShellCommand("printf 'HelloWorldn%.0s' {1..50000}")
for curLine in lines:
print curLine,