Why does python exit immediately when I pipe code in with echo but not with cat?

那年仲夏 提交于 2021-01-27 12:52:33

问题


#!/bin/bash

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

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

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

This outputs

Hello 1
Hello 2

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.

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


回答1:


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, 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 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.

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

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


来源:https://stackoverflow.com/questions/50935974/why-does-python-exit-immediately-when-i-pipe-code-in-with-echo-but-not-with-cat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!