我想在返回子进程命令的标准输出时有断线:
p = subprocess.Popen(['ping', site, '-c', '2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return (out)
实际上,我通过网页得到了此输出因为我正在使用 flask :
PING foo-bar (1.2.3.4) 56(84) bytes of data. 64 bytes from 1.2.3.4 (1.2.3.4): icmp_seq=1 ttl=54 time=15.3 ms 64 bytes from 1.2.3.4 (1.2.3.4): icmp_seq=2 ttl=54 time=14.3 ms --- foo-bar ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1001ms rtt min/avg/max/mdev = 14.334/14.848/15.363/0.528 ms
我想要这样的输出:
PING foo-bar (1.2.3.4) 56(84) bytes of data.
64 bytes from 1.2.3.4 (1.2.3.4): icmp_seq=1 ttl=54 time=16.4 ms
64 bytes from 1.2.3.4 (1.2.3.4): icmp_seq=2 ttl=54 time=13.6 ms
--- foo-bar ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 13.695/15.088/16.482/1.398 ms
这是路线的完整代码:
@app.route('/path/<action>', methods=['POST'])
def webping(action):
if action == 'ping':
site = request.form['site']
r = re.match(r"^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$", site)
if r :
p = subprocess.Popen(['ping', site, '-c', '2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return (out.decode())
else :
return ('Error regex')
最佳答案
在 Python3 中,p.communicate()
将返回 bytes
对象。如果您将它们解码为字符串,我怀疑您会看到换行符按照您期望的方式处理。
print(out.decode())
我还猜测,当您将“实际”输出放入问题中时,换行符已被以某种方式删除。在我的终端中,我看到原始字节输出为
PING foo-bar (1.2.3.4) 56(84) bytes of data.\n64 bytes...
关于python - Flask 断线子进程 stdout python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41792101/