popen(), sendmail: Success?

Carsten Gaebler news at snakefarm.org
Thu Apr 10 17:50:13 EDT 2003


In article <3e95d63f.2635484 at news.muenster.de>, Martin Bless wrote:
> 
> To send mails from Python here's the example my provider provides:
> This http://faq.puretec.de/skripte/python/3.html
> 
> The relevant lines are these:
> 
> sendmail = os.popen("/usr/lib/sendmail -t", "w")
> sendmail.write(msg)
> sendmail.close()
> 
> This works just fine. But is it enough? How do I know the operation
> succeeded?

In an error condition python would either raise an exception or give you
sendmail's error status as the return value of the close() call.

If your code appears in a CGI script, you should catch the exception and
print it to stdout because otherwise the error would go to stderr which
will not be captured by the webserver. If it is a script run from a shell
or as a cron job, exception handling is not needed as long as you don't want 
to continue the program.

If errors should go to stdout I'd do something like the following:

import os, sys

try:
  sendmail = os.popen("/usr/lib/sendmail -t", "w")
  sendmail.write(msg)
  status = sendmail.close()
except:
  print "something went wrong:", sys.exc_type, sys.exc_value
else:
  exitcode = status >> 8
  signal = status & 0xFF
  print "sendmail exit code %d (killed by signal %d)" % (exitcode, signal)


If you really care about error messages from sendmail you should probably
go for the popen2 and select modules. But I've never used popen2.

cg.





More information about the Python-list mailing list