【问题标题】:Live output status from subprocess command Error:I/o operation on closed file Python子进程命令的实时输出状态错误:已关闭文件 Python 上的 I/o 操作
【发布时间】:2020-10-20 14:41:02
【问题描述】:

我正在编写一个脚本来使用 subprocess.Popen 获取 netstat 状态。

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)

上面给出了 ValueError: I/O operation on closed file.。有什么办法可以得到直播输出。在live output from subprocess command 他们使用 writen 和 readlines 在这里我只需要打印实时状态请有人帮助我解决这个问题。谢谢!

【问题讨论】:

    标签: python python-3.x shell subprocess netstat


    【解决方案1】:

    由于stdout 文件描述符在您想要对其进行迭代时已经关闭,您会收到此错误。我写了一个工作版本。该实现可以实时提供被调用命令的输出。

    代码:

    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()
    

    输出:

    >>> 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  
    
       
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 2022-01-21
      • 2016-08-26
      相关资源
      最近更新 更多