1

I'm very new to python and I have following problem. I'm trying to divide a variable (counta) by 3 and get the result every 10 seconds. At the same time I want to add 1 to the counter every time I press 'a'. The problem is that I'm using a method where I can only add 1 every 10 seconds. Please can you advise what could be changed so that I could add 1 whenever I like and i still get the current result (counta/3). Thank you in advance for your help. This is my code so far:

from pynput.keyboard import Listener
import sched, time 




counta = 0
Timer = 0




def on_press(key):


    if key.char == 'a':
        #print("")
        global counta
        counta += 1
        #print("Aktuell" + str(counta))

    elif key.char == 'p':
        print(int(counta/3))

    elif key.char == 's':
        Stand(counta, Timer)


    else:
        print("Falsche Taste!")
        print("a = counta")


def Stand(counta, Timer):
    while Timer < 10: 
        print(str(counta/3))
        time.sleep(1)
        Timer += 1




with Listener(on_press=on_press) as listener:
    listener.join()
2
  • You need to read up on the Threading package. It allows you to execute a function in a thread in parallel with other functions. Commented Sep 18, 2019 at 10:17
  • you have to use Listener in differen way. Create listener = Listener(on_press=on_press) before while loop, and use listener.join() after while loop Commented Sep 18, 2019 at 10:20

2 Answers 2

2

You can use Listener in different way

listener = Listener(on_press=on_press)
listener.start()

while Timer < 10: 
    print(str(counta/3))
    time.sleep(1)
    Timer += 1

#listener.stop()
listener.join()

or using your function

listener = Listener(on_press=on_press)
listener.start()

Stand(counta, Timer)

#listener.stop()
listener.join()

BTW: class Listener already uses thread to listen keys - class Listener(threading.Thread):.


EDIT: I released that you can also use it this way

with Listener(on_press=on_press) as listener:

    while Timer < 10: 
        print(str(counta/3))
        time.sleep(1)
        Timer += 1

    #listener.stop()
    listener.join()

or using your function

with Listener(on_press=on_press) as listener:

    Stand(counta, Timer)

    #listener.stop()
    listener.join()
Sign up to request clarification or add additional context in comments.

1 Comment

I added example which uses with Listener()
0

The easiest way is to use a Tread :

import treading # at begin of your file


thread = threading.Thread(target=Stand) # create thread with your function
thread.start() # launch your function

Note that print method can reduce time execution of your function, and print in thread won't be recommended.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.