问题
#!/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