【问题标题】:Python function to print a dot to console while HTTP call executesPython函数在HTTP调用执行时打印一个点到控制台
【发布时间】:2022-01-24 02:01:01
【问题描述】:

我对 Python 有点陌生。我环顾四周,但找不到完全符合我要求的答案。

我有一个使用 requests 包进行 HTTP 调用的函数。我想打印一个'。在 HTTP 请求执行时每 10 秒显示一次屏幕(或任何字符),并在完成后停止打印。所以像:

def make_call:  
  rsp = requests.Post(url, data=file)  
  while requests.Post is executing print('.')  
   

当然,上面的代码只是伪代码,但希望能说明我希望实现的目标。

【问题讨论】:

    标签: python python-3.x python-requests


    【解决方案1】:

    我并没有真正得到你要找的东西,但如果你想同时处理两件事情,你可以使用 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

    【讨论】:

    • 您错过了主要问题 - opp 希望在响应到来时停止打印
    • 谢谢。我应该提到我不想使用外部包。如果我更清楚,我只想在 requests.Post() 调用执行时向控制台打印一些状态,并在执行完成时停止打印。一种让用户知道 HTTP 请求仍在处理中的方法。对于状态,我只是选择打印一个“。”字符。
    • 如果我理解正确,如果不使用线程、多处理等一些包,您不能同时执行 2 个进程...
    【解决方案2】:

    来自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) 之类的原因,并行性用引号引起来。来自不同线程的代码语句不会同时执行。

    【讨论】:

      【解决方案3】:
      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()
      

      【讨论】:

        【解决方案4】:

        下面的代码也解决了这个问题。它将打印“POST Data..”和附加的尾随 '.'每秒直到 HTTP POST 返回。

        import concurrent.futures as fp
        import logging
        
        with fp.ThreadPoolExecutor(max_workers=1) as executor: 
          post = executor.submit(requests.post, url, data=fileobj, timeout=20)     
          logging.StreamHandler.terminator = ''
          logging.info("POST Data..")
          while (post.running()):
            print('.', end='', flush=True)
            sleep(1)
          print('')
          logging.StreamHandler.terminator = '\n'
          http_response = post.result()
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
        猜你喜欢
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        • 2018-05-02
        • 2012-09-21
        • 2010-09-23
        • 2017-12-15
        • 1970-01-01
        相关资源
        最近更新 更多