【问题标题】:Python pause loop on user input用户输入的Python暂停循环
【发布时间】:2019-06-30 01:35:38
【问题描述】:

嘿,我正在尝试让用户输入暂停循环,就像在终端中有一个输入框,如果你输入 pause 它会暂停循环,然后如果你输入 start 它会重新开始。

类似这样的事情,但在不等待输入发送的情况下不断发生“#Do something”。

while True:
    #Do something
    pause = input('Pause or play:')
    if pause == 'Pause':
        #Paused

【问题讨论】:

  • 你打算如何打断“暂停”?
  • 我强烈怀疑你没有清楚地解释你想要完成的事情。无论如何,这是一个猜测,请参阅Non-Blocking raw_input() in python
  • @DavidZemens 你是对的,你不能在同一个线程中这样做!所以我创建了两个,一个用于循环,另一个用于中断
  • @martineau 这将是另一个很棒的方法!感谢分享

标签: python loops


【解决方案1】:

好的,我现在明白了,这是一个使用 Threads 的解决方案:

from threading import Thread
import time
paused = "play"
def loop():
  global paused
  while not (paused == "pause"):
    print("do some")
    time.sleep(3)

def interrupt():
  global paused
  paused = input('pause or play:')


if __name__ == "__main__":
  thread2 = Thread(target = interrupt, args = [])
  thread = Thread(target = loop, args = [])
  thread.start()
  thread2.start()

【讨论】:

    【解决方案2】:

    您不能直接使用,因为 input 会阻止所有内容,直到它返回为止。
    不过,_thread 模块可以帮助您:

    import _thread
    
    def input_thread(checker):
        while True:
            text = input()
            if text == 'Pause':
                checker.append(True)
                break
            else:
                print('Unknown input: "{}"'.format(text))
    
    def do_stuff():
        checker = []
        _thread.start_new_thread(input_thread, (checker,))
        counter = 0
        while not checker:
            counter += 1
        return counter
    
    print(do_stuff())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 2016-02-15
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      相关资源
      最近更新 更多