【问题标题】:How to insert an inline (heredoc maybe? ) python script into a bash stdin/stdout streaming pipeline如何将内联(可能是heredoc?)python脚本插入bash标准输入/标准输出流管道
【发布时间】:2013-06-10 11:06:22
【问题描述】:

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

这里需要解决什么问题?

谢谢!

【问题讨论】:

    标签: python bash redirect heredoc


    【解决方案1】:

    如果你能解释一下你对这个结构的目标是什么,那就更好了。也许可以简化?

    问题在于这个脚本echo 转到(...) 表示法启动的封装外壳的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/&lt;filehandle&gt; 读取的,所以stdin 可以被echo 的管道使用。

    解决方案 #2

    还有另一种解决方案。该脚本可以作为文档发送到 的标准输入,但随后必须将输入管道重定向到另一个文件描述符。为此,必须在脚本中使用类似 fdopen(3) 的函数。我对不熟悉,所以我举一个的例子:

    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 部分可以删除(-1 fork),使用另一个

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

    多行 SCIPRT

    或者直接使用-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"'
    

    【讨论】:

    • 也许你展示的 python
    • @javadba:但是为什么不使用python -c '...' 而不是&lt;(...) 版本呢?它更干净。或者,如果您需要在文件上创建脚本,您可以创建一个临时文件 (mktemp(1)) 并将脚本重定向到那里。
    • 我有多行脚本。如何使用 python -c 做到这一点,而外壳不会弄乱引号?
    • @javadba:我又添加了两个解决方案。最后一个只是使用-c
    猜你喜欢
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多