![](/img/trans.png)
[英]pressing “spacebar” to stop a pause a loop, press again to resume loop (see UPDATE)
[英]Python - using [spacebar] to pause for loop
我正在尋找一種方法,當用戶按下[空格鍵]時暫停下面的for循環,然后在再次按下[空格鍵]時從最近的迭代繼續循環。
當前,腳本會提示用戶輸入三個值,然后以一定的時間間隔打印文本文件中的單詞,直到沒有剩余的單詞為止。
最好的方法是什么? 非常感謝。
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)
這是對您問題的部分答案(關於空間的部分內容未得到回答,但是請仔細閱讀,有一些提示)。 我從這里改編了答案python的subprocess.PIPE上的非阻塞讀取 。
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按鈕暫停/恢復閱讀。 對於空間,您可以嘗試使用此答案中的配方如何在while循環中獲取用戶輸入而不會阻塞
...或使用一些控制台ui(curses,urwid等)或gui(tkinter,pyqt等)模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.