1

I am running the following python code. I hoped it would execute some external Python code in terminal and save the output in a numpy array which I could then append to another numpy array to add an extra column. It runs the external python command in shell; but I cannot find a way to fetch the output so that I may save it in my program.

Here is the code :

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

How can I get what is output by my "python GetAlexRanking.py" command and save this in a variable in my Python code?

Thanks.

Simon Kiely
  • 5,880
  • 28
  • 94
  • 180
  • Check out [Get Python OUtput](http://stackoverflow.com/questions/2502833/python-store-output-of-subprocess-popen-call-in-a-string) – DOOM Feb 23 '14 at 14:54

1 Answers1

1

Use stdout=subprocess.PIPE. Without it, the subprocess is printing its output straight to the terminal.

cmd = subprocess.Popen("python GetAlexRanking.py " + row ,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       shell=True)
(output, err) = cmd.communicate()
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677