views:

357

answers:

6
python -c "for x in range(1,10) print x"

I enjoy python one liners with -c, but it is limited when indentation is needed.

Any ideas?

+12  A: 
python -c "for x in range(1,10): print x"

Just add the colon.

To address the question in the comments:

How can I make this work though? python -c "import calendar;print calendar.prcal(2009);for x in range(1,10): print x"

python -c "for x in range(1,10): x==1 and __import__('calendar').prcal(2009); print x;"

As you can see it's pretty gross. We can't import before the loop. To get around this we check if x is at the first iteration in the loop, if so we do the import.

More examples here.

Stephen Pape
@Luis: you need to add the colon anyway, even when not running from a command line.
nosklo
How can I make this work though?python -c "import calendar;print calendar.prcal(2009);for x in range(1,10): print x"
Luis
+1 just for that link!
Ben Blank
@Luis: there are limits on one-liners; and you've found the limit. Good work.
S.Lott
+3  A: 

Not a python script, but might help:

for /L %i in (1, 1, 10) do echo %i
dirkgently
+1  A: 

Don't you just want this?

python -c “for x in range(1,10): print x”

Zoredache
+3  A: 
python -c "for x in range(1,10): print x"

Remember the ":" !!

dwc
+1  A: 

Here's a solution that doesn't require putting a statement after the colon, which is not considered very highly.

python2 -c "print '\n'.join([str(x) for x in range(1,10)])"

What's more pythonic than a list comprehension!

TokenMacGuy
Disclaimer: I don't actually like this any better. I put statements after colons more than I should. Probably because I have a widescreen monitor.
TokenMacGuy
A: 
python -c 'print "\n".join(map(str, range(1,10)))'

but what's wrong in a "real" python script? (you know, a foo.py launched via "python foo.py") If you really like one-liners, I suggest perl :)

ZeD