2016-03-21 222 views
-1

如何在python腳本中運行以下命令?運行bash命令到python腳本

echo "show stat" | socat unix-connect:/var/run/haproxy/admin.sock stdio | grep webservers,BACKEND | cut -d , -f8 

我想這

import subprocess 
var = subprocess.check_output(echo "show stat" | socat unix-connect:/var/run/haproxy/admin.sock stdio '| grep ' webservers,BACKEND' | cut -d , -f8', shell=True) 
var=int(var) 

但是那不行!

+1

'VAR = subprocess.check_output( 「」「回聲 」顯示統計「 | socat UNIX的連接:/var/run/haproxy/admin.sock STDIO '| grep的'網頁服務器,BACKEND'| cut -d,-f8'「」「,shell = True)' –

+0

檢查這個問題http://stackoverflow.com/questions/27911820/python-subprocess-with-quotes-and-pipe-grep –

+1

您需要傳遞一個字符串,而不是命令。 – asimoneau

回答

0

嘗試用Popen

from subprocess import Popen, PIPE 

p1 = Popen(["echo", "show stat"], stdout=PIPE) 
p2 = Popen(["socat", "unix-connect:/var/run/haproxy/admin.sock", "stdio"], stdin=p1.stdout) 
p3 = Popen(["grep", "webservers,BACKEND"], stdin=p2.stdout) 
p4 = Popen(["cut", "-d", ",", "-f8"], stdin=p3.stdout)