python - Sys.stdout.write not working as expected -
i've got test script iterates through 2 string arrays, , want use sys.stdout.write
provide user simple 'progress bar'.
my current script:
import sys time import sleep names = ['serv1', 'serv2', 'serv3', 'serv4', 'serv5'] states = ['running', 'stopped', 'running', 'running', 'stopped'] terminated=0 passed=0 in range (0, len(names)): if 'running' in states[i]: print " [*] stop if running {0} ".format(str(names[i])) #service_info(action, machine, names[i]) terminated+=1 else: print " [!] passing on {0} ".format(str(names[i])) passed+=1 sleep(2) sys.stdout.write(" [ ] {0}/{1} progress left\r".format(i+1, len(names)))
the expected output sys.stdout.write
keep updating, whilst print statements informing user of action. when run this, time sys.stdout.write
shown @ end of script. e.g.
[*] stop if running serv1 [!] passing on serv2 [*] stop if running serv3 [*] stop if running serv4 [!] passing on serv5 [ ] 5/5 progress left
how can progress left shown below of prints whilst updating?
you'll need flush buffer; output buffered; kept in memory until amount of data has been collected, improve write performance.
the print
statement flushes buffer you, when writing stdout
directly, need explicitly flush:
sys.stdout.write(" [ ] {0}/{1} progress left\r".format(i+1, len(names))) sys.stdout.flush()
next, writing stdout
after sleeping; next thing replace line next print
statement. write message before sleeping:
for in range (0, len(names)): if 'running' in states[i]: print " [*] stop if running {0} ".format(str(names[i])) #service_info(action, machine, names[i]) terminated+=1 else: print " [!] passing on {0} ".format(str(names[i])) passed+=1 sys.stdout.write(" [ ] {0}/{1} progress left\r".format(i+1, len(names))) sys.stdout.flush() sleep(2)