问题描述
我有一个 python 脚本,它调用一堆函数,每个函数都将输出写入标准输出.有时,当我运行它时,我想通过电子邮件发送输出(连同生成的文件).我想知道如何在内存中捕获输出,以便我可以使用 email
模块来构建电子邮件.
I've got a python script that calls a bunch of functions, each of which writes output to stdout. Sometimes when I run it, I'd like to send the output in an e-mail (along with a generated file). I'd like to know how I can capture the output in memory so I can use the email
module to build the e-mail.
到目前为止我的想法是:
My ideas so far were:
- 使用内存映射文件(但似乎我必须为此在磁盘上保留空间,而且我不知道输出会持续多久)
- 绕过所有这些并将输出通过管道发送到 sendmail(但如果我还想附加文件,这可能会很困难)
推荐答案
你说你的脚本调用了一堆函数",所以我假设它们是可以从你的程序访问的 python 函数.我还假设您使用 print
在所有这些函数中生成输出.如果是这种情况,您只需将 sys.stdout
替换为 StringIO.StringIO
即可拦截您正在编写的所有内容.然后,您最终可以在您的 StringIO
上调用 .getValue
方法以获取已发送到输出通道的所有内容.这也适用于使用写入 sys.stdout
的子进程模块的外部程序.
You said that your script "calls a bunch of functions" so I'm assuming that they're python functions accessible from your program. I'm also assuming you're using print
to generate the output in all these functions. If that's the case, you can just replace sys.stdout
with a StringIO.StringIO
which will intercept all the stuff you're writing. Then you can finally call the .getValue
method on your StringIO
to get everything that has been sent to the output channel. This will also work for external programs using the subprocess module which write to sys.stdout
.
这是一种廉价的方式.我建议您使用 logging
模块进行输出.您将对它的输出方式有更多的控制,也可以更轻松地控制它.
This is a cheap way. I'd recommend that you do your output using the logging
module. You'll have much more control over how it does it's output and you can control it more easily as well.
这篇关于在 Python 中的同一进程中捕获标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!