使用多个管道从Python执行Shell脚本 [英] Execute Shell Script from Python with multiple pipes
本文介绍了使用多个管道从Python执行Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在python脚本中执行以下Shell命令:
I want to execute the following Shell Command in a python script:
dom=myserver
cat /etc/xen/$myserver.cfg | grep limited | cut -d= -f2 | tr -d \"
我有这个:
dom = myserver
limit = subprocess.call(["cat /etc/xen/%s.cfg | grep limited | cut -d= -f2", str(dom)])
subprocess.call(['/root/bin/xen-limit', str(dom), str(limit)])
它不起作用,但是我不知道为什么.
It does not work, but I don't know why..
更新:
c1 = ['cat /etc/xen/%s.cfg']
p1 = subprocess.Popen(c1, stdout=subprocess.PIPE)
c2 = ['grep limited']
p2 = subprocess.Popen(c2, stdin=p1.stdout, stdout=subprocess.PIPE)
c3 = ['cut -d= -f2']
p3 = subprocess.Popen(c3, stdin=p2.stdout, stdout=subprocess.PIPE)
c4 = ['tr -d \"']
p4 = subprocess.Popen(c4, stdin=p3.stdout, stdout=subprocess.PIPE)
result = p4.stdout.read()
limit = subprocess.call([result])
subprocess.call(['/root/bin/xen-limit', str(dom), str(limit)])
推荐答案
您可以将几个子流程粘合在一起:
You can glue several subprocesses together:
c1 = ['ls']
p1 = subprocess.Popen(c1, stdout=subprocess.PIPE)
c2 = ['wc']
p2 = subprocess.Popen(c2, stdin=p1.stdout,
stdout=subprocess.PIPE)
result = p2.stdout.read()
请注意,我们如何将p2的标准输入设置为p1的标准输出.
Notice how we've set the stdin of p2 to be the stdout of p1.
简化示例
这篇关于使用多个管道从Python执行Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文