2014-11-25 279 views
1

我正在尋找一種方法,當用戶按[空格鍵]時,暫停下面的for循環,然後再次按[空格鍵]時從最近一次迭代繼續循環。Python - 使用[空格鍵]暫停循環

目前,腳本會提示用戶輸入三個值,然後按定時間隔從文本文件中打印單詞,直到沒有剩餘單詞。

什麼是最好的方式去做這件事?非常感謝。

import time 

with open('Textfile.txt', 'r', encoding='utf8') as file: 

    data = file.read() 
    data2 = data.split() 


def reading(start, speed, chunks): 

    for i in range(start, len(data2), chunks): 

     print('\r' + (' '.join(data2[i:i+chunks])), end="") 

     time.sleep(60/speed * chunks) 

    print ("The End.") 


start = int(input('Where would you like to start? (word number) ')) 
speed = int(input('How many words per minute? ')) 
chunks = int(input('How many words at a time? ')) 

reading(start, speed, chunks) 
+0

看看[curses編程](https://docs.python.org/3/howto/curses.html)。 – eryksun 2014-11-25 17:18:09

回答

0

這裏是部分回答你的問題(關於空間的部分沒有回答,但是請閱讀到最後,有一些提示)。 我改編了這裏的答案Non-blocking read on a subprocess.PIPE in python

import time 
import sys 
from threading import Thread 
try: 
    from Queue import Queue, Empty 
except ImportError: 
    from queue import Queue, Empty # python 3.x 


def enqueue_output(output, queue): 
    for line in iter(output, b''): 
     queue.put(line) 
    out.close() 


with open('Textfile.txt', 'r', encoding='utf8') as file: 
    data = file.read() 
    data2 = data.split() 


def reading(start, speed, chunks): 
    q = Queue() 
    t = Thread(target=enqueue_output, args=(sys.stdin.readline, q)) 
    t.daemon = True # thread dies with the program 
    t.start() 

    for i in range(start, len(data2), chunks): 
     print('\r' + (' '.join(data2[i:i+chunks])), end="") 
     time.sleep(60/speed * chunks) 

     try: 
      line = q.get_nowait() # or q.get(timeout=.1) 
     except Empty: 
      pass 
     else: 
      print("Pausing") 
      while 1: 
       time.sleep(0.3) # Adjust frequency of reading user's input 
       try: 
        line = q.get_nowait() # or q.get(timeout=.1) 
       except Empty: 
        pass 
       else: 
        print("Resuming") 
        break 

    print ("The End.") 


start = int(input('Where would you like to start? (word number) ')) 
speed = int(input('How many words per minute? ')) 
chunks = int(input('How many words at a time? ')) 

reading(start, speed, chunks) 

用戶可以按下Enter按鈕暫停/繼續閱讀。 對於空間你可以嘗試使用這個答案的食譜How to get user input during a while loop without blocking

...或者使用一些控制檯ui(curses,urwid,...)或gui(tkinter,pyqt,...)模塊。