首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

[]Python管道即时读取输出有关问题

2013-07-08 
[求助]Python管道即时读取输出问题import subprocess, timepipe subprocess.Popen(myapp.exe file.ext

[求助]Python管道即时读取输出问题


import subprocess, time

pipe = subprocess.Popen('myapp.exe file.ext', stdout=subprocess.PIPE)
while 1:
    pipe.stdout.readline()
    time.sleep(0.2)


在myapp.exe执行过程中会产生许多Log,我是想能够即时地把Log取出来显示在界面上。
但是发现read(), readlines(), communicate()都是会等待myapp.exe执行完毕,再读取所有输出,达不到“即时”的效果。
现在是用了一个等待循环,每0.2秒用readline()来读取一行显示在界面。
请问有没有更好的方法?更智能点的
[解决办法]
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

好似有个interactive()函数吧

没找到,在哪?怎么用?

大概我记乱了,用pexpect模块更简单一些,但是目前pexpect只能在linux上安装
下面是个例子
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before   # Print the result of the ls command.
child.interact()     # Give control of the child to the user.


这个是expect交互,好像跟我的问题无关呢……


pexpect比subprocess更好用一些,你如果能把subprocess换成pexpect.spawn就行
解决你的问题可以使用select和非堵塞io,(pexpect和telnetlib内部大概也都是这样做的)

热点排行