[Tutor] bash heredoc and python
David Lowry-Duda
david at lowryduda.com
Thu Apr 27 16:14:21 EDT 2023
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?
- DLD
More information about the Tutor
mailing list