A solution to break/continue a Python loop?

Asked

Viewed 1,859 times

-1

The point is, I can’t find a solution that replaces using the console for my small application.

What happens is: My app runs in eternal loop, but after it runs the loop, it should stop to ask if I want to stop the loop or continue. So far nothing impossible. However, I want it to continue the loop if I do nothing. For example:

  1. I open the program.
  2. The program executes the first loop.
  3. A message appears: "Press any key to stop or wait 4 seconds."

From that moment there are two possibilities.

  1. I press any key and the program closes.
  2. I don’t squeeze anything and the program continues.

I have already thought of some things, such as using two threads one to read the keys (if any) and another to count the 4 seconds, but I could not. So I come to ask if anyone knows a solution to this problem.

import pyautogui
import sys, time, msvcrt, random, time, os

# obs: Minha resolução de tela é 1366 x 768. Talvez será necessário adaptar as coordenadas
#      dos cliques automatizados para sua tela. 

def jogar():
    time.sleep(0.5)
    pyautogui.click(670, 330)
    time.sleep(0.5)
    cartaEscolhida = random.randint(1,5) # Escolhe uma carta aleatória.
    if cartaEscolhida == 1: 
        pyautogui.click(670, 330)
    elif cartaEscolhida == 2:
        pyautogui.click(717, 350)
    elif cartaEscolhida == 3:
        pyautogui.click(771, 351)
    elif cartaEscolhida == 4:
        pyautogui.click(815, 357)
    else:
        pyautogui.click(863, 350) 
    time.sleep(7.5)
    pyautogui.click(760, 410)

def abrirJogo():                # Dá os cliques para abrir a extensão e o jogo de cartas.
    pyautogui.click(891, 537)
    time.sleep(1)
    pyautogui.click(694, 386)

def fecharJogo():               # Dá os cliques para fechar a extensão.
    time.sleep(0.5)
    pyautogui.click(880, 531)

def mudarAba():                 # Para mudar da aba do console para a aba do navegador.
    pyautogui.keyDown('alt',)
    pyautogui.press('tab')
    pyautogui.keyUp('alt')

def pararPrograma():
    timeout = 4
    startTime = time.time()
    inp = None
    print("Aperte qualquer tecla para continuar ou aguarde 4 segundos.")
    while True:
        if msvcrt.kbhit():
            inp = msvcrt.getch()
            break
        elif time.time() - startTime > timeout:
            break
    if inp:
        sys.exit()
    else: 
       parar = False

clear = lambda: os.system('cls')  # Para limpar o console. 

# Daqui pra frente é o programa funcionando. 

print("Abra o canal na twitch e deixe em modo teatro. O programa iniciará em 10 segundos.")
time.sleep(10)
parar = False
while parar == False:
     abrirJogo()
     jogar()
     fecharJogo()
     mudarAba()
     clear()
     pararPrograma()     
     mudarAba()

I also put the source code on the website Pastebin.com and recorded a video running it.

Note: The current source code works, however I want to solve this problem because I want to use a graphical interface.

To simplify a little more the problem I did it:

from threading import Thread
import time, sys

def pergunta():
    print("Aperte qualquer tecla para parar ou aguarde 4 segundos.")
    input()

def contar():
    timeout = 4
    startTime = time.time()
    while True:
        if time.time() - startTime > timeout:
            print("Continuando")
            break

ThreadA = Thread(target=pergunta)
ThreadB = Thread(target=contar)

ThreadA.start()
ThreadB.start()

Now the problem changes. The input does not end after the 4 seconds. And I cannot call these threads again.

  • Well, basically you’re going to use the Break command, and maybe Continue/Pass or Timer...

  • Yes. I used the team to count from 1-4 (stopProgram). And so did the break. However I can’t do this count/read a key. And if a key is pressed before the count ends, the program stops.

1 answer

2

Good guys. It’s 4:31 in the morning and I solved. = D I’ll post on Google drive since they are almost identical codes.

The solution was I put the thread(deletes one) inside a while with a for. That way every time the thread finishes it will go back to while that will repeat the thread.

And the input I left as something normal. However now, Once 4 seconds pass and nothing is pressed, the program will type "continue" and continue the loop.

Obs: v3 is where the solution is.

The link

  • 1

    it would be nice to put at least the relevant code part here, links may cease to exist, or other users may not even have access

Browser other questions tagged

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