简体   繁体   中英

Getting output of external python program in Windows Terminal

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM