Python - 无限循环,打破用户输入

Teh*_*Guy 6 python user-input while-loop

我有一个无限的while循环,我想在用户按下一个键时突破.通常我raw_input用来获取用户的回复; 但是,我不需要raw_input等待回应.我想要这样的东西:

print 'Press enter to continue.'
while True:
    # Do stuff
    #
    # User pressed enter, break out of loop
Run Code Online (Sandbox Code Playgroud)

这应该是一个简单的,但我似乎无法弄明白.我倾向于使用线程的解决方案,但我宁愿不必这样做.我怎么能做到这一点?

mic*_*ses 8

您可以使用stdin的非阻塞读取:

import sys
import os
import fcntl
import time

fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
while True:
    print("Waiting for user input")
    try:
        stdin = sys.stdin.read()
        if "\n" in stdin or "\r" in stdin:
            break
    except IOError:
        pass
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)


oct*_*ref 6

我认为你可以用 msvcrt 做得更好:

import msvcrt, time
i = 0
while True:
    i = i + 1
    if msvcrt.kbhit():
        if msvcrt.getwche() == '\r':
            break
    time.sleep(0.1)
print(i)
Run Code Online (Sandbox Code Playgroud)

可悲的是,仍然是特定于 Windows 的。


gtc*_*der 5

在 python 3.5 上,您可以使用以下代码。它可以针对特定的击键进行调整。while 循环将一直运行,直到用户按下某个键。

import time
import threading

# set global variable flag
flag = 1

def normal():
    global flag
    while flag==1:
        print('normal stuff')
        time.sleep(2)
        if flag==False:
            print('The while loop is now closing')


def get_input():
    global flag
    keystrk=input('Press a key \n')
    # thread doesn't continue until key is pressed
    print('You pressed: ', keystrk)
    flag=False
    print('flag is now:', flag)

n=threading.Thread(target=normal)
i=threading.Thread(target=get_input)
n.start()
i.start()
Run Code Online (Sandbox Code Playgroud)