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:
- use a memory-mapped file (but it seems like I have to reserve space on disk for this, and I don’t know how long the output will be)
- bypass all this and pipe the output to sendmail (but this may be difficult if I also want to attach the file)
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
printto generate the output in all these functions. If that’s the case, you can just replacesys.stdoutwith aStringIO.StringIOwhich will intercept all the stuff you’re writing. Then you can finally call the.getValuemethod on yourStringIOto get everything that has been sent to the output channel. This will also work for external programs using the subprocess module which write tosys.stdout.This is a cheap way. I’d recommend that you do your output using the
loggingmodule. You’ll have much more control over how it does it’s output and you can control it more easily as well.