简体   繁体   English

如何在python中将多个函数的输出重定向到字符串或标准输出? (stdout 到变量的反向)

[英]How do I redirect output of multiple functions to string or stdout in python? (The reverse of stdout to a variable)

Often I have to print all sorts of diagnostics and I am tired of wrapping everything into a print.通常,我必须打印各种诊断信息,而且我厌倦了将所有内容都打印出来。 Is there something that allows me to just redirect output ie return values of multiple function calls to a string or stdout?有什么东西可以让我只重定向输出,即多个函数调用的返回值到字符串或标准输出?

import numpy as np
import pandas as pd

df = pd.DataFrame({'a':range(10)})

# tedious
print(df.describe())
print(df.head())

# better
with something():
    df.describe()
    df.head()

I am aware of Redirect stdout to a file in Python?我知道将标准输出重定向到 Python 中的文件吗? that is not what I want to do.那不是我想做的。

I assume that you want to print the return values of those functions (functions don't "have output" unless they themselves use print or write to a file, in which case your problem would already be solved).我假设你想打印这些函数的返回值(函数没有“输出”,除非它们自己使用print或写入文件,在这种情况下你的问题已经解决了)。 You could do this:你可以这样做:

def print_many(*values):
    for value in values:
        print value

print_many(
    df.describe(),
    df.head(),
)

Note that this will execute all the functions before anything is printed.请注意,这将在打印任何内容之前执行所有功能。

Short answer: no.简短的回答:没有。

Long answer: you can maybe do something like this:长答案:你可以做这样的事情:

def print_all(*expressions):
    for expr in expressions:
        print(expr)

print_all(
    df.describe(),
    df.head(),
)

which comes with a couple caveats:这有几个警告:

  1. You couldn't use conventional assignment.你不能使用传统的分配。 When assignment would be required, you'd have to use the assignment operator := , which is only available in python 3.8, so this would be structured differently than a normal function.当需要赋值时,您必须使用赋值运算符:= ,它仅在 python 3.8 中可用,因此它的结构与普通函数不同。
  2. Everything would be evaluated first, before being printed.在打印之前,将首先评估所有内容。 You could work up some dynamic thing probably by using eval() , but that has other risks.您可以通过使用eval()来处理一些动态的事情,但这有其他风险。

Alternatively, you could try modifying the df object beforehand so that all relevant methods print their return values - essentially, applying a decorator to every method you want:或者,您可以尝试预先修改df对象,以便所有相关方法打印其返回值 - 本质上,将装饰器应用于您想要的每个方法:

def print_wrapper(func):
    def wrap(*args, **kwargs):
        retval = func(*args, **kwargs)
        print(retval)
        return retval
    return wrap

def wrap_funcs(obj, funcnames):
    for funcname in funcnames:
        func = getattr(obj, funcname)
        setattr(obj, funcname, print_wrapper(func))

df = pd.DataFrame({'a':range(10)})
wrap_funcs(df, ['describe', 'head'])

df.describe()
df.head()

This also has caveats, as you'd need to ensure that the names you give it actually are functions or things start going wrong fast, but it should be a possible starting point.这也有警告,因为你需要确保你给它的名字实际上函数或者事情开始很快出错,但这应该是一个可能的起点。

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

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