What is the equivalent of
ls | perl -ne 'print "test $_"'
in python
I just want to pass the result of a unix command to the python interpreter.
5
There is no direct equivalent. The main thing you are making use of is the -n
option, which provides an implicit loop around the given code. You are also using a variable that the loop implicitly sets. With Python, you’d have to supply a similar loop explicitly.
One possibility that doesn’t require you to embed literal newlines into the Python script (but is otherwise not idiomatic Python) is
... | python -c 'import sys; [print(f"test {x}", end="") for x in sys.stdin]'
Abuse of the list comprehension is to avoid the need to write something like
... | python -c 'import sys
for x in sys.stdin:
print(f"test {x}", end="")
'
Also unlike Perl (which allows multiple -e
options to build up a script piecewise), Python allows only one -c
option; everything following that is considered an argument to the -c
script itself, not additional arguments for python
to process.