带有 heredocs 的 Python 子进程 [英] Python subprocess with heredocs
问题描述
我在玩 Python 的 subprocess 模块,尝试了几个例子,但我似乎无法让 heredoc 语句起作用.
I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work.
这是我玩的一个简单的例子:
Here is the trivial example I was playing with:
import subprocess
a = "A String of Text"
p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"])
当我运行上面的代码时出现以下错误:
I get the following error when I run the code above:
cat: <<DATA\nA String of Text\nDATA: No such file or directory
我做错了吗?这甚至可能吗?如果是这样,我将如何去做?
Am I doing it wrong? Is this even possible? If so how would I go about doing it?
更新
只是想说这不应该在真正的 Python 程序中执行,因为有更好的方法可以做到这一点.
Just wanted to say that this should never be performed in a real python program because there are better ways of doing this.
推荐答案
外壳heredoc"支持是外壳功能.subprocess.Popen
默认情况下不会通过 shell 运行您的命令,因此此语法肯定不起作用.
The shell "heredoc" support is a shell feature. subprocess.Popen
does not run your command through the shell by default, so this syntax certainly won't work.
然而,因为无论如何你都在使用管道,所以没有必要使用 shell 的 heredoc 支持.只需将您的字符串 a
写入您刚刚启动的进程的标准输入管道.无论如何,这正是 shell 对 heredoc 所做的.
However, since you're using pipes anyway, there isn't any need to use the heredoc support of the shell. Just write your string a
to the stdin pipe of the process you just started. This is exactly what the shell would do with the heredoc anyway.
您可以使用 Popen.communicate()
:
You can do this with Popen.communicate()
:
p.communicate(a)
communicate()
函数的返回值包含进程的输出(在两个流中,请参阅文档).
The return value of the communicate()
function contains the output of the process (in two streams, see the docs).
这篇关于带有 heredocs 的 Python 子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!