【问题标题】:mailx does not work with subprocessmailx 不适用于子进程
【发布时间】:2014-11-27 17:53:14
【问题描述】:

我可以通过在命令行中手动输入此命令来发送电子邮件:

 echo "test email" | mailx -s "test email" someone@somewhere.net

我在我的收件箱中收到了电子邮件,工作正常。

但它不适用于子进程:

import subprocess
recipients = ['someone@somewhere.net']
args = [
    'echo', '"%s"' % 'test email', '|',
    'mailx',
    '-s', '"%s"' % 'test email',
] + recipients
LOG.info(' '.join(args))
subprocess.Popen(args=args, stdout=subprocess.PIPE).communicate()[0]

没有错误,但我从未在收件箱中收到电子邮件。

有什么想法吗?

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    | 字符必须由 shell 解释,而不是由程序解释。您当前执行的操作类似于以下命令:

    echo "test email" \| mailx -s "test email" someone@somewhere.net
    

    即不让shell处理|并将其作为字符串传递给echo。

    你有两种方法可以解决这个问题:

    • 使用子进程(echomailx)从 python 中显式启动 2 个命令,并将echo 的输出通过管道传输到mailx 的输入
    • 在子进程中使用shell=True参数

    第二种解决方案更简单,会导致:

    import subprocess
    recipients = 'someone@somewhere.net'
    cmd = ('echo "%s" | mailx -s "%s"' % ('test email', 'test email')) + recipients
    LOG.info(cmd)
    subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
    

    但是您应该在命令中使用完整路径以避免可能导致安全问题的PATH 环境问题(您最终会执行不需要的命令)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2018-03-09
      • 2021-08-06
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多