首頁  >  問答  >  主體

python - subprocess.Popen執行指令後stdout.read()到的資訊為空,是路由原因還是自身程式問題?

下面的程式碼是我日常用來監測網路聯通性的,昨天之前(截止到前天晚上)都可以獲取到返回的信息,而昨天開始stdout.read()讀到的內容就是空。我直接在CMD視窗ping主機回傳的訊息是聯通的,用call方法取到的回傳訊息也正常。請大神幫忙解惑

cmd='ping 10.9.88.69'
P=subpross.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
reshult=p .stdout.read()

PHP中文网PHP中文网2686 天前1215

全部回覆(1)我來回復

  • 学习ing

    学习ing2017-06-12 09:23:16

    你這個指令ping 10.9.88.69 在linux環境下是不會停止的,
    而且subprocess.Popen預設是等待指令結束才回傳結果,是阻塞的

    可以這樣

    1.讓ping早點結束 加多個以參數 -c 指定下ping的次數

    cmd='ping 10.9.88.69 -c 3'
    P=subpross.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    reshult=p.stdout.read()
    

    2.把阻塞變成不阻塞

    import os
    import time
    import fcntl
    import subprocess
    
    cmd = 'ping 10.9.88.69'
    
    p = subprocess.Popen(cmd,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,shell=True)
    
    fd = p.stdout.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    
    while True:
        try:
            line = p.stdout.readline()
            print(line)
        except:
            time.sleep(1)

    回覆
    0
  • 取消回覆