如何插入一个内联(定界符也许?)python脚本到bash的标准输入/输出流管道 [英] How to insert an inline (heredoc maybe? ) python script into a bash stdin/stdout streaming pipeline

查看:504
本文介绍了如何插入一个内联(定界符也许?)python脚本到bash的标准输入/输出流管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在做的工作相当数量的在Python,并希望能够udse其功能,而不是外壳/ bash的内建命令/ shell脚本。

I have recently been doing fair amount of work in python and would like to be able to udse its features instead of shell/bash builtins / shell scripting.

因此​​,对于一个管道是这样的:

So for a shell pipeline like this:

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

所有这一切都印就是标准输出喜

All that is printed is "stdout hi"

有什么需要固定在这里?

What needs to be fixed here?

谢谢!

推荐答案

如果您解释一下什么是这个建筑你的目标会更好。也许这可以简化。

It would be better if You explain what is your goal with this construction. Maybe it could be simplified.

问题是这个脚本的回声变成由<​​code>(...)符号。但内壳标准输入被重新定义为定界符管道到蟒蛇,因此它从标准输入读取脚本,这是目前来自定界符管的问题。

The problem is with this script that the echo goes to the stdin of the encapsulating shell initiated by the (...) notation. But inside the shell stdin is redefined as the heredoc piped to python, so it reads the script from stdin, which is now comes from the heredoc pipe.

所以你想是这样的:

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

文件句柄&GT; ,所以标准输入可用于

现在的脚本是从的/ dev / FD / LT与阅读由回声的管道。

Now the script is read from /dev/fd/<filehandle>, so stdin can be used by the echo's pipe.

解决方案#2

有另一种解决方案。该脚本可以被发送到蟒蛇的标准输入作为这里,是-文档,但随后的输入管道已被重定向到另一个文件描述符。对于这个一个 fdopen(3)之类的函数在脚本中使用。我不熟悉的蟒蛇,所以我表现出 perl的例如:

There is another solution. The script can be sent to python's stdin as here-is-the document, but then the input pipe has to be redirected to another file descriptor. For this an fdopen(3) like function has to be used in the script. I'm unfamiliar with python, so I show a perl example:

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

下面的回声被重定向到文件句柄10,这是打开脚本中。

Here the echo is redirected to the file handle 10, which is opened inside the script.

回声部分可以删除(-1 ),使用其他的定界符

But the echo part can be removed (-1 fork), using an other heredoc:

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

多SCIPRT

或者干脆进入使用 -c 选项脚本多重:

Or simply enter a multile script using the -c option:

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

这篇关于如何插入一个内联(定界符也许?)python脚本到bash的标准输入/输出流管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆