简体   繁体   English

如何使用 python 将脚本的“打印”发送到列表中而不使用“附加”?

[英]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).您会注意到一些“单词”重复,例如: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.我不确定我是否完全理解这个问题,但你能否通过将多行合并为一个来将 append 列在一个列表中。

eg例如

Joining into one line using append with an f string.使用带有 f 字符串的 append 加入一行。

newlist.append(f'Model:{file}\n') 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您可以将脚本的标准输出重定向到字符串缓冲区,以便打印函数的 output 将 go 到缓冲区中,然后您可以根据换行符拆分缓冲区的内容以获取 Z78E6221F6393D1356681DBCE3 作为列表

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())

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

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