簡體   English   中英

Python-並行執行兩個函數

[英]Python - executing two functions in parallel

我是python的新手,遇到以下問題。 我正在嘗試將變量(counta)除以3,然后每10秒獲取一次結果。 同時,我想在每次按“ a”時將1加到計數器上。 問題是我使用的方法是每10秒只能加1。 請您告知可能要更改的內容,以便我願意時可以加1,但我仍然可以得到當前結果(counta / 3)。 預先感謝您的幫助。 到目前為止,這是我的代碼:

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()

您可以以其他方式使用Listener

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

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

#listener.stop()
listener.join()

或使用您的功能

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

Stand(counta, Timer)

#listener.stop()
listener.join()

順便說一句:類Listener已經使用thread來監聽鍵- class Listener(threading.Thread):


編輯:我發布了您也可以這種方式使用它

with Listener(on_press=on_press) as listener:

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

    #listener.stop()
    listener.join()

或使用您的功能

with Listener(on_press=on_press) as listener:

    Stand(counta, Timer)

    #listener.stop()
    listener.join()

最簡單的方法是使用Tread:

import treading # at begin of your file


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

請注意,打印方法可以減少函數執行的時間,因此不建議使用線程打印。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM