Search code examples
pythonpython-3.xshellsubprocessnetstat

Live output status from subprocess command Error:I/o operation on closed file Python


I'm writing a script to get netstat status using subprocess.Popen.

cmd = 'netstat -nlpt | grep "java" | grep -v tcp6'

result1 = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True )
stdout, stderr=result1.communicate()

for line in iter(result1.stdout):
    print(line)

The above is giving ValueError: I/O operation on closed file.. Is there any way to get the live-streaming output. In live output from subprocess command they are using writen and readlines here i just need to print live status please some one help me on this issue. Thank you!


Solution

  • You get this error due to the stdout file descriptor has already been closed when you want to iterate on it. I have written a working version. This implementation can provide the output of the called command in real-time.

    Code:

    import sys
    import subprocess
    
    cmd = 'netstat -nlpt | grep "java" | grep -v tcp6'
    
    result1 = subprocess.Popen(
        cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True
    )
    
    while True:
        out = result1.stdout.read(1)
        if out == "" and result1.poll() is not None:
            break
        if out != "":
            sys.stdout.write(out)
            sys.stdout.flush()
    

    Output:

    >>> python3 test.py
    tcp        0      0 127.0.0.1:6943          0.0.0.0:*               LISTEN      239519/java         
    tcp        0      0 127.0.0.1:63343         0.0.0.0:*               LISTEN      239519/java