简体   繁体   English

如何在永远循环中运行函数?

[英]how to run function in forever loop?

i want to loop forever my function.我想永远循环我的函数。 but i'm having a struggle.但我正在挣扎。

import os
import requests
import glob
import time 
import base64

url = 'http://0.0.0.0:5000/'

def load_data():

    os.chdir('./40_mb')
    for image in glob.glob('*.jpg'):
        with open(image, 'rb') as imageFile:
            # image_s = base64.b64encode(imageFile.read())
            image_s = {'file_image':open(image, 'rb')}

    return image_s

def send_data():


    start = time.time()
    r = requests.post(url, files = load_data())
    end = time.time()

    print('client 1: {} ms'.format((end - start)*1000))



if __name__ == "__main__":
    while True:
        send_data()

when i run it, i get this error:当我运行它时,我收到此错误:

Traceback (most recent call last):
  File "http_1.py", line 32, in <module>
    send_data()
  File "http_1.py", line 23, in send_data
    r = requests.post(url, files = load_data())
  File "http_1.py", line 11, in load_data
    os.chdir('./40_mb')
FileNotFoundError: [Errno 2] No such file or directory: './40_mb'

without while True my code runs fine.没有while True我的代码运行良好。 does anyone can help my problem?有没有人可以帮助我的问题? sorry if this a silly question.对不起,如果这是一个愚蠢的问题。 thanks in advance提前致谢

Its seems you are not redirecting to the correct directory when in the while loop.在 while 循环中,您似乎没有重定向到正确的目录。 Essentially to fix this you will want to is change your working directory to where you originally started from.基本上要解决这个问题,您需要将工作目录更改为最初开始的位置。 A really clean and convenient way to do that would be to use it in a context manager, just for a cleaner more reusable code.一个真正干净和方便的方法是在上下文管理器中使用它,只是为了更干净、更可重用的代码。

import os
import os
import requests
import glob
import time 
import base64
from contextlib import contextmanager


@contextmanger
def workingdir(path):
    try:
       origin = os.getcwd()
       os.chdir(path)
       yield
    except:
       print('error occured') #might be better to logging the error instead of a just a print statement
    finally:
        os.chdir(origin)

url = 'http://0.0.0.0:5000/'

def load_data():

    with workingdir(path):
        for image in glob.glob('*.jpg'):
            with open(image, 'rb') as imageFile:
                # image_s = base64.b64encode(imageFile.read())
                image_s = {'file_image':open(image, 'rb')}

        return image_s

def send_data():


    start = time.time()
    r = requests.post(url, files = load_data())
    end = time.time()

    print('client 1: {} ms'.format((end - start)*1000))



if __name__ == "__main__":
    while True:
        send_data()

With this every time the while loop runs, it comes right back the directory it started from.每次 while 循环运行时,它都会返回它开始的目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM