我最近在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被重新定义为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的stdin,因为这是文档,但是输入管道必须重定向到另一个文件描述符.为此,必须在脚本中使用fdopen(3)like函数.我对python不熟悉,所以我展示了perl示例:
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),使用另一个heredoc:
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"'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。