mailx 不适用于子进程 [英] mailx does not work with subprocess
问题描述
我可以通过在命令行中手动输入此命令来发送电子邮件:
I can send email by typing this command manually into the command line:
echo "test email" | mailx -s "test email" someone@somewhere.net
我在收件箱中收到了电子邮件,工作正常.
I get the email in my inbox, works.
虽然它不适用于子进程:
It does not work with subprocess though:
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]
没有错误,但我从未在收件箱中收到电子邮件.
No errors, but I never receive the email in my inbox.
有什么想法吗?
推荐答案
|
字符必须由 shell 解释,而不是由程序解释.您当前执行的操作类似于以下命令:
The |
character has to be interpreted by the shell, not by the program. What you currently do looks like the following command :
echo "test email" \| mailx -s "test email" someone@somewhere.net
那就是没有shell处理|
并将其作为字符串传递给echo.
That is do not have the shell process the |
and pass it as a string to echo.
你有两种方法可以解决这个问题:
You have two ways to fix that :
- 使用子进程(
echo
和mailx
)从 python 显式启动 2 个命令,并将echo
的输出通过管道传输到的输入mailx
- 在子进程中使用
shell=True
参数
- explicitely start 2 commands from python with subprocess (
echo
andmailx
) and pipe the output fromecho
to the input ofmailx
- use
shell=True
parameter in subprocess
第二种解决方案更简单,会导致:
The second solution is simpler and would result in :
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
环境问题,这会导致安全问题(你最终会执行不需要的命令)
But you should use full path in commands to avoid PATH
environment problems that can result in security problems (you end in executing unwanted commands)
这篇关于mailx 不适用于子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!