Python 子进程 : why won't the list of arguments work analogous to the full shell string?

标签 python subprocess

在此先感谢您的帮助。我是 python 的新手,但对脚本编写并不是特别陌生。我正在尝试运行一个简单的自动电子邮件程序,但电子邮件模块似乎在我们的系统上安装不正确(我没有 python 示例中描述的 75% 的功能,只有“message_from_string”和“message_from_file”) smtplib 对于我的需要来说过于复杂。

事实上,用简单的 bash 术语来说,我只需要:

/bin/email -s "blah" "recipients" < file.with.body.info.txt

或者,

echo "my body details" | /bin/email -s "blah" "recipients"

这样我就可以避免为了发送消息而写入文件。

我尝试使用子进程,无论是 call 还是 Popen,我最终能让事情正常工作的唯一方法是如果我使用:

subprocess.call('/bin/mail -s "blah" "recipients" < file.with.body.info.txt', shell=True)

我特别不喜欢这种方法的一些地方:

(1) 我无法将事物分成列表或元组,因为它应该工作,所以我失去了子进程的全部优势,据我所知,在保证事物安全方面。如果我尝试:

subprocess.call(['/bin/mail', '-s', subjVariable, recipVariable, '<', 'file.with.body.info.txt'], shell=True)

它会失败。同样,如果我尝试使用管道“|”而不是从文件中读取,它将失败。如果我使用“-cmd”而不是管道,它也会失败。 “失败”通常是它会读取“<”和“file.with.body.info.txt”,就好像它们是其他收件人一样。换句话说,无论我是否说“shell = True”,子进程都无法将调用中的特殊字符解释为它们本来的特殊字符。 “<”未被识别为来自文件等的输入,除非我将所有内容都保存在一个大调用中。

我理想中希望能够做的事情是这样的,因为它看起来更安全,也更灵活:

subprocess.call(['/bin/echo', varWithBody, '|', '/bin/mail', '-s', subjVariable, recipVariable,])

但似乎子进程根本不理解管道,我无法弄清楚如何在 python 后面将事物连接在一起。

有什么建议吗?欢迎提供所有帮助,但尝试解释如何使用“电子邮件”或“smtplib”模块除外。不管这个特定的应用程序是什么,我真的很想学习如何更好地使用子流程,这样我就可以将不同的程序结合在一起。我的理解是 python 在这方面应该相当不错。

谢谢!迈克

最佳答案

Python docs似乎涵盖了这种情况。

我可能会做类似下面的事情

from subprocess import *
readBody = Popen(["/bin/echo", varWithBody], stdout=PIPE)
mail = Popen(["/bin/mail", "-s", subjVariable, recipVariable], stdin=readBody.stdout, stdout=PIPE)
output = mail.communicate()[0]

关于Python 子进程 : why won't the list of arguments work analogous to the full shell string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4381673/

相关文章:

python - 使用循环创建命名元组实例作为数据库记录

Python:没有这样的文件或目录错误(Mac 用户)

python - 如何循环子图中的轴

python - Python 3.4 中的 UnboundLocalError

python - 在运行时与 python 子进程通信

python - 在 python 程序中运行 C 可执行文件

python - 名称错误 : name "webdriver" is not defined

Python:为子进程提供输入

python - 调用子进程时在文件名中引用空格

python - subprocess.call 在 Windows 上使用 cygwin 而不是 cmd