One line command line filter

Hans Mulder hansmu at xs4all.nl
Tue Sep 6 07:15:10 EDT 2011


On 6/09/11 01:18:37, Steven D'Aprano wrote:
> Terry Reedy wrote:
>
>> 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.
>
> I imagine that it depends on the shell you are using, but bash on Linux
> makes it simple: double quotes "..." are like Python's triple-quoted
> strings in that they can include newlines.

Single quotes in bash are more similar to triple quotes in Python, in
that some shell syntax is recognized within double quoted string, but
not within single quoted strings:

$ python -c 'import sys
print `sys.version`'
'2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) \n[GCC 4.2.1 (Apple Inc. 
build 5664)]'

$ python -c "import sys
 > print `sys.copyright`"
-bash: sys.copyright: command not found

When using single quotes, the `` are passed to Python, which interprets
them as a call to repr().  With double quotes, the shell interprets ``
as a sub-command.

> Other shells may be different.

Most *nix shells are similar to bash. The ones that are different
are csh and tcsh: they require a backslash before each newline:

$ tcsh
% ls f*.py | python -c 'import sys \
? print sys.stdin.read()'
filecmp.py
fileinput.py
fnmatch.py
formatter.py
fpformat.py
fractions.py
ftplib.py
functools.py
%

Sometimes you need two backslashes, one for csh and one for Python:

% python -c 'print "spam spam spam spam spam spam spam spam " \\
? "spam spam spam spam spam"'
spam spam spam spam spam spam spam spam spam spam spam spam spam
%

Hope this helps,

-- HansM







More information about the Python-list mailing list