2012-01-11 126 views
1

打印出返回值,我用Python调用的bash执行另一个bash脚本:如何避免使用os.system()在python

begin = int(sys.argv[1]) 
result = os.system("/tesladata/isetools/cdISE.bash %s" %begin) 

我打印result后,它不仅给我的输出还有退货状态(这里的0)。 如果我只需要输出,我该怎么办?

而且,为了好奇,有多少种方法可以在Python中调用bash?如果有人能够提供一些如何使用它们的参考资料,我会很高兴,到目前为止我只找到os.system()os.popen()

+0

你的第二个问题是在这里(http://stackoverflow.com/questions/3479728/is-it-good-style-to-call-bash-commands-within-a-python-script-using-os-讨论systemb)和(http://stackoverflow.com/questions/4256107/running-bash-commands-in-python)Here – Bry6n 2012-01-11 16:49:38

回答

7

其实,result只是作为一个整数返回状态。你所调用的东西写入stdout,它从你的程序继承,所以你会立即看到它被打印出来。它永远不可用于您的程序。

退房的子模块文档的更多信息:

http://docs.python.org/library/subprocess.html

包括捕获输出,并以不同的方式调用炮弹。

+4

具体来说,它看起来像他希望[subprocess.check_output(http://docs.python.org/library/subprocess.html#subprocess.check_output) – 2012-01-11 17:05:56

3

您可以通过管道的任何输出只是扔掉到/dev/null

begin = int(sys.argv[1]) 
result = os.system("/tesladata/isetools/cdISE.bash %s > /dev/null" %begin) 

如果你不想或者显示错误,改变>2&>丢弃stderr为好。

2

你的Python脚本没有bash脚本的输出可言,但只有“0”,它返回。 bash脚本的输出与python脚本的输出流相同,并在打印result的值之前打印。如果你不想看到0,不要打印结果。

+0

感谢您的回复。我想你是对的,但是如果我想从bash脚本获得输出并将其存储在其他地方呢? – 2012-01-11 16:53:43

+0

@dazhuangcao如果你想输出,使用os.popen或子 – 2012-01-11 17:19:20