How to suspend a command without disturbing active commands

Asked

Viewed 192 times

2

well I wanted to know if you know a command in python that suspends the operation of a command (for a few seconds)without disturbing the other commands that are active, because it was wanting to make a rental system but the team.Leep() did not let the other commands work. here an example:

import time
aluguel=False
dinheiro=0
while True:
    time.sleep(10)
    aluguel=True
    dinheiro=dinheiro-1
    #o time.sleep inpede o funcionamento do codigo a seguir mas n quero que isso aconteça
a=str(input(''))
if a == MONEY:
    dinheiro=dinheiro+1'
  • I made a change explaining better

  • 1

    What exactly this code should do? Can you explain it with words?

  • from seconds to seconds the program will charge the rent and you will have to make money not to be evicted, I tried to use the team.Leep() but it for the entire program, I just want to make a count that does not interfere in anything

  • Have knowledge about Threads?

  • I’m not really a beginner;--;

  • What does that mean MONEY ? What good is he?

  • I made the code without testing to give as an example. _. I forgot to put the quotes, this and the code to make money

  • In my humble knowledge, I see solutions using threads or asy. Both are relatively complex for those who are starting out. Why do you need to do this?

  • Why I want to ._.

  • 1

    So start reading about parallelism and competition. Without understanding the concepts, in my view, it will not do to have an answer with a code that works. Study what they are threads, processes, how they are managed by the processor, how to work with competition issues, etc.

  • This looks very much like a XY problem.

Show 6 more comments

1 answer

1

So - "normal" programs, at this level of learning always run with one instruction after another.

If you want one part of your code to do one thing, while another part of your code does another, you need to have "something" that controls which part of the program will be executed, and how the processing will move to another part while the first is "paused".

The first thing that comes to everyone’s head when you mention this is the concept of "threads". A "thread" is like a separate program, running in the same code, and in the same variables. You could have a thread running code from one function, while another thread runs code in another function. In this case the time.sleep would have the effect you expect on the question: that thread to,.

However threads are far from being didactic: one has to really be aware of the program flow and several other things to make something with direct threads work.

In your code, we can see that you don’t use functions. If you have not mastered the use of functions to the point of being something trivial, there is no alternative - why even to think about this "pause" is complicated. Where does the program "go" if part of the code is "paused". Where does it "come back"? In addition to all that is described for them, functions serve as units of code organization to "know" which part is running. (To create a thread, for example, you pass a function as a parameter, as the starting point of the "secondary program" of that thread).

So go, and learn about functions, within of a function are "watertight" - are not visible or alterable outside the function, and how you can have "global" variables that are shared.

After that you will be able to think in an organized way in parts of the code that run in parallel.

That is why I am writing this answer. As I put it above, there has to be "something" that manages which part of your code is running in parallel. But this thing doesn’t necessarily have to be its own code controlling threads. The library for graphical interfaces that comes with Python - Tkinter, can do this very well, taking care of all the complexity for you.

When you use a graphical library, in general your program declares all functions, classes and objects you will use, and transfers control of the program to the library. In the case of Tkinter, you call the function mainloop, and this is typically the last line of your program. From there, the control passes to the graphical library, which will call functions and methods of the your code, which you configured in the lines above. For example, it can call a function that changes the global vailable "balance", when the user clicks a button, or after spending a certain time interval, for example.

The process would be the same with other graphic libraries, like gtk+ and Qt - what they have in common is that they manage the "what code runs when" part, which for users is "common" since we’ve grown up with applications that have menus ready to use, or web forms. And more importantly: always, always organize your code in functions, first of all!

Here follows an example that looks like what you were trying, using the "Tkinter framework":

import tkinter


def adiciona(*args):
    saldo.set(saldo.get()  + int(valor.get()))
    mostra_saldo()

def mostra_saldo(*args):
    mensagem["text"] = ("Saldo atual: {}".format(saldo.get()))

def cobra_aluguel():
    saldo.set(int(saldo.get()) - 1)
    mostra_saldo()
    janela.after(2000, cobra_aluguel)

def constroi():
    # Essas variáveis globais estarão visíveis em todas as funções.
    global janela, mensagem, saldo, valor
    # como as outras funções não modificam as mesmas com o sinal de "=",
    # apenas chamando métodos, não precisam declara-las como globais também. 

    janela = tkinter.Tk()
    valor = tkinter.Variable()
    saldo = tkinter.Variable()
    mensagem = tkinter.Label(janela)
    texto = tkinter.Label(janela, text="Valor a receber:")
    entrada = tkinter.Entry(janela, textvariable=valor)
    # O parametro "command" indica a função chamada quando o botão 
    # for clicado:
    botao = tkinter.Button(janela, text="Adicionar", command=adiciona)

    # métodos para exibir controles na janela, da forma mais simples:
    # um abaixo do outro:
    mensagem.pack()
    texto.pack()
    entrada.pack()
    botao.pack()
    # Exbibe o saldo inicial
    saldo.set(0)
    mostra_saldo()
    # Cobra aluguel daqui 2000 milisegundos: 
    janela.after(2000, cobra_aluguel)

    # Transfere o controle do programa para o tkinter,
    # que vai chamar "cobra_aluguel" no intervalo de tempo 
    # e "adiciona"  quando o botao for pressionado
    tkinter.mainloop()

constroi()

Browser other questions tagged

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