簡體   English   中英

同時在Python中調用具有不同參數的函數

[英]Simultaneously call functions with different parametrs in Python

我發現了很多例子,但不是我的。 請在這里幫助我:

我有一個需要參數(URL)的函數,並且我需要同時多次調用函數(使用不同的參數),以獲得類似的信息:

 function started with param: rsync://.... (1)
 function started with param: rsync://.... (2)
 function started with param: rsync://.... (3)
 ....
 function (k) with param rsync://....has finished
 .....
 function started with param: rsync://.... (n)
 function (1) with param rsync://....has finished
 ....
 function (n) with param rsync://....has finished

這些函數是獨立的,它們不與任何常見對象或類似對象(不包括導入)進行交互。 我需要同時運行它們(這些功能中的n個)。 順序如何完成並不重要。

使用線程

例如,您可以使用:

import threading
my_thread = threading.Thread(target=your_function, args=(), kwargs={})  # This can go inside a loop, providing different args each time.
my_thread.start()

請訪問答案頂部的鏈接以獲取更多信息。

如果您想不停地關注此函數的內容,請使用Raydel提到的線程,或者如果應該將這些函數綁定到CPU而不是IO綁定,則使用multiprocessing

如果您的任務只是調用子流程,則可以

  • 使用sp = subprocess.Popen()啟動子sp = subprocess.Popen()
  • 保留這個sp ,有點像
  • 然后它們並行運行
  • poll()他們,直到他們完成
  • 那么您知道他們什么時候完成的。

暫無
暫無

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

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