如何在bash stdin / stdout流管道中插入内联(也许是heredoc?)

我最近在python中做了大量工作,希望能够使用它的功能来代替shell / bash内置程序/ shell脚本。


所以对于这样的shell管道:


echo -e "Line One\nLine Two\nLine Three" | (cat<<-HERE | python

import sys

print 'stdout hi'

for line in sys.stdin.readlines():

  print ('stdout hi on line: %s\n' %line)

HERE

) | tee -a tee.out

打印的全部是“ stdout hi”


这里需要解决什么?


呼如林
浏览 176回答 1
1回答

DIEA

如果您解释一下此构造的目标,那就更好了。也许可以简化?该脚本的问题在于,该脚本echo转到了stdin由(...)符号启动的封装外壳的。但是在shell内,stdin被重新定义为Heredoc 用管道输送到 Python,因此它会从stdin读取脚本,该脚本现在来自 Heredoc 管道。所以你尝试这样的事情:echo -e "Line One\nLine Two\nLine Three" |&nbsp; python <(cat <<HEREimport sysprint "stdout hi"for line in sys.stdin:&nbsp; print line.rstrip()print "stdout hi"HERE)输出:stdout hiLine OneLine TwoLine Threestdout 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<<XXXLine OneLine TwoLine ThreeXXX多行脚本或简单地使用以下-c选项输入多脚本:echo -e "Line One\nLine Two\nLine Three"|python -c 'import sysprint "Stdout hi"for line in sys.stdin:&nbsp; print line.rstrip()print "Stdout hi"'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python