sending commands to the unix shell

Chris Rebert clp2 at rebertia.com
Tue Oct 12 02:41:44 EDT 2010


On Mon, Oct 11, 2010 at 7:30 PM, Rodrick Brown <rodrick.brown at gmail.com> wrote:
> Trying to do something very trivial why is it failing

It would have been helpful if you had specified in exactly what way(s)
they were failing.

> I've tried three approaches
>     1. os.system("/bin/cat %s | /bin/mail -s \'connection error\' %s" %
> (logFile,notifyList))
>     2. os.system("/bin/mail -s \'connection error\' %s < %s" %
> (notifyList,logFile))

os.system() is outmoded. So skipping to the modern approach...

>     3. p1 = sp.Popen(["/bin/cat",], stdout=sp.PIPE)
>         p2 = sp.Popen(["/bin/mail", "-s", "error", notifyList],
> stdin=p1.stdout, stdout=sp.PIPE)

Let's pipe the file directly instead of using cat. It's simpler and faster.
I will assume notifyList is, despite its name, actually a
correctly-formatted string.
I will also assume that the last character in the file referred to by
logFile is a newline (/bin/mail apparently requires this).

import subprocess as sp
payload = open(logFile, 'r')
returncode = sp.call(["/bin/mail", "-s", "error", notifyList],
stdin=payload, stdout=sp.PIPE, stderr=sp.STDOUT)
if returncode:
    # then there was some sort of error

On the gripping hand, you should consider just using smtplib to send
the email directly from Python and thus avoid having to run an
external command at all:
http://docs.python.org/library/smtplib.html

Cheers,
Chris
--
South Park dot stdout; Hah.
http://blog.rebertia.com



More information about the Python-list mailing list