【问题标题】:Python handling system output without returnsPython 处理系统输出没有返回
【发布时间】:2017-08-10 10:59:05
【问题描述】:

我有两个程序。第一个程序中的函数返回一些消息并包含许多prints。因此,我将第一个程序函数导入第二个程序并使用返回值。但是,我也需要第一个程序的prints。我怎样才能得到它们?

仅供参考,我不能在返回值中附加 print 值。有什么方法可以获取程序使用的所有打印件?

示例代码:

第一个程序1.py

class Test():
    def first(self,name):
        print "first print"
        print "second print"
        print "third print"
        #do some thing..
        return {"sucess":"end result"}

第二个程序2.py

from firstprog import Test
result = Test().first("testing")
return result + "first program prins here"

【问题讨论】:

  • 请提供您所解释内容的示例代码,以便我们轻松为您提供帮助。我们不需要完整的代码或真实的代码,只需要一个代码 sn-p 来举例说明您当前正在执行的操作。
  • 应显示对第一个 python 文件中包含print() 的函数的调用。发布您为每个文件使用的代码示例。
  • 我意识到我在回答中假设您是从另一个 python 文件中导入函数。是这样吗?
  • 添加代码@CristianRamon-Cortes
  • 是的,见上面的示例代码@FunkySayu

标签: python input printing output system


【解决方案1】:

您可以通过将sys.stdout 设为您自己的StringIO 对象来修补它。

import StringIO
import sys

def my_function():
    print("foo")
    return 5

stdout = sys.stdout
sys.stdout = my_stdout = StringIO.StringIO()

result = my_function()

sys.stdout = stdout
print(my_stdout.getvalue())  # prints foo
print(result)  # prints 5

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 2022-01-03
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多