简体   繁体   English

Sys.stdout.write无法正常工作

[英]Sys.stdout.write not working as expected

I've got a test script that iterates through two string arrays, and I want to use sys.stdout.write to provide the user a simple 'progress bar'. 我有一个遍历两个字符串数组的测试脚本,并且我想使用sys.stdout.write为用户提供一个简单的“进度条”。

My current script: 我当前的脚本:

import sys
from time import sleep
names  = ['Serv1', 'Serv2', 'Serv3', 'Serv4', 'Serv5']
states = ['Running', 'Stopped', 'Running', 'Running', 'Stopped']
terminated=0
passed=0
for i 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 over {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 is for the sys.stdout.write to keep updating, whilst the print statements are informing the user of some action. 预期的输出是为了使sys.stdout.write保持更新,而print语句则将某些操作通知用户。 But when I run this, the only time sys.stdout.write is shown is at the end of the script. 但是,当我运行此命令时,唯一显示sys.stdout.write的时间是在脚本末尾。 Eg 例如

 [*] stop if running Serv1
 [!] Passing over Serv2
 [*] stop if running Serv3
 [*] stop if running Serv4
 [!] Passing over Serv5
 [ ] 5/5 progress left

How can I get the progress left to be shown below all of the prints whilst updating? 更新时,如何使进度显示在所有打印下方?

You'll need to flush the buffer; 您需要刷新缓冲区; all output is buffered; 所有输出都已缓冲; kept in memory until a certain amount of data has been collected, to improve write performance. 保留在内存中,直到收集到一定数量的数据为止,以提高写入性能。

The print statement flushes that buffer for you, but when writing to stdout directly, you need to explicitly flush: print语句为您刷新该缓冲区,但是当直接写入stdout ,您需要显式刷新:

sys.stdout.write(" [ ] {0}/{1} progress left\r".format(i+1, len(names)))
sys.stdout.flush()

Next, you are writing to stdout after sleeping ; 接下来,您正在睡觉后写到stdout the very next thing you do is replace that line with the next print statement. 接下来要做的就是用下一个print语句替换该行。 Write the message before sleeping: 睡觉写信息:

for i 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 over {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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM