2012-08-22 87 views
2

可能重复:
Running shell command from python and capturing the output简单的python命令来捕获shell执行输出?

当我想捕捉shell执行输出,我这样做。

declare TAGNAME=`git describe --tags` 

简单。我在Python中寻找这个,但其中大多数看起来非常复杂。什么是最简单的方法来做到这一点?是的,我知道我可以创建一个函数,但是我想知道预定义的函数是否存在。

tagname = theFunc('git describe --tags') 

回答

6

尝试:

>>> import subprocess 
>>> tagname = subprocess.check_output('git describe --tags'.split()) 
+0

需要为返回的字符串调用'.strip('\ n')'。 – Eonil

+0

@Eonil为什么要调用'.strip('\ n')'?拥有'\ n'真的很重要吗? – quantum

+0

@xiaomao是的。因为我会将字符串传递给另一个shell命令。如果你意想不到的结果会很好,那真是太好了。 – Eonil

1

你应该看看subprocess模块。你也可以捕获一个命令的输出。手册页中有很多例子说明了如何使用模块。

实施例:

output=subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE).communicate() 

结果是具有输出和错误一个元组是从命令捕获。