当我使用echo而不是cat传递代码时,为什么python立即退出? [英] Why does python exit immediately when I pipe code in with echo but not with cat?

查看:40
本文介绍了当我使用echo而不是cat传递代码时,为什么python立即退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/bin/bash

echo "print('Hello 1')" | python3

cat | python3 -u <<EOF
print('Hello 2')
EOF

echo "print('Hello 3')" | python3

此输出

Hello 1
Hello 2

在打印最终的 Hello 3 前,它会等我按Enter键.它还使用python的 -u 标志进行无缓冲输出.

It will wait for me to press enter before printing the final Hello 3. It does this also using python's -u flag for unbuffered output.

为什么对 cat 执行此操作,而不对 echo 执行此操作?

Why does it do this for cat but not for echo?

推荐答案

您没有使用cat.您使用的是Here-doc,而cat正在分别等待输入.只需删除 cat | ,然后重试即可.

You aren't using cat. You're using a here-doc, and cat is waiting for input separately. Just remove the cat | and try it again.

echo "print('Hello 1')" | python3
python3 -u <<EOF
print('Hello 2')
EOF
echo "print('Hello 3')" | python3

cat(您使用它的方式)会将其stdin通过管道传递到其stdout,成为管道另一侧上proc的stdin,但是您还定义了<< EOF here-doc优先,并忽略 cat 的空输出.

cat, the way you are using it, would pipe its stdin to its stdout, becoming the stdin for the proc on the other side of the pipe, but you also defined a <<EOF here-doc which takes precedence and ignores cat's empty output.

cat仍在等待 input .一旦您按回车键(通过OS Magic),它就会尝试并意识到没有人在听管道,然后退出.

cat is still waiting for input though. Once you hit return it (via OS magic) tries and realizes no one is listening on the pipe, and exits.

顺便说一句,您还可以使用here字符串,如下所示:

As an aside, you could also use a here-string, like this:

python3 <<< "print('Hello 2')"

这篇关于当我使用echo而不是cat传递代码时,为什么python立即退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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