我對 Python 有點陌生。我環顧四周,但找不到完全符合我正在尋找的答案。
我有一個使用 requests 包進行 HTTP 呼叫的函式。我想列印一個 '.' 在 HTTP 請求執行時每 10 秒對螢屏(或任何字符)說一次,并在完成時停止列印。所以像:
def make_call:
rsp = requests.Post(url, data=file)
while requests.Post is executing print('.')
當然,上面的代碼只是偽代碼,但希望能說明我希望完成的作業。
uj5u.com熱心網友回復:
來自requests模塊的每個函式呼叫都是阻塞的,因此您的程式會一直等到函式回傳一個值。最簡單的解決方案是使用threading已經建議的內置庫。使用此模塊允許您使用代碼“并行性”*。在您的示例中,您需要一個執行緒用于請求,該執行緒將被阻塞,直到請求完成,另一個用于列印。
如果您想了解有關更高級解決方案的更多資訊,請參閱此答案https://stackoverflow.com/a/14246030/17726897
以下是使用threading模塊實作所需功能的方法
def print_function(stop_event):
while not stop_event.is_set():
print(".")
sleep(10)
should_stop = threading.Event()
thread = threading.Thread(target=print_function, args=[should_stop])
thread.start() # start the printing before the request
rsp = requests.Post(url, data=file) # start the requests which blocks the main thread but not the printing thread
should_stop.set() # request finished, signal the printing thread to stop
thread.join() # wait for the thread to stop
# handle response
* 由于全域解釋器鎖 (GIL) 之類的東西,并行性用引號引起來。來自不同執行緒的代碼陳述句不會同時執行。
uj5u.com熱心網友回復:
我并沒有真正得到您想要的東西,但是如果您想同時處理兩件事,您可以使用multithreading模塊示例:
import threading
import requests
from time import sleep
def make_Request():
while True:
req = requests.post(url, data=file)
sleep(10)
makeRequestThread = threading.Thread(target=make_Request)
makeRequestThread.start()
while True:
print("I used multi threading to do two tasks at a same time")
sleep(10)
或者您可以使用非常簡單的日程安排模塊以簡單的方式安排您的任務
檔案:https : //schedule.readthedocs.io/en/stable/#when-not-to-use-schedule
uj5u.com熱心網友回復:
import threading
import requests
from time import sleep
#### Function print and stop when answer comes ###
def Print_Every_10_seconds(stop_event):
while not stop_event.is_set():
print(".")
sleep(10)
### Separate flow of execution ###
Stop = threading.Event()
thread = threading.Thread(target=Print_Every_10_seconds, args=[Stop])
### Before the request, the thread starts printing ###
thread.start()
### Blocking of the main thread (the print thread continues) ###
Block_thread_1 = requests.Post(url, data=file)
### Thread stops ###
Stop.set()
thread.join()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390762.html
