How to pass stdin to python script
I’d like to pass input from a shell command over to a python script in an alias that uses a shell command.
test.py:
import sys
print(sys.argv)
the alias
alias foo='echo $(python test.py $1)'
since $ python cd_alias_test.py hello
would print all the args: ['test.py', 'hello']
I’d expect this alias to do the same. However its stdout is
['test.py'] hello
Which means that the input string is being passed to stdin and not the script’s arguments.
How I achieve the intended effect?
Your question is confusingly worded, but I seems you just want to execute an alias passing a parameter to your script.
I think this is what you want.
alias runtest='python test.py'
As otherwise mentioned, shell functions can be preferable to aliases — allowing for less trivial arg handling.
So in this example:
function runtest() { python test.py "$1" ; }
alias test='echo $(python test.py $1)'
$1
is not defined in an alias, aliases aren’t shell functions; they’re just text replacement; so your test hello
gets expanded to echo $(python test.py ) hello
, which gets expanded to echo ['test.py'] hello
.
If you want a shell function, write one! (and don’t call your function or alias test
, that name is already reserved for the logical evaluation thing in your shell).
function foo() { echo $(python test.py $1) }
foo hello
But one really has to wonder: Why not simply make test.py
executable (e.g. chmod 755 test.py
) and include the #!/usr/bin/env python3
first line in it? Then you can just run it directly:
./test.py hello darkness my old friend