繁体   English   中英

在另一个文件中记录已执行的 python 文件的打印输出并同时在终端中打印结果

[英]Logging printout of an executed python file within another file and printing out the result in terminal simultaneously

我有两个 Python 文件( main.pymain_test.py )。 文件main_test.pymain.py中执行。 当我不使用日志文件时,打印出来的是:

Main file: 17:41:18
Executed file: 17:41:18
Executed file: 17:41:19
Executed file: 17:41:20

当我使用日志文件并执行main.py>log时,我得到以下信息:

Executed file: 17:41:18
Executed file: 17:41:19
Executed file: 17:41:20
Main file: 17:41:18

另外,当我使用python3 main.py | tee log python3 main.py | tee log打印并记录 output,它等待并在完成所有操作后打印出来。 此外,倒车的问题依然存在。


问题

  1. 我怎样才能修复颠倒的打印输出?
  2. 如何在终端中同时打印出结果并以正确的顺序记录它们?

Python 个文件用于复制

main.py

import os 
import time
import datetime
import pytz

python_file_name = 'main_test'+'.py'

time_zone = pytz.timezone('US/Eastern') # Eastern-Time-Zone

curr_time = datetime.datetime.now().replace(microsecond=0).astimezone(time_zone).time()

print(f'Main file: {curr_time}')
cwd = os.path.join(os.getcwd(), python_file_name)
os.system(f'python3 {cwd}')

main_test.py

import pytz
import datetime
import time

time_zone = pytz.timezone('US/Eastern') # Eastern-Time-Zone

for i in range(3):
    curr_time = datetime.datetime.now().replace(microsecond=0).astimezone(time_zone).time()
    print(f'Executed file: {curr_time}')
    time.sleep(1)

当您运行这样的脚本时:

python main.py>log

shell 将 output 从脚本重定向到名为log的文件。 但是,如果脚本在它们自己的子 shell 中启动其他脚本(这是os.system()所做的),则不会捕获其中的 output。

你的例子令人惊讶的是,你在重定向时会看到任何东西,因为 output 应该已经被重定向并且不再回显 - 所以也许你在这里遗漏了一些东西。

此外, tee等待标准输入中的 EOF,或发生某些错误,因此您在那里看到的行为是有道理的。 这是预期的行为。

为什么要为贝壳而烦恼呢? 为什么不自己写几个函数调用,导入另一个Python模块调用它的函数呢? 或者,如果您需要并行运行(在您的示例中没有),请查看multiprocessing

直接回答你的问题:

  • “我怎样才能修复颠倒的打印输出?”
    不要使用重定向,直接从脚本写入文件,或者确保在从第一个调用其他脚本时使用相同的重定向(这会变得混乱),或者从子 shell 中的子进程捕获 output 并将其捕获到 pipe主脚本的标准。

  • “如何在终端中同时打印出结果并以正确的顺序记录它们?”
    您可能应该只在脚本中执行此操作,否则这不是一个真正的 Python 问题,您应该尝试使用 SuperUser 或类似站点,看看是否有某种方法可以让tee或类似工具实时写入。

不过一般来说,除非您有非常充分的理由让其他功能在其他 shell 中运行,否则您应该考虑在 Python 脚本中解决您的问题。 如果你不能,你可以使用Popen或衍生工具来捕获下标的 output 并做你需要的,而不是依赖运行脚本的主机操作系统上可能可用或不可用的工具。

暂无
暂无

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

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