Executing multi-line statements in the one-line command-line?
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.
Solution 1:
You could do
echo -e "import sys\nfor r in range(10): print 'rob'" | python
or without pipes:
python -c "exec(\"import sys\nfor r in range(10): print 'rob'\")"
or
(echo "import sys" ; echo "for r in range(10): print 'rob'") | python
or @SilentGhost's answer / @Crast's answer
Solution 2:
this style can be used in makefiles too (and in fact it is used quite often).
python - <<EOF
import sys
for r in range(3): print 'rob'
EOF
or
python - <<-EOF
import sys
for r in range(3): print 'rob'
EOF
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).
Solution 3:
The issue is not actually with the import statement, it's with anything being before the for loop. Or more specifically, anything appearing before an inlined block.
For example, these all work:
python -c "import sys; print 'rob'"
python -c "import sys; sys.stdout.write('rob\n')"
If import being a statement were an issue, this would work, but it doesn't:
python -c "__import__('sys'); for r in range(10): print 'rob'"
For your very basic example, you could rewrite it as this:
python -c "import sys; map(lambda x: sys.stdout.write('rob%d\n' % x), range(10))"
However, lambdas can only execute expressions, not statements or multiple statements, so you may still be unable to do the thing you want to do. However, between generator expressions, list comprehension, lambdas, sys.stdout.write, the "map" builtin, and some creative string interpolation, you can do some powerful one-liners.
The question is, how far do you want to go, and at what point is it not better to write a small .py
file which your makefile executes instead?