2011-09-22 73 views
1

我知道这已被回答了很多次,但我还没有找到一种工作方式来做到这一点在我的情况下......我希望你会帮助。 我想要从stdout和/或stderr实时地将Popen调用的数据输出到套接字连接,而不是标准输出。所以sys.stdout.flush()不适合我。 顺序发送标准输出从subprocess.Popen通过套接字

data=sok.recv(512) #the command to execute 
p = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE stderr=subprocess.PIPE) 

#this work.. but not how i spected, if the subprocess ends too fast, i only get the first line 
while p.poll() is None: 
    sok.send(p.stdout.readline()) 

#this only send the last line 
for i in p.stdout.readline(): 
    sok.send(i) 
    sys.stdout.flush() #why sys.stdout? i don't use it 
    p.stdout.flush() #same result 

+0

你打电话'Popen'用'壳= TRUE'数据你从网络连接中获得?你知道你是用这种方式创建一个shell服务器,不是吗? –

+0

是的,我知道,但那不是重点。事实上,这正是我想要做的,为了好玩。 –

回答

3

p.poll()指示进程是否正在执行。所以一旦程序退出,它就会返回false。所以这不是你应该检查的。

代码:

for i in p.stdout.readline(): 

读了该行的每个字母一行,然后遍历。不是你想要的。使用:

for i in p.stdout.readlines(): 

这将返回每一行。

但是在生成任何行之前,它会读取整个文件,可能不是您想要的。

所以使用:

for line in p.stdout: 

这应该给你的每一行,一行行,直到有没有更多的阅读