如何发送;印刷品;将脚本插入列表而不使用;附加“;,使用python?

如何发送;印刷品;将脚本插入列表而不使用;附加“;,使用python?,python,list,Python,List,我想将脚本中的所有“打印”内容发送到列表中。 我有“函数”和“循环”。 您会注意到一些“单词”重复出现,例如:标签、型号、图像、时间(毫秒)、分数、TPU_温度(°C) 我曾想过使用“append”,但我需要每个值的“words”,因为我会将它们发送到数据库中 我的代码如下所示 def getInterpreter(root, files): for file in files: filepath = os.path.join(root, file) if

我想将脚本中的所有“打印”内容发送到列表中。 我有“函数”和“循环”。 您会注意到一些“单词”重复出现,例如:标签、型号、图像、时间(毫秒)、分数、TPU_温度(°C)

我曾想过使用“append”,但我需要每个值的“words”,因为我会将它们发送到数据库中

我的代码如下所示

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



我不确定我是否完全理解这个问题,但是你可以通过将多行内容合并成一行来添加到列表中吗

e、 g

使用带f字符串的追加连接到一行。

追加(f'Model:{file}\n')


如果我误解了您的问题,请告诉我。

您可以将脚本的stdout重定向到字符串缓冲区,这样打印函数的输出将进入缓冲区,然后您可以根据换行符拆分缓冲区的内容,以获得列表形式的输出

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

对不起,我一定错过了什么。为什么不在每个print语句后追加列表呢。追加有什么问题吗?您可以编写一个实用函数,向其中传递字符串,并用于打印和列表追加。这将提供更清晰的语法。为什么?为什么不直接从函数返回数据,然后在调用站点使用它呢?可以通过检查标准输出来完成您想要的操作,但实际上,对于奇怪的设置代码来说,这是一个混乱的解决方法。请添加结果列表的外观。我已经添加了更多信息
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())