2017-01-22 87 views
1

我想有斷線,而返回的子命令的標準輸出:瓶斷線子標準輸出python3

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

回答

1

在Python3 p.communicate()將返回bytes對象。如果你將它們解碼爲字符串,我懷疑你會看到你所期待的換行符處理。

print(out.decode()) 

我還猜測,當你在你的問題中放置「實際」輸出時,換行符會以某種方式被刪除。在我的終端中,我看到原始字節輸出爲

PING foo-bar (1.2.3.4) 56(84) bytes of data.\n64 bytes... 
+0

它似乎不適用於我的問題 – corentin