2016-10-04 16 views
0

我面對的行爲我無法理解。當終端的尺寸發生變化時,詛咒打破了time.sleep()

import curses 
import time 

myscreen = curses.initscr() 

y, x = myscreen.getmaxyx() 
i = 0 

while y >= 24 and x >= 80 and i <= 23: 
    myscreen.addstr(i, 0, 'Python curses in action!') 
    myscreen.refresh() 
    y, x = myscreen.getmaxyx() 
    i += 1 
    time.sleep(1) 

curses.endwin() 

此代碼將寫入24個字符串,間隔爲1秒,這沒關係。 但是,當我在執行過程中開始更改終端窗口的大小時,字符串將以每秒1個字符串的速度快速出現在屏幕上。 你能解釋這種行爲,並可能得到建議如何「保護」我的time.sleep()? 謝謝。

P.S.沒有詛咒睡眠()工作正常。

回答

0

time.sleep()文檔:

掛起當前線程用於 秒給定數量的執行。該參數可能是一個浮點數,用於指示更準確的睡眠時間。 實際掛起時間可能小於 ,因爲任何捕獲的信號都會在執行該信號的捕獲程序後終止睡眠() 。另外,由於系統中其他活動的調度,暫停時間可能比任意數量 所要求的更長。

0

當您調整您的終端的大小時,終端仿真器將使用它的信號(SIGWINCH)發送給輸入/輸出。在你的例子中,中斷time.sleep()

而不是使用time.sleep(),您可以使用curses函數napms()(等待給定的毫秒數)。

與您現有的程序開始,你可以看到時間的行爲更好,如果你把它打印出來(改編自Get current time in milliseconds in Python?答案):

import curses 
import time 
from datetime import datetime 
from datetime import timedelta 

start_time = datetime.now() 

# returns the elapsed seconds since the start of the program 
def elapsed(): 
    dt = datetime.now() - start_time 
    ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds/1000.0 
    return ms/1000.0 

myscreen = curses.initscr() 

y, x = myscreen.getmaxyx() 
i = 0 

while y >= 24 and x >= 80 and i <= 23: 
    myscreen.addstr(i, 0, 'Python curses in action ' + "%.3f" % elapsed()) 
    myscreen.refresh() 
    y, x = myscreen.getmaxyx() 
    i += 1 
    time.sleep(1) 

myscreen.getch() 
curses.endwin() 

詛咒已經像睡眠的功能,但在毫秒napms。使用它,您將獲得更加一致的行爲,因爲ncurses根據需要處理SIGWINCH,restartingnapms以獲得請求的時間延遲。當我改變time.sleep(1)

curses.napms(1000) 

程序繼續「睡眠」一秒,而終端被調整大小。