How to generate condition of interruption of a repetition loop in Python during its execution?

0

I'm trying to make a program in Python that while executing a loop loop, some command is waiting for an input condition while the loop is executed.

For example, a program that prints on the screen numbers, in ascending order and every 1 second, from zero while waiting for the user to enter a string "quits". When this string is read, the loop is interrupted and stops printing the numbers on the screen.

I tried to do this, but it did not work:

#-*- coding: utf-8 -*-

import time

i = 0
mensagem = 0
while mensagem!='terminar':
    mensagem = str(raw_input())
    if mensagem=='terminar':
        print "encerrado"
    else:
        print i
        time.sleep(1)
        i+=1
    
asked by anonymous 26.07.2018 / 18:29

1 answer

1

Your problem is that the function raw_input() "block" - that is - it is waiting for user input and does not return until that input arrives. The program there! time.sleep() also only returns when time passes.

To get around this, one of the ways is to check before calling raw_input() if there is data to be read. In python we can use the select module. He waits, for a certain amount of time in seconds, to see if he has data available for reading. If they have data, it returns immediately, otherwise it only returns at the specified time.

import sys import select

i = 0

while True:
    print i
    pode_ler = select.select([sys.stdin,],[],[], 1)[0]
    if pode_ler and raw_input().strip().lower() == 'terminar':
        break
    i+=1

Note that this only works on linux. In windows, select only works with sockets, so a simple solution like this is not possible - it would be necessary to use a thread forwarding data to a "selectable" socket.

But serious programs that read data from stdin while doing something else on windows are rare, so that's not very important. If you need to read data while displaying something else, I suggest you start graphing your program by using a visual programming library such as tkinter - in this case your program will respond to events such as the click of a button to end. p>     

26.07.2018 / 18:47