Search code examples
pythonsubprocesspostfix-mta

Running a system command through python not producing the same output


Ok so this incredibly weird thing happened. I am running a python script to produce some output and store it in a file. At the end of the script, I am using subprocess module to send a mail via postfix. I run

subprocess.call(['sudo mail -s "Subject" person@example.com < /path/to/file.txt'], shell=True)

This executes but gives the message mail: Null message body; hope that's ok even though the file has contents. And I receive an email with no body (but correct subject).

When I run the command directly:

sudo mail -s "Subject" person@example.com < /path/to/file.txt

I receive the contents of the file in the email.

What is going wrong here? It has totally messed up my head!


Solution

  • As expected, it was an utterly stupid error (These are the best ones).

    I wasn't flushing my file handle and sending the mail. So the message body was empty. Now I am using

    file_name.flush()
    file_name.close()
    subprocess.call(['sudo mail -s "Subject" person@example.com < /path/to/file.txt'], shell=True)
    

    and the mail I receive has the body. Phew!