I'm using Python with -c
to execute a one-liner loop, i.e.:
$ python -c "for r in range(10): print 'rob'"
This works fine. However, if I import a module before the for loop, I get a syntax error:
$ python -c "import sys; for r in range(10): print 'rob'"
File "<string>", line 1
import sys; for r in range(10): print 'rob'
^
SyntaxError: invalid syntax
Any idea how this can be fixed?
It's important to me to have this as a one-liner so that I can include it in a Makefile.
This variant is most portable for putting multi-line scripts on command-line on Windows and *nix, py2/3, without pipes:
(None of the other examples seen here so far did so)
Neat on Windows is:
Neat on bash/*nix is:
This function turns any multiline-script into a portable command-one-liner:
Usage:
Input was:
I've written a simple web page for this. You can paste your multiple-line code there and it is converted into a working single-line statement.
Python Single Line Converter
Your problem is created by the fact that Python statements, separated by
;
, are only allowed to be "small statements", which are all one-liners. From the grammar file in the Python docs:Compound statements can't be included on the same line with other statements via semicolons - so doing this with the
-c
flag becomes very inconvenient.When demonstrating Python while in a bash shell environment, I find it very useful to include compound statements. The only simple way of doing this is with heredocs.
Heredocs
Use a heredoc (created with
<<
) and Python's command line interface option,-
:Adding the
-
after<<
(the<<-
) allows you to use tabs to indent (Stackoverflow converts tabs to spaces, so I've indented 8 spaces to emphasize this). The leading tabs will be stripped.You can do it without the tabs with just
<<
:Putting quotes around
EOF
prevents parameter and arithmetic expansion. This makes the heredoc more robust.Critique of the accepted answer (and others)
This is not very readable:
Not very readable, and additionally difficult to debug in the case of an error:
Perhaps a bit more readable, but still quite ugly:
You'll have a bad time if you have
"
's in your python:Don't abuse
map
or list comprehensions to get for-loops:These are all sad and bad. Don't do them.
you could do
or w/out pipes:
or
or @SilentGhost's answer / @Crast's answer
just use return and type it on the next line:
this style can be used in makefiles too (and in fact it is used quite often).
or
in latter case leading tab characters are removed too (and some structured outlook can be achieved)
instead of EOF can stand any marker word not appearing in the here document at a beginning of a line (see also here documents in the bash manpage or here).