I'm automating a installer using pexpect
, which works nicely. However, I would like to replace the pexpect.interact()
with some sort of stdout
, which would allow me to keep track of the progress bar of the installer:
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
The source code looks like:
## 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')
so the last part is being done manually, become I can't get of the child.interact()
once the install has been completed. How could I accomplish that?
I had to do the same thing once. The problem is that things are working in line buffered mode by default. Here is how I worked around it:
Right after you create your child
(I am assuming this is a pexpect.spawn
) you can set the attribute child.logfile
to something - this doesn't have to be a logfile literally, it can be any file handle. In your case, you can set it to sys.stdout
but open this file handle in unbuffered mode.
Working example:
#!/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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.