Reading stdin from inline python in bash

Can someone explain why this short bash / python command does not output "hello"

$ echo hello | python - <<END import sys for line in sys.stdin: print line END 

If I save my python script file to a file, this command works as expected.

In script.py

 import sys for line in sys.stdin: print line END 

$ echo "hello" | python script.py

"Hi"

+5
source share
3 answers

Because python << END redirects stdin to read the program. You also cannot read a line from echo to stdin.

+4
source

The reason it doesn't work is because you have conflicting redirects. echo | python echo | python trying to associate standard input with a pipe from echo , and python - <<HERE trying to associate standard input with a document here. You cannot have both. (This document wins.)

However, there really is no reason to want to connect the script itself to standard inputs.

 bash$ echo hello | python -c ' > import sys > for line in sys.stdin: > print line' hello 
+4
source

Oh boy, that makes sense! I struggled with this for the last hour, and finally, I understand, thank you both.

To provide a working alternative for the source program, you can do something like this:

 $ echo hello | python <(cat <<END import sys for line in sys.stdin: print line END ) 

But be careful! If you put this in a file, the final END should touch the left gutter (no spaces). Otherwise, it will not analyze the โ€œunexpected end of the file when looking for a suitable characterโ€ or something similar (in fact, it took me two more hours to find out when I started answering this question).

Explaining the code, what happens is that <<END ... END in combination with <(cat ...) creates a file (in /dev/fd ) so that it can be passed to python as if it were a real file. Quoting this explanation <(...) :

Replaces the process. It feeds the output of the command to FIFO, which can be read as a regular file.

There is another interesting answer on this question here .

+2
source

Source: https://habr.com/ru/post/1208375/


All Articles