打印并写出生成器对象

问题描述

试图将生成器对象合并到我的代码中,但有些无法正常工作。

def get_data():
    data = some_api_call
    result = data.json()
    return result

结果如下所示,其中每个{}都位于换行符上:

{u'bytes_out': 1052.0,u'host': u'abc.com'}
{u'bytes_out': 52.0,u'host': u'def.com'}
{u'bytes_out': 5558.0,u'host': u'xya.com'}
...


def write_to_file(line):
    #replacing the write statement with a print for testing
    print(line)

def read_report(data):
    for line in data:
        yield line

def main():
    alldata = get_data()
    write_to_file(read_report(alldata))

我的期望是它应该打印出来:

{u'bytes_out': 1052.0,u'host': u'xya.com'}

但是我回来的是:

<generator object read_report at 0x7fca02462a00>

不确定我在这里缺少什么

***编辑-修复了我使用不正确的情况

def main():
    all_data = get_data()
    for line in read_report(all_data)
        print(line)

解决方法

您也可以直接从生成器打印:

gen = range(1,10)
print(*gen,flush=True)
#out: 1 2 3 4 5 6 7 8 9

所以对于您的情况:

print(*read_report(all_data),flush=True)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...