拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 在执行HTTP呼叫时将一个点打印到控制台的Python函式

在执行HTTP呼叫时将一个点打印到控制台的Python函式

白鹭 - 2022-02-10 1986 0 0

我对 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()
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *