No loops in Python one-liners?

You can pass to the Python interpreter a one-liner, such as this one:
python -c 'print "hello"'

You can even do fancy things like this:
python -c "import os; print os.listdir('.')"

But it seems you cannot do loops within the line:
python -c "import os; for i in os.listdir('.'): print i"

However, you can do loops as long as it begins the line, as follows:
python -c "for i in range(10): print i; print i"

Interestingly, both “print i” above are considered to be inside the loop. I could not find any documentation anywhere regarding this limitation which seems to derive from how Python parses code lines.

Published by

Daniel Lemire

A computer science professor at the Université du Québec (TELUQ).

2 thoughts on “No loops in Python one-liners?”

  1. You can do loops in the form of list comprehensions.

    import sys,os,re,fileinput;a=[i[2] for i in os.walk(‘.’) if i[2]] [0];[sys.stdout.write(re.sub(‘at’,’op’,j)) for j in fileinput(a,inplace=1)]

    Careful with this one though, it will edit files on your path without prompt!

    Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax