【问题标题】:Pause an infinite while loop with a single keypress用一个按键暂停无限循环
【发布时间】:2012-06-29 19:51:45
【问题描述】:

我是 python 新手,我一直在尝试找到一种简单的方法来暂停正在运行的 while 循环,从而可以从暂停的位置重新启动它。我在谷歌上搜索了帮助和提示,但我发现的一切似乎都非常复杂。有没有简单的方法可以做到这一点?

我了解到您可以使用 termios 和 tkinter。

我正在使用 ubuntu。

抱歉,语言错误

谢谢!

【问题讨论】:

标签: python loops ubuntu while-loop infinite


【解决方案1】:

这是一个在无限循环中运行的简单 tkinter 程序。按 space 暂停/取消暂停,按 Esc 退出。

注意:以下内容适用于 Python 2.x,如果您使用的是 Python 3,请将第一行中的 Tkinter 更改为 tkinter(小写 t)。

from Tkinter import *
import time

class MyLoop():
    def __init__(self, root):
        self.running = True
        self.aboutToQuit = False
        self.root = root
        self.someVar = 0
        self.root.bind("<space>", self.switch)
        self.root.bind("<Escape>", self.exit) 

        while not self.aboutToQuit:
            self.root.update() # always process new events

            if self.running:
                # do stuff
                self.someVar += 1
                print(self.someVar)
                time.sleep(.1)

            else: # If paused, don't do anything
                time.sleep(.1)

    def switch(self, event):
        print(['Unpausing','Pausing'][self.running])
        self.running = not(self.running)

    def exit(self, event):
        self.aboutToQuit = True
        self.root.destroy()

if __name__ == "__main__":
    root = Tk()
    root.withdraw() # don't show the tkinter window
    MyLoop(root)
    root.mainloop()

这是一个可能的输出,我在退出之前手动暂停和取消暂停了两次程序。

1
2
3
4
5
6
7
Pausing
Unpausing
8
9
10
11
12
13
14
15
16
Pausing
Unpausing
17
18
19
20
21
22
23
24
25

【讨论】:

  • 非常感谢,这正是我想要的! :)
【解决方案2】:

不要讨论如何使用单个按键来执行此操作,而是要恢复和暂停 while 循环,您可以使用 generator functions,请参见下面的示例:

i=-1
def infi():
   global i
   while i<99999999:
       i+=1
       yield i

a=iter(infi())

for x in range(6):
    print(next(a))
#loop paused at 5     
print('now it wil start from start 6')

for x in range(11):
    print(next(a))

输出:

0
1
2
3
4
5
now it wil start from start 6
6
7
8
9
10
11
12
13
14
15
16

【讨论】:

  • 好的,谢谢!问题是我希望能够在它循环的任何给定时间暂停它。
  • @user1488138 这就是generator function 所做的,他们可以暂停执行并可以从离开的地方开始执行。
  • @Ashwini:这似乎根本不符合 OP 的要求。用户如何暂停进程?
  • 好的,抱歉我的愚蠢问题^^是否可以使用类似的功能制作它,以便我可以在它实际运行时随机暂停它?如果没有特定的位置,它应该暂停和恢复吗?
【解决方案3】:

老兄,这是一个while循环...不要在while循环中运行它,这会阻塞CPU,只需尝试使用计时器...

这是一个 python 3 示例,用于从未显示的窗口中获取输入,在 OSX、Linux Ubuntu 和 Windows 8 上进行了测试

import tkinter as tk
import time

class App():
    def __init__(self):
        self.state = 'running'
        self.cnt = 0
        self.root = tk.Tk()
        self.update_clock()
        self.root.bind("<Key>", self.key)
        self.root.geometry('1x1+9000+9000')
        self.root.mainloop()

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.root.after(100, self.update_clock)
        self.root.focus_set()
        if(self.state == 'running'):
            self.cnt = self.cnt + 1
        if(self.cnt <= 100):
            print('state: ',self.state,' count:',self.cnt,'%')
        else:
            exit()

    def key(self,event):
        self.root.focus_force()
        if(event.keysym == 'Escape'):
            self.state = 'paused'
        elif(event.keysym == 'space'):
            self.state = 'running'
        print("pressed", repr(event.keysym))
        print("state",self.state)
app=App()
app.mainloop()

您可以为此感谢@saranyan...

【讨论】:

  • 哦,顺便说一句,您可能应该在 update_clock 方法中使用 self.root.focus_set(),并将数字或数据保存为 init 中声明的另一个 var,但仅更新if(self.state == 'paused'):
【解决方案4】:

我一直在寻找这个解决方案,但结果非常简单。我很高兴选择模块仅适用于 Unix 系统,但它使事情变得非常简单。

import sys
import select
inputSrc = [sys.stdin]

while True:

    # Do important stuff

    # Check if a key was pressed and if so, process input
    keypress = select.select(inputSrc, [], [], 0)[0]
    while keypress:
        for src in keypress:
            line = src.readline()
            if not line:
                inputSrc.remove(src)
            else:
                # The "enter" key prints out a menu
                if line == "\n":
                    print "Test Paused\nOptions: [0]: Quit  [any other key]: Resume"
                elif line.rstrip() == "0":
                    exit(0)
                elif len(line) >= 1: #any other key
                    print "Resuming..."
                    keypress = None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2021-05-26
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多