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

1586010002-jmsa.png

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.

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 .

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.

For space you can try to use recipes from this answer How to get user input during a while loop without blocking

...or use some console ui (curses, urwid, ...) or gui (tkinter, pyqt, ...) modules.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值