在文件中写入打印日志时,Python子进程在屏幕缓冲区中延迟 [英] Python subprocess delayed in screen buffer while writing print logs in file

查看:91
本文介绍了在文件中写入打印日志时,Python子进程在屏幕缓冲区中延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Below is my script which calls another script using below example and produces entire output after execution is completed while expectation is that it should produce live output as well as write in file at the same time.
What happening is that its not producing output line by line and printing entire output in the end.

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

My_Tests.py:

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)  

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

I also tried with below command but it prints only on Terminal and not saving output in file.
import subprocess

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

推荐答案

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

What was the issue and solution :
My tests.py file had many print statements what i was doing wrong:

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

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

Here is what i did :
1. Created a function for above subprocess code.
2. Created functions for every part of code inside my tests.py and made n numbers of tests-n.py
3. Then call thiese tests-n.py inside subprocess function code one after another. Parent file is now 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")

这篇关于在文件中写入打印日志时,Python子进程在屏幕缓冲区中延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆