繁体   English   中英

在Windows Terminal中获取外部python程序的输出

[英]Getting output of external python program in Windows Terminal

我正在运行以下python代码。 我希望它可以在终端中执行一些外部Python代码,并将输出保存在numpy数组中,然后可以将其附加到另一个numpy数组中以添加额外的列。 它在shell中运行外部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

如何获取“ python GetAlexRanking.py”命令的输出并将其保存在Python代码的变量中?

谢谢。

使用stdout=subprocess.PIPE 没有它,子进程将直接将其输出打印到终端。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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