Python,从shell命令捕获整个输出

时间:2014-10-29 20:55:34

标签: shell python-2.7 output

我使用Python来自动完成我在机器学习中所做的一些工作。我使用的机器学习工具是Vowpal Wabbit,我通常从终端运行它。 我能够使用Python的调用(vw_command,shell = True)来运行Vowpal Wabbit,但我也希望捕获VW的整个shell输出。 这就是我试过的:

output =check_output(vw_command, shell=True)

这是我在Python IDE中看到的:

creating quadratic features for pairs: hh hb hp hr  final_regressor = model_vw.vw Num weight bits = 28 learning rate = 0.7 initial_t = 0 power_t = 0.5 decay_learning_rate = 1 creating cache_file = fold1.vw.cache Reading datafile = fold1.vw num sources = 1 average    since         example     example  current  current  current loss      last          counter      weight    label  predict features
0.693147   0.693147            1         1.0  -1.0000   0.0000     1209
0.615108   0.537070            2         2.0  -1.0000  -0.3411     1217
0.527696   0.440284            4         4.0  -1.0000  -0.5287     1217
0.474677   0.421658            8         8.0  -1.0000  -0.9651     1201
0.363831   0.252986           16        16.0  -1.0000  -1.2778     1217
0.259342   0.154852           32        32.0  -1.0000  -2.1993     1209
0.170503   0.081664           64        64.0  -1.0000  -2.5598     1217
0.106260   0.042017          128       128.0  -1.0000  -2.8044     1217
0.083359   0.060457          256       256.0  -1.0000  -8.8870     1217
0.056569   0.029780          512       512.0  -1.0000  -4.4179     1209
0.044556   0.032542         1024      1024.0  -1.0000  -4.0888     1209
0.036272   0.027989         2048      2048.0  -1.0000  -5.3605     1217
0.033533   0.030794         4096      4096.0  -1.0000  -5.7477     1199
0.026593   0.019653         8192      8192.0  -1.0000  -9.1520     1194
0.019215   0.011837        16384     16384.0  -1.0000 -13.8832     1209
0.014147   0.009079        32768     32768.0  -1.0000  -9.5163     1209
0.012523   0.010898        65536     65536.0  -1.0000 -17.4003     1209
0.009721   0.006920       131072    131072.0  -1.0000 -13.1049     1217
0.007038   0.004355       262144    262144.0  -1.0000 -10.1183     1209
0.005340   0.003642       524288    524288.0  -1.0000 -10.7823     1203
0.003909   0.002478      1048576   1048576.0  -1.0000  -9.5997     1209
0.002318   0.000727      2097152   2097152.0  -1.0000 -22.7368     1217

finished run
number of examples per pass = 425000
passes used = 1
weighted example sum = 425000
weighted label sum = -419716
average loss = 236.561
best constant = -0.987572
total feature number = 514554601

但是当我查看变量输出时,它是一个空字符串''。 如何捕获整个shell输出?

3 个答案:

答案 0 :(得分:2)

使用Popen管道,这里是:

import subprocess
child = subprocess.Popen('command',shell=True,stdout=subprocess.PIPE)
output = child.communicate()[0]
print output

答案 1 :(得分:1)

你可以使用sh module,这几乎就是魔术。输出正好在通话之外:

enter image description here

如果您不想使用其他模块,请忽略我的答案。

答案 2 :(得分:0)

import subprocess

cmd = "ls -l"

output = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT).stdout.read()

print output