简体   繁体   English

Python-使用[空格键]暂停循环

[英]Python - using [spacebar] to pause for loop

I am looking for a way to pause the for loop below when the user presses [spacebar] and then continue the loop from the most recent iteration when [spacebar] is pressed again. 我正在寻找一种方法,当用户按下[空格键]时暂停下面的for循环,然后在再次按下[空格键]时从最近的迭代继续循环。

Currently, the script prompts the user for three values and then prints words from a text file at timed intervals until there are no words remaining. 当前,脚本会提示用户输入三个值,然后以一定的时间间隔打印文本文件中的单词,直到没有剩余的单词为止。

What would be the best way to go about this? 最好的方法是什么? Thanks very much. 非常感谢。

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)

Here is partial answer to you question (part about space is not answered, however please read to the end, there are some hints). 这是对您问题的部分答案(关于空间的部分内容未得到回答,但是请仔细阅读,有一些提示)。 I adapted answer from here Non-blocking read on a subprocess.PIPE in python . 我从这里改编了答案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)

With this user will be able to pause/resume reading with pressing Enter button. 使用此用户将可以通过按Enter按钮暂停/恢复阅读。 For space you can try to use recipes from this answer How to get user input during a while loop without blocking 对于空间,您可以尝试使用此答案中的配方如何在while循环中获取用户输入而不会阻塞

...or use some console ui (curses, urwid, ...) or gui (tkinter, pyqt, ...) modules. ...或使用一些控制台ui(curses,urwid等)或gui(tkinter,pyqt等)模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM