简体   繁体   English

打印每个功能的输出

[英]Print output from every function

Using a save_ouput function, how can I save the output of every function? 使用save_ouput函数,如何保存每个函数的输出?

def a():
    print("abc,")

def b():
    print("help,")

def c():
    print("please")

def save_output():
    # save output of all functions

def main():
    a()
    b()
    c()
    save_output()

main()

^So it'd save abc,help,please as a text file when main is called ^因此将main调用时abc,help,please它将abc,help,please另存为文本文件

You can't with your current structure, at least not without something crazy like inspecting the terminal (which might well not exist). 您不能使用当前的结构,至少不能没有像检查终端这样的疯狂东西(可能不存在)。

The right way to do this is by redirecting standard out before you call the other functions: 正确的方法是调用其他函数之前重定向标准输出:

import sys
def a():
  print("abc,")
def b():
  print("help,")
def c():
  print("please")

def main():
 original_stdout = sys.stdout
 sys.stdout = open('file', 'w')
 a()
 b() 
 c()
 sys.stdout = original_stdout

main()
# now "file" contains "abc,help,please"

However, it's also worth asking why you want to do this at all – there are many more straightforward ways to write to a file that don't involve messing with stdout, which might have unintended consequences. 但是,也值得一提的是, 为什么要执行此操作-有很多更简单的方法来写入文件,而不会涉及混乱stdout,这可能会带来意想不到的后果。 Can you describe your use case a little more fully? 您能否更全面地描述用例?

Would you consider something like this 你会考虑这样的事情吗

def a():
    return 'abc'
def b():
    return 'help'
def c():
    return 'please'
def save_output(file_name, *args):
    with open(file_name, 'w') as f:
        for x in args:
            f.write('Function {0}() returned: {1}{2}'.format(x.__name__,x(),'\n'))

To test: 去测试:

save_output('example.txt',a,b,c)

Output: 输出:

Function a() returned: abc
Function b() returned: help
Function c() returned: please

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

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