我使用pexpect
自动化安装程序,效果很好。但是,我想用某种pexpect.interact()
替换stdout
,这样我就可以跟踪安装程序的进度条:
Please wait while Setup installs on your computer.
Installing
0% ______________ 50% ______________ 100%
#########################################
----------------------------------------------------------------------------
Setup has finished installing on your computer.
View readme file [Y/n]: n
[Errno 5] Input/output error
源代码如下:
## A bunch of informations being given to the installer above
## Do you want install? y
child.sendline('y')
## now I keep tracking of the installation bar progress ...
child.interact()
## View readme file [Y/n]: n
child.sendline('n')
所以最后一部分是手动完成的,一旦安装完成,我就无法获得child.interact()
。
我怎么能做到这一点?
答案 0 :(得分:1)
我必须做同样的事情一次。问题是默认情况下工作在行缓冲模式下。以下是我如何解决这个问题:
在您创建child
之后(我假设这是pexpect.spawn
),您可以将属性child.logfile
设置为某些内容 - 这不一定是字面意义上的日志文件,它可以是任何文件句柄。在您的情况下,您可以将其设置为sys.stdout
,但在无缓冲模式下打开此文件句柄。
工作示例:
#!/usr/bin/env python
import pexpect
import sys
import time
import os
def potato():
for i in range(20):
time.sleep(0.1)
sys.stdout.write(str(i))
sys.stdout.flush()
sys.stdout.write('bye\n')
if __name__ == '__main__':
if sys.argv[-1] == 'potato':
potato()
else:
child = pexpect.spawn(__file__ + ' potato')
child.logfile = os.fdopen(sys.stdout.fileno(), 'w', 0)
child.expect('bye')