raw_input and break

Peter Otten __peter__ at web.de
Thu Nov 5 06:38:05 EST 2015


input/ldompeling at casema.nl wrote:

>  >   choices = raw_input("letter s to stop:")
> 
> Oh no, this is not what I want. Now it is waiting for input when its go
> further with the script. Because I have an while True: so I want that the
> script go's continue only when I press a key then it must stop the script.

Solutions to that problem are OS-dependent. For Unix terminals

https://docs.python.org/2/faq/library.html#how-do-i-get-a-single-keypress-at-a-time

shows one way which I used to write the contextmanager below:

$ cat capture_key.py
import termios, fcntl, sys, os

from contextlib import contextmanager


@contextmanager
def nonblocking(stdin=None):
    if stdin is None:
        stdin = sys.stdin

    fd = sys.stdin.fileno()

    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)

    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
    def read(n):
        try:
            return stdin.read(n)
        except IOError:
            return ""
    try:
        yield read
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)


Put the capture_key.py module into the same folder as your script and use it 
like in the demo below:

from capture_key import nonblocking

# put your code here

with nonblocking() as read:
    print("letter s to stop:")
    while True:
        enable_servo()
        servo(90)
        mindist = 80
        choices = read(1)
        if choices == 's':
            print("stop")
            break
if mindist > us_dist(15):
    bwd()
    print("backward 1x")





More information about the Python-list mailing list