编程语言
首页 > 编程语言> > 如何将内联(heredoc may?)python脚本插入bash stdin / stdout流式传输管道

如何将内联(heredoc may?)python脚本插入bash stdin / stdout流式传输管道

作者:互联网

我最近在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”

需要修复什么?

谢谢!

解决方法:

如果您解释了这个结构的目标,那会更好.也许它可以简化?

问题在于这个脚本,echo返回到由(…)表示法启动的封装shell的stdin.但是在shell中,stdin被重新定义为管道到,所以它从stdin读取脚本,现在来自管道.

所以你尝试这样的事情:

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

还有另一种解决方案.脚本可以发送到的stdin,因为这是文档,但是输入管道必须重定向到另一个文件描述符.为此,必须在脚本中使用fdopen(3)like函数.我对不熟悉,所以我展示了示例:

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,文件句柄10在脚本内部打开.

但是可以删除echo部分(-1 fork),使用另一个

exec 10<<XXX
Line One
Line Two
Line Three
XXX

MULTILINE SCIPRT

或者只需使用-c选项输入multile脚本:

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

标签:heredoc,python,bash,redirect,heredoc,python,heredoc,python,python,perl,heredoc
来源: https://codeday.me/bug/20190831/1778576.html