python - 在 Windows 终端中获取外部 python 程序的输出

标签 python windows python-2.7 numpy 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()

关于python - 在 Windows 终端中获取外部 python 程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21969515/

相关文章:

excel - 如何使用 pandas to_exel 将 'utf-8' 格式的字符串保存为 .xlsx(to_csv 能够将其保存为 .csv)

python - 如何在 iOS Appium 上按 "OK"弹出位置

python - AttributeError 'tuple' 对象没有属性 'get'

python - 不确定如何在使用 groupby 后按版本规范化计数

windows - 如何使用日期和时间创建文件夹?

Python 将字典列表转换为另一个字典列表

Python 2.7 - 比较两个文本文件并仅写入第一个文件中的唯一值

python - 如何在 Keras/Tensorflow 中返回增强数据

windows - IOCP 循环终止可能导致内存泄漏?如何优雅地关闭 IOCP 循环

windows - 重启docker后docker compose无法启动service network not found