[Tutor] bash heredoc and python

Mats Wichmann mats at wichmann.us
Thu Apr 27 16:31:48 EDT 2023


On 4/27/23 14:14, David Lowry-Duda wrote:
> I like to use python as a simple commandline calculator. I only just 
> learned that it's possible to do something like the following in bash
> 
> ```
> $ python <<EOF
> import math
> print('multiple lines')
> print(math.pi)
> ```
> 
> and python will happily run this. I had thought this wouldn't work, and 
> that python would instead complain that there was no file with some 
> amalgamated name.
> 
> I discovered this by an accident, but googling shows of course that this 
> isn't new or anything. I would have expected this to run with "python - 
> <<EOF" instead of "python <<EOF", as the `-` indicates to read from stdin.
> 
> So I opened up the python manpage to see about this, and saw nothing 
> there (not even about what `-` is supposed to mean!). Then I went to
> 
> https://docs.python.org/3/using/cmdline.html#command-line
> 
> to see if I could learn more, and I don't see much there either. There 
> is a somewhat cryptic remark: "In non-interactive mode, the entire input 
> is parsed before it is executed."
> 
> I guess python does something like: check to see if args were given, if 
> not then check for standard input and then run it noninteractively? Do 
> you think this is an intended behavior, or is this merely an 
> undocumented implementation detail?

Intended - and little to do with Python.

The shell syntax  <<  connects standard input to the following text 
stream (the here-document), instead of to the terminal.  So when Python 
opens, stdin is not a tty, and thus non-interactive.  Because that 
plumbing is set up by the shell as it's launching Python, there's no 
need for Python to be called with any special options.

For grins, if you like doing Python inline in your shell, consider a 
weird project called xonsh.





More information about the Tutor mailing list