标签:heredoc python bash redirect heredoc python heredoc python python perl heredoc
我最近在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"'
标签:heredoc,python,bash,redirect,heredoc,python,heredoc,python,python,perl,heredoc 来源: https://codeday.me/bug/20190831/1778576.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。