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.

import sys

the alias

alias foo='echo $(python $1)'

since $ python hello would print all the args: ['', 'hello']
I’d expect this alias to do the same. However its stdout is

[''] hello

Which means that the input string is being passed to stdin and not the script’s arguments.

How I achieve the intended effect?

Asked By: Brian Barry


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'

As otherwise mentioned, shell functions can be preferable to aliases — allowing for less trivial arg handling.

So in this example:

function runtest() { python "$1" ; }
Answered By: bxm
alias test='echo $(python $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 ) hello, which gets expanded to echo [''] 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 $1) }
foo hello

But one really has to wonder: Why not simply make executable (e.g. chmod 755 and include the #!/usr/bin/env python3 first line in it? Then you can just run it directly:

./ hello darkness my old friend
Answered By: Marcus Müller
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.