1 回答

TA贡献1820条经验 获得超2个赞
如果您解释一下此构造的目标,那就更好了。也许可以简化?
该脚本的问题在于,该脚本echo转到了stdin由(...)符号启动的封装外壳的。但是在shell内,stdin被重新定义为Heredoc 用管道输送到 Python,因此它会从stdin读取脚本,该脚本现在来自 Heredoc 管道。
所以你尝试这样的事情:
echo -e "Line One\nLine Two\nLine Three" | python <(cat <<HERE
import sys
print "stdout hi"
for line in sys.stdin:
print line.rstrip()
print "stdout hi"
HERE
)
输出:
stdout hi
Line One
Line Two
Line Three
stdout hi
现在,该脚本是从读取的/dev/fd/<filehandle>,因此stdin可以由echo的管道使用。
解决方案#2
还有另一种解决方案。脚本可以发送到Python的标准输入是这里的文档,但随后必须将输入管道重定向到另一个文件描述符。为此fdopen(3),必须在脚本中使用类似的函数。我不熟悉Python,所以我显示一个 佩尔 例子:
exec 10< <(echo -e "Line One\nLine Two\nLine Three")
perl <<'XXX'
print "stdout hi\n";
open($hin, "<&=", 10) or die;
while (<$hin>) { print $_; }
print "stdout hi\n";
XXX
在这里,echo重定向到文件句柄10,该文件句柄在脚本内部打开。
但是echo可以fork使用另一个将其移除(-1 )Heredoc:
exec 10<<XXX
Line One
Line Two
Line Three
XXX
多行脚本
或简单地使用以下-c选项输入多脚本:
echo -e "Line One\nLine Two\nLine Three"|python -c 'import sys
print "Stdout hi"
for line in sys.stdin:
print line.rstrip()
print "Stdout hi"'
添加回答
举报