python - Flask 断线子进程 stdout python3

标签 python linux flask

我想在返回子进程命令的标准输出时有断线:

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/

相关文章:

python - 未找到命名游标的模块

python - 如何使用 Python 传输二进制数据?

php - Python 3 标准化 URL

linux - 即时输出重定向,在程序仍在运行时查看文件重定向输出

python - 为什么在设置了 default 和 server_default 时,当 row 包含 null 时,session.merge 会抛出 IntegrityError

linux - Vagrant 的 Ubuntu 16.04 vagrantfile 默认密码

linux - 如何为关闭的套接字捕获信号 (`SIGPIPE` )?

python - 匹配任意路径或空字符串,无需添加多个 Flask 路由装饰器

python - Flask App 在 heroku 上失败,但与工头合作

python - 修改 FlaskForms 类 - 对象没有属性 '_fields'