2014-02-23 40 views
1

我正在運行以下python代碼。我希望它會在終端中執行一些外部Python代碼,並將輸出保存在一個numpy數組中,然後我可以將它添加到另一個numpy數組中以添加額外的列。它在shell中運行外部python命令;但是我找不到獲取輸出的方式,以便將其保存到我的程序中。在Windows終端中獲取外部python程序的輸出

下面是代碼:

import csv 
import GetAlexRanking #External Method exposed here 
import subprocess 
import pandas as p 
import numpy as np 

loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter=' ') 
with open('train.tsv','rb') as tsvin, open('PageRanks.csv', 'wb') as csvout: 
    tsvin = list(np.array(p.read_table('train.tsv'))[:,0]) 
    csvout = csv.writer(csvout) 

    for row in tsvin: 
     count = 0 
     cmd = subprocess.Popen("python GetAlexRanking.py " + row ,shell=True) 
     (output, err) = cmd.communicate() 
     exit_code = cmd.wait() 
     print exit_code #testing 
     print output #**error here**, always prints "none" 
     csvout.write(url + "\t" + cmd_string) #writing 
     count+=1 

我怎樣才能得到的是輸出由我「蟒蛇GetAlexRanking.py」命令,並在一個變量保存這在我的Python代碼?

謝謝。

+0

退房[獲取Python的輸出(http://stackoverflow.com/questions/2502833/python-store-output-of-subprocess-popen-call-in-a-string) – DOOM

回答

1

使用stdout=subprocess.PIPE。沒有它,子進程將其輸出直接打印到終端。

cmd = subprocess.Popen("python GetAlexRanking.py " + row , 
         stdout=subprocess.PIPE, 
         stderr=subprocess.PIPE, 
         shell=True) 
(output, err) = cmd.communicate()