2014-01-31 28 views
0

不幸的是,我僅限於Python 2.4,並希望在腳本執行時運行ascii動畫(即旋轉的圓圈)我只是想知道常用的方法或實踐是做什麼的像這樣以及與解決方案相關的任何/所有資源,示例腳本將非常棒!我一直在使用os.sytem('command')並想要擺脫這種習慣。子流程的常見做法Python

謝謝!

+0

你有'curses'嗎?它可以讓你用終端做一些奇特的事情(儘管你應該記住,圖書館的名字不是隨機的......你學習/使用它時會說一些咒語)。 – Bakuriu

回答

3

執行此操作的一種可能方法是使用回車符「\ r」將光標返回到行的開頭,以便可以覆蓋先前寫入的字符。這允許您創建動畫,只要它適合當前行。例如:

import time 

def do_a_little_work(): 
    time.sleep(0.1) 

print "about to do work..." 

icons = ["-", "/", "|", "\\"] 
icon_idx = 0 

while True: 
    do_a_little_work() 
    #todo: check if work is done, and break out of the loop. 
    print "\r" + icons[icon_idx], 
    icon_idx = (icon_idx+1)%len(icons) 

print "\rdone." 

結果:

about to do work... 
- 

,這已經成爲

about to do work... 
/

,這已經成爲

about to do work... 
| 

,這已經成爲

about to do work... 
\ 

等等......最後成爲

about to do work... 
done. 

enter image description here


您可以使用threading與您的常規代碼同時運行動畫。

from threading import Thread 
import time 

def do_the_work(): 
    #execute your script here 

work_thread = Thread(target=do_the_work) 
print "Working..." 
work_thread.start() 

icons = ["-", "/", "|", "\\"] 
icon_idx = 0 
while work_thread.is_alive(): 
    time.sleep(0.1) 
    print "\r" + icons[icon_idx], 
    icon_idx = (icon_idx+1)%len(icons) 
print "\rdone" 
+0

感謝您的回覆,我實際上想知道是否將這個過程與我的其他腳本同時進行,而不是爲了自己動畫 – sunshinekitty

+0

您可以使用'threading'。編輯。 – Kevin