Sunday, April 3, 2011

How can I make this one-liner work in DOS?

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?

From stackoverflow
  • 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.

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

    for /L %i in (1, 1, 10) do echo %i
    
  • Don't you just want this?

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

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

    Remember the ":" !!

  • 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.
  • 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 :)

0 comments:

Post a Comment