3

Starting with for works

root@messagerie-secours[10.10.10.19] /home/serveur # python -c "for x in xrange(10):print x;"
0
1
2
3
4
5
6
7
8
9
root@messagerie-secours[10.10.10.19] /home/serveur # 

If you have for in the middle, it's a syntax error :

root@messagerie-secours[10.10.10.19] /home/serveur # python -c "a=2;for x in xrange(10):print x;"
  File "<string>", line 1
    a=2;for x in xrange(10):print x;
          ^
SyntaxError: invalid syntax
root@messagerie-secours[10.10.10.19] /home/serveur #

Is it possible to get rid of that syntax error ?

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
ychaouche
  • 4,922
  • 2
  • 44
  • 52

5 Answers5

3

Woo, plenty of solutions! here some others:

python -c 'print "\n".join(map(str, xrange(10)))'

python <<"EOF"
for x in range(10):
  print x
EOF

echo $'a=12\nfor x in range(a): print x' | python
bufh
  • 3,153
  • 31
  • 36
  • Nice ! also, thrid one can also be written like this (tested, working) : `python -c $'a=2\nfor x in xrange(1,10):\n print x'` – ychaouche Jul 29 '15 at 10:30
2

Writing mutlitple statements and control structures in one line is not a good idea, since Python heavily depends on indentation.

You can place your code correctly indented in a loop.py file and you should be fine.

#!/usr/bin/nev python

a = 2
for x in xrange(10):
    print x

Run it with python loop.py.

If you really need the program written in the command line, try this:

root@messagerie-secours[10.10.10.19] /home/serveur # python -c "
> a = 2
> for x in range(10) :
>     print x
> "
redevined
  • 772
  • 2
  • 6
  • 23
2

It depends on the underlying OS. It will be easy on an Unix-like :

python -c "a=5
for i in range(a): print i"

correctly gives

0
1
2
3
4

on my FreeBSD system, because Unix shells allow newline between quotes.

But AFAIK, it is not possible in Windows CMD shell.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You can use itertools.count which will yields 0, 1, 2, ....

With __import__, you can do it in one line:

python -c 'for x in __import__("itertools").count(): print x'
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

The following works for me on Python 2.7:

python -c "exec('\n'.join(['a=42', 'for x in xrange(10):', '  print x', 'print a']))"

Giving the output:

0
1
2
3
4
5
6
7
8
9
42
Martin Evans
  • 45,791
  • 17
  • 81
  • 97