运行 通过 python 的系统命令未产生相同的输出

Running a system command through python not producing the same output

好吧,这件非常奇怪的事情发生了。我正在 运行ning 一个 python 脚本来生成一些输出并将其存储在一个文件中。在脚本的最后,我使用 subprocess 模块通过 postfix 发送邮件。我运行

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

这会执行但会给出消息 mail: Null message body; hope that's ok,即使文件有内容也是如此。我收到一封没有正文(但主题正确)的电子邮件。

当我直接运行命令时:

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

我在电子邮件中收到了文件的内容。

这里出了什么问题?它完全搞砸了我的脑袋!

不出所料,这是一个非常愚蠢的错误(这些是最好的错误)。

我没有刷新我的文件句柄并发送邮件。所以消息正文是空的。现在我正在使用

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

而且我收到的邮件有正文。呸!