簡體   English   中英

同時運行兩個函數

[英]Run two function concurrently

我定義了幾個函數。

def func1():
    '''something goes here'''

def func2():
    '''something goes here'''

def func3():
    '''something goes here'''

def func4():
    '''something goes here'''

所以問題是:如果我們在func1()運行時調用該函數,我想始終運行func1()並且其他函數( func2()func3()func4() )應該可用。 除非用戶調用,否則希望func2()func3()func4()運行 這怎么辦?。 這是我到目前為止所做的

if __name__ == '__main__':
    Thread(target=func1()).start()

在這里,我啟動了函數func1() 意思是當函數func1()運行時,如果用戶調用它應該運行的其他函數,否則不會

我已經提到了一些線程和多處理,但仍然無法得到答案。 是否可以? 如果是這樣,請以正確的方式指導我。

提前致謝

threading.Timer 應該可以解決問題:

from threading import Timer

def func1():
    t = Timer(60.0, func2)
    t.start() #func2 will be called 60 seconds from now.

def func2():
    '''something goes here'''

def func3():
    '''something goes here'''

def func4():
    '''something goes here'''

根據您指定的內容,這是代碼。 func1()由線程執行,並且一直在執行。 用戶指定的輸入觸發其余功能。

from threading import Thread
def func1():
    '''do something'''
    func1() #recursive call to keep it running

def func2():
    '''something goes here'''

def func3():
    '''something goes here'''

def func4():
    '''something goes here'''
    
if __name__ == '__main__':
    Thread(target=func1).start()
    while True:
        n = input("Enter Command: ")
        if n=="func2":
            func2()
        elif n=="func3":
            func3()
        # add your cases
        else:
            print("Invalid Input")

假設您在 Python 交互式控制台中執行此操作。 如果你這樣做:

from threading import Timer

def func2(): 
    print("func2 called")

def func1(): 
    print("func1 called")

t = Timer(60.0, func2)
t.start()

現在控制台是免費的,並顯示提示。 func2將在60.0秒后執行,您可以調用func1()或任何您想要的。 看:

在此處輸入圖片說明

您的代碼中的一個明顯錯誤是啟動您需要的線程

Thread(target=func1).start()

即目標應該引用函數而不是調用它(不是func1() )。 所以代碼應該是:

from threading import Thread
import time

def func1():
    while True:
        print('Running func1')
        time.sleep(60)

def func2():
    '''something goes here'''
    print('func2 called')

def func3():
    '''something goes here'''
    print('func3 called')

def func4():
    '''something goes here'''
    print('func4 called')


if __name__ == '__main__':
    Thread(target=func1).start()
    func2()
    func3()
    func4()

暫無
暫無

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

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