One line command line filter
tjreedy at udel.edu
Tue Sep 6 00:21:56 CEST 2011
On 9/5/2011 4:38 PM, Jon Redgrave wrote:
> It seems unreasonably hard to write simple one-line unix command line
> filters in python:
> eg: ls | python -c "<something> print x.upper()"
> to get at sys.stdin or similar needs an import, which makes a
> subsequent for-loop illegal.
> python -c "import sys; for x in sys.stdin(): print x"<<- SyntaxError
> Am I missing something obvious?
The doc says "-c <command>
Execute the Python code in command. command can be one or more
statements separated by newlines,"
However, I have no idea how to put newlines into a command-line string.
Changing '; ' to '\n' does not work, at least not in Windows. The '\n'
is passed on to Python as 2 chars, and the '\' is seen as the
line-continuation char and the 'n' as illegal following it. Will a *nix
shell 'cook' the string and convert '\n' to a literal newline before
passing it to Python?
For *nix, I would expect the <<EOF mechanism to work. Have you tried that?
That said, Python is designed for named multiple-statement programs,
just as it is designed for named multiple-statement functions. Or it is
designed for interactive work.
The following works:
dir | python -c "while True: print(input())"
except that it finishes with an error traceback:
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
Perhaps tolerable if Python is at the end of the pipe, not otherwise.
> Is there a better solution - if not is this worth a PEP?
PEPs have to propose a concrete solution, preferably with some previous
discussion. I take is that your proposal would be to add another builtin
means to access stdin.
Terry Jan Reedy
More information about the Python-list