Cancel button on a timer

Asked

Viewed 273 times

2

Hello, I was doing a timer that went up to 100 and then to, and then I had the brilliant idea to put a cancel button on the count. I did some things only that when he says "To cancel type "c"" the timer does not continue until I give some reply.

You have to keep the timer going instead of waiting for an answer ?

import time
porcentagem = 1
vitima = input('Quem deseja hackear?')


def main():
    while True:
        time.sleep(1)
        global porcentagem
        porcentagem = porcentagem + 1
        if porcentagem < 100:
            global hackeando, vitima
            hackeando = 'a'
            hackeando = input('Hackeando {}, {} %, Para cancelar digite "c"'.format(vitima,porcentagem))
            main()
        elif porcentagem == 100:
            print('Hackeado com sucesso')
        elif hackeando == 'c':
            break


main()

1 answer

3


Tem como fazer o timer continuar - "Having how, has". Only this ceases to be a simple program like what you are doing, and above all, violates the expected way of running programs through the terminal.

Trying to explain better: when you are making a program that only communicates with the user with print and input (or even using other functions, but mostly using the terminal ("cmd" in windows)) - the rule is that for the program, everything it will "receive" from the user (with the "input" function) is indistinguishable to the program from a text file that it will read line by line. Only the operating system will only actually pass to the program (whether it uses the input, whether it is reading the "terminal file" in some other way) one whole line at a time - and one line is only considered when the user presses "enter". So - both the input, and the reading of the file otherwise, can only read, or know if the user typed anything, when he presses enter. This "input file" can be configured differently, but not only is it much more advanced than programs that use print and input, in this faase of learning, as the behavior of the program becomes strange for users accustomed to programs in the terminal.

In general, who uses programs on the terminal - even advanced programs used by developers, such as the git, nay respond to keys without stopping the execution and stay waiting for the user. The interruption of the program is done by the combination of keys ctrl + C.

How to Create a Program with Greater User Interaction

If you want to evolve the interaction with the user, the ideal is to start learning to create programs that or create a graphic window, using for example, the Tkinter, or web applications, using a framework such as Flask.

It is worth more than trying to change the behavior of a terminal program before having a good programming domain.

A more sophisticated terminal program can use the library curses for example, but it’s also another level of programming - it can take more work than simple graphical applications using Tkinter, and be much stranger to the end user.

But I really wanted to do it at the terminal, just this one

There is a simpler way than reconfiguring the terminal to detect single keys, but that involves a shift to another programming paradigm. (Web or graphical applications will involve a similar change anyway). In this case, you would have to change your program to use two "threads" in parallel. A "Thread" is basically this: your program "splits" and runs in parallel - Python will effectively, from the developer’s point of view, be running two or more lines at the same time. so while one thread may be stopped waiting for the "input" result, the other may continue with the timer.

Creating threads is easy - harder in this case is controlling the terminal output if you were printing the countdown. "Real" programs using threads can be quite complex, because of data that are changed in one thread and modify the behavior of the program in another (so much so that there is a tendency not to use threads, there are several years).

Finally, if we just put the "input" on a separate thread, the timer can continue running on the main thread - and at each step you see if the user ordered the program to stop.

In this simple program, at the end of the count, the program ends - as the input will be running, the program will stand still waiting for the user to press <enter> anyway. There is no way to force the stop of a thread that is waiting for a input - then this approach would not work in any more complex program.

import time
from threading import Thread

porcentagem = 0
vitima = input('Quem deseja hackear?')


def verifica_parada():
    global parada
    while True:
        entrada = input("Pressione 'c' e <enter> para cancelar")
        if entrada == 'c':
            parada = True
        return

def main():
    global porcentagem
    thread_de_parada = Thread(target=verifica_parada)
    thread_de_parada.start()
    while True:
        time.sleep(1)
        porcentagem +=  1
        if parada:
            print("Programa cancelado pelo usuário")
            return
        if porcentagem < 100:
            print (f'Hackeando {vitima}, {porcentagem}%, Para cancelar digite "c" e <enter>')
        elif porcentagem == 100:
            print('Hackeado com sucesso')

parada = False
main()

I’ve made some other improvements to the program that may contribute to your learning - global is only necessary for the variables you will change in the function, and should always come at the beginning of the function.

Another thing is that you were calling the "main" function recursively from within itself - there is no need for that in this case - the command while already repeats the main block of the program within main.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.