Multi-line commands with 'python -c'

Chris Angelico rosuav at gmail.com
Thu May 29 22:47:54 EDT 2014


On Fri, May 30, 2014 at 12:34 PM, Zachary Ware
<zachary.ware+pylist at gmail.com> wrote:
> You can always cheat:
>
> $ python -c 'exec("import os\nfor root, dirs, files in os.walk(\".\"):\n if
> len(dirs + files) == 1: print(root)")'
>
> Doesn't do much for being long and fiddly, though.

Not really, no! Heh. I wrote that in competition against a theoretical
solution involving shell commands and pipes and so on, with the
intention being that the Python version could be a simple shell
one-liner, just as the pipe version could. (The task: Find all
directories with exactly one subdirectory or file in them, not
counting dot and dot-dot. Python's os.walk() is pretty much perfect
for that.) I tried fiddling with __import__() rather than the import
statement, but it didn't really aid clarity much.

ChrisA



More information about the Python-list mailing list