Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read stdin from inlined python in bash

Tags:

python

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

"hello"

like image 600
will Avatar asked Dec 04 '14 18:12

will


People also ask

How do I run an inline from a bash shell in Python?

From the manual, man python : -c command Specify the command to execute (see next section). This termi- nates the option list (following options are passed as arguments to the command). Make sure "Hi" is in quotes.

What is %% bash in Python?

%%bash. Means, that the following code will be executed by bash. In bash $() means it will return with the result of the commands inside the parentheses, in this case the commands are: gcloud config list project --format "value(core.project)" Google cloud has its own command set to control your projects.

How do I run a Python script from the shell?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


2 Answers

The reason it's not working is that you have conflicting redirections. echo | python tries to tie standard input to the pipe from echo, while python - <<HERE tries to tie standard input to the here document. You can't have both. (The here document wins.)

However, there is really no reason to want to pipe the script itself on standard input.

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

Another solution might be to embed your data in a triple-quoted string within the script itself.

python <<\____
import sys
 
data = """
hello
so long
"""
 
for line in data.strip('\n').split('\n'):
   print line
____

The newlines between the triple quotes are all literal, but the .strip('\n') removes any from the beginning or the end. (You can't do that if you have significant newlines at the end, of course.)

The backslash before the here-document separator says to not perform any variable interpolation or command substitutions inside the here document. If you want to use those features, take it out (but then of course take care to individually escape any literal dollar signs or backticks in your Python code).

like image 135
tripleee Avatar answered Oct 02 '22 04:10

tripleee


Because python << END redirects stdin to read the program. You can't also read the line piped from echo on stdin.

like image 32
Elliott Frisch Avatar answered Oct 02 '22 06:10

Elliott Frisch