我有一個測試腳本迭代通過兩個字符串數組,我想使用sys.stdout.write
爲用戶提供一個簡單的「進度條」。Sys.stdout.write不按預期方式工作
我當前的腳本:
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)))
預期的輸出是sys.stdout.write
保持更新,而打印報表,通知一些動作的用戶。但是當我運行這個時,顯示的唯一時間sys.stdout.write
在腳本的末尾。例如。
[*] stop if running Serv1
[!] Passing over Serv2
[*] stop if running Serv3
[*] stop if running Serv4
[!] Passing over Serv5
[ ] 5/5 progress left
如何在更新的同時在所有打印照片下方顯示進度?
這些都是每行,在默認情況下,你不能回去寫上一行。一種方法是清除屏幕並一次又一次地寫入所有行或一些窗口API。 http://stackoverflow.com/questions/7122775/python-multiple-line-terminal-update – YOU
我有另一個腳本掃描通過任何主機IP地址的端口,它成功地打印並提供一個進度輸出在同一時間。我直接從它複製了一些部分,但在這個例子中似乎不起作用。 –