python - After subprocess.Popen executes the command, the information received by stdout.read() is empty. Is it due to routing or its own program problem?
PHP中文网
PHP中文网 2017-06-12 09:21:16
0
1
1237

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

PHP中文网
PHP中文网

认证0级讲师

reply all(1)
学习ing

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!