Getting realtime output using subprocess

前端 未结 18 2626
执笔经年
执笔经年 2020-11-22 10:12

I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be abl

18条回答
  •  囚心锁ツ
    2020-11-22 11:06

    Real Time Output Issue resolved: I encountered a similar issue in Python, while capturing the real time output from C program. I added fflush(stdout); in my C code. It worked for me. Here is the code.

    C program:

    #include 
    void main()
    {
        int count = 1;
        while (1)
        {
            printf(" Count  %d\n", count++);
            fflush(stdout);
            sleep(1);
        }
    }
    

    Python program:

    #!/usr/bin/python
    
    import os, sys
    import subprocess
    
    
    procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    
    while procExe.poll() is None:
        line = procExe.stdout.readline()
        print("Print:" + line)
    

    Output:

    Print: Count  1
    Print: Count  2
    Print: Count  3
    

提交回复
热议问题