为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

呼如林 2021-03-30 08:58:34
我最近在python中做了大量工作,希望能够使用它的功能来代替shell / bash内置程序/ shell脚本。所以对于这样的shell管道:echo -e "Line One\nLine Two\nLine Three" | (cat<<-HERE | pythonimport sysprint 'stdout hi'for line in sys.stdin.readlines():  print ('stdout hi on line: %s\n' %line)HERE) | tee -a tee.out打印的全部是“ stdout hi”这里需要解决什么?
查看完整描述

1 回答

?
DIEA

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"'


查看完整回答
反对 回复 2021-04-01
  • 1 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号