2016-03-21 223 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)