简体   繁体   中英

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 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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM