简体   繁体   中英

How to send the “prints” of a script into a list without using “append”, using python?

I would like to send all the "print" from my script into a list. I have "functions" and also "loops". You will notice that some "words" repeat, for example: Labels, Model, Image, Time(ms), Score, TPU_temp(°C).

I thought of using "append", but I need the "words" of each value as I will send them into a database.

MY CODE LOOKS LIKE THIS

def getInterpreter(root, files):
    for file in files:
        filepath = os.path.join(root, file)
        if filepath.endswith(".tflite"):
            print("Model:", file) <---------------------------HERE IS A PRINT
            print("\n") <--------------------------IT IS OKAY IF THIS GOES IN THE LIST 
            interpreter = make_interpreter(filepath)
            interpreter.allocate_tensors()
            return interpreter   
    return None



def getImage(dir_path, image_file):
    for file in image_file:#all files within the current path
         if re.match('.*\.jpg|.*\.bmp|.*\.png', file): 
                filepath = os.path.join(dir_path, file)
                print("Image:", file)   <-------------HERE IS A PRINT
                print("\n")         <------------ANOTHER PRINT
                return filepath
    return None


def main():
    subprocess.run('/usr/bin/snapshot', shell=False)           
    image_file = os.listdir(rootdir) 
    
    for root, subdirs, files in os.walk(rootdir):          
        labels = getLabel(root, files)
        interpreter = getInterpreter(root, files)
       
        if interpreter is not None:
            size = classify.input_size(interpreter)

            for _ in range(count):
                start = time.perf_counter()
                interpreter.invoke()
                inference_time = time.perf_counter() - start
                classes = classify.get_output(interpreter, top_k, threshold)
                print('Time(ms):', '%.1f' % (inference_time * 1000)) <----ANOTHER PRINT!
            print("\n")                                  <--------------ANOTHER PRINT


if __name__ == '__main__':
    main()


THIS IS WHAT IS PRINTED AFTER EXECUTING MY SCRIPT

Labels: imagenet_labels.txt

Model: efficientnet-edgetpu-S_quant_edgetpu.tflite

Image: img0000.jpg

*The first inference on Edge TPU is slow because it includes loading the model i                                                                                                             nto Edge TPU memory*
Time(ms): 23.1
Time(ms): 6.1


Inference: nematode, nematode worm, roundworm
Score: 0.02734

TPU_temp(°C): 61.55
#####################################

Labels: imagenet_labels.txt

Model: efficientnet-edgetpu-M_quant_edgetpu.tflite

Image: img0000.jpg

*The first inference on Edge TPU is slow because it includes loading the model i                                                                                                             nto Edge TPU memory*
Time(ms): 28.9
Time(ms): 10.6


Inference: wall clock
Score: 0.01953

TPU_temp(°C): 61.55
#####################################

I'm not sure I fully understand the issue but can you append to a list by wrapping up your multiple lines into one.

eg

Joining into one line using append with an f string.

newlist.append(f'Model:{file}\n')

Let me know if I misunderstood your issue.

You can redirect stdout of your script to a string buffer, so that the output of print functions would go into the buffer and then you can split the contents of the buffer based on newlines to get the output as list

from io import StringIO
import sys
import re

buffer = StringIO()
sys.stdout = buffer


# Your code should go here

stdout_lst = re.split(r'(?=\n)', buffer.getvalue())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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