【问题标题】:Print output from every function打印每个函数的输出
【发布时间】:2018-02-22 22:50:22
【问题描述】:

使用 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()

^所以当 main 被调用时它会将abc,help,please保存为文本文件

【问题讨论】:

  • 你的save_output() 函数没有任何作用。您需要明确告诉它您要保存什么以及要保存在哪里。应该有代码而不是评论#save output of all functions
  • 几种方法,你有没有找过一种尝试过?
  • @joaoavf 这是“在此处插入其他人的代码”的占位符。这就像参数化 SQL 语句的反面
  • 我知道它需要代码,我只是不知道是什么。我试过了:
  • with io.open("abc.txt.", 'w') as f: with redirect_stdout(f): #What print statements here?

标签: python function save output


【解决方案1】:

你会考虑这样的事情

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'))

测试:

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

输出:

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

【讨论】:

    【解决方案2】:

    你不能用你当前的结构,至少不能没有像检查终端这样疯狂的东西(很可能不存在)。

    正确的做法是在调用其他函数之前重定向标准输出:

    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"
    

    但是,为什么你也应该问一下你为什么要这样做 - 有许多更直接的方法可以写入文件,而不涉及弄乱标准输出,这可能会产生意想不到的后果.您能更全面地描述一下您的用例吗?

    【讨论】:

    • 感谢您的评论。我有几个函数对某些文本执行某些操作(例如附加),然后由每个函数添加。我想用 save_output 函数打印每个函数的输出
    • This answer 可能是相关的。这是一个如何复制stdout 的秘诀,因此“正常”输出不会丢失。
    • @GskgskgxBczkgxlhx 我的方法有没有达到你的目标?我更新了答案以更明确地反映您的代码,以防出现任何混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2020-02-11
    • 2018-10-09
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多