The code below is what I use daily to monitor network connectivity. The returned information could be obtained before yesterday (as of the night before yesterday), but the content read by stdout.read() starting yesterday was empty. The information returned by me directly pinging the host in the CMD window is China Unicom, and the return information obtained by using the call method is also normal. Please help me solve my doubts
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()
学习ing2017-06-12 09:23:16
Your command ping 10.9.88.69 will not stop in the Linux environment,
And subprocess.Popen defaults to waiting for the command to end before returning the result, which is blocking
It can be like this
1. Let the ping end early. Add multiple parameters -c to specify the number of pings
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. Change blocking to non-blocking
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)