【问题标题】:Running a system command through python not producing the same output通过python运行系统命令不会产生相同的输出
【发布时间】:2015-10-23 12:06:24
【问题描述】:

好的,所以这件不可思议的事情发生了。我正在运行一个 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

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

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

【问题讨论】:

  • 首先,确保使用 sudo 启动 Python 脚本。另外,您是否尝试过拆分传递给 subprocess.call 的列表? (['sudo', 'mail', '-s', "Subject", person@example.com, '
  • 我认为使用 sudo 运行它不会有帮助。你看我还在收到邮件,只是正文不见了。
  • 在标准输入上将文本文件通过管道传输到mail 会更安全一些,并且有望让您完全避免使用sudo,并消除对shell=True 的需要。

标签: python subprocess postfix-mta


【解决方案1】:

正如预期的那样,这是一个完全愚蠢的错误(这些是最好的)。

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

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

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

猜你喜欢
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 2020-02-01
  • 2020-02-07
  • 2011-05-25
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
相关资源
最近更新 更多