Python 在文件中写入打印日志时,子进程在屏幕缓冲区中延迟

Python subprocess delayed in screen buffer while writing print logs in file

下面是我的脚本,它使用下面的示例调用另一个脚本并在执行完成后生成完整的输出,而期望它应该生成实时输出并同时写入文件。
发生的事情是它没有逐行生成输出并最终打印整个输出。

./My_Tests.py ALL
TC 1 : PASSED
TC 2 : PASSED
Tatal Passed Tests : 2
Tatal Failed Tests : 0 

My_Tests.py :

from subprocess import Popen, PIPE, STDOUT
with Popen("./tests.py", stdout=PIPE, stderr=STDOUT, bufsize=1, universal_newlines=True) as p, \  
    open('tests.log', 'ab') as file:  
    for line in p.stdout: # b'\n'-separated lines  
        print(line, end='') #new addition  
        sys.stdout.buffer.write(line)  
        file.write(line)  

我也尝试使用以下命令,但它只在终端上打印,而不是将输出保存在文件中。
导入子流程

# Run command and redirect it by | tee to a file named out.txt 
p = subprocess.Popen([command, '|', 'tee', 'out.txt'])
p.wait()

问题及解决方案:
我的 tests.py 文件有很多打印语句我做错了什么:

  • 我在上面的代码中直接调用 tests.py 文件,这导致整个文件明显执行然后打印输出。

这是我所做的:
1. 为上面的子流程代码创建了一个函数。
2. 为我的 tests.py 中的每个代码部分创建函数并进行 n 次测试-n.py
3.然后依次调用subprocess函数代码里面的thiese tests-n.py。父文件现在是 tests.py

    from subprocess import Popen, PIPE, STDOUT  

    def logc(file, logfile):
    with Popen(file, stdout=PIPE, stderr=STDOUT, bufsize=1, universal_newlines=True) as p, \  
        open(logfile, 'ab') as file:  
        for line in p.stdout: # b'\n'-separated lines  
            print(line, end='') #new addition  
            sys.stdout.buffer.write(line)  
            file.write(line)  

    os.system("> logs.py")
    logc("tests1.py", "logs.py")
    logc("tests2.py", "logs.py")
    logc("tests3.py", "logs.py")
    logc("tests3.py", "logs.py")