One-liners in Python? Not a chance!

When I recently told someone that I often use awk when I write shell scripts, the comment, together with a raised eyebrow, was "So, anyone's still using this?!" I felt a bit old-fashioned, and when today I caught myself writing a one-liner in awk I decided to give Python a chance (yes, I know, there is also Perl, but I never give Perl another chance :-/).

The problem I wanted to solve was splitting a comma-separated list into a whitespace separated list of words that I could use for iteration in the shell. The awk one-liner I came up with after 1 minute was this:

echo a,b,c | awk '{split($0,parts,",");for (i in parts) {print parts[i]}}'

I imagined the corresponding Python program would look something like this:

import sys
for part in sys.stdin.read().split(","):
    print part

I spent maybe half an hour trying to figure out how to convert this into a one-liner, then I gave up. Incredible but true: The issue here is Python's indentation-defines-scope syntax. This syntax makes it virtually impossible to write any kind of control structure (i.e. something that uses if, for or while) in a single line.

The bad (or sad) thing about this is that it makes Python a lot less useful for quick-and-dirty shell scripting. The good thing is... awk lives on, and I feel a lot less old-fashioned :-)

Comments

one liner

from sys import stdin; print('\n'.join(a for a in stdin.read().split(','))

hah!

Thanks for that! Not that I am too happy about the syntax, but that's probably me, I am just not used to Python. Two remarks (in case someone else is reading this):

  1. There should be an additional closing parenthesis, otherwise Python barfs and says "SyntaxError: unexpected EOF while parsing"
  2. The following one-liner prints 4 lines instead of the expected 3, the last line is an empty line.
echo a,b,c | python -c "from sys import stdin; print('\n'.join(a for a in stdin.read().split(',')))"