我希望在返回子进程命令的stdout时有断行:
p = subprocess.Popen(['ping', site, '-c', '2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return (out)
实际上我通过网页输出,因为我使用了烧瓶:
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')
答案 0 :(得分:2)
在Python3中,p.communicate()
将返回bytes
个对象。如果您将这些解码为字符串,我怀疑您会看到换行符以您期望的方式处理。
print(out.decode())
我还猜测,当你在问题中放置“实际”输出时,换行字符会以某种方式被移除。在我的终端中,我将原始字节输出视为
PING foo-bar (1.2.3.4) 56(84) bytes of data.\n64 bytes...