kip_price
kip_price

Reputation: 91

Give input to a python script from a shell?

I'm trying to write a shell script that will run a python file that takes in some raw input. The python script is essentially along the lines of:

def main():
    name=raw_input("What's your name?")
    print "Hello, "+name
main()

I want the shell script to run the script and automatically feed input into it. I've seen plenty of ways to get shell input from what a python function returns, or how to run a shell from python with input, but not this way around. Basically, I just want something that does:

python hello.py
#  give the python script some input here
#  then continue on with the shell script.

Upvotes: 5

Views: 25957

Answers (2)

Fredrick Brennan
Fredrick Brennan

Reputation: 7357

There's really no better way to give raw input than sys.stdin. It's cross platform too.

import sys
print "Hello {0}!".format(sys.stdin.read())

Then

echo "John" | python hello.py # From the shell
python hello.py < john.txt # From a file, maybe containing "John"

Upvotes: 5

mgilson
mgilson

Reputation: 309831

Do you mean something like:

python hello.py <<EOF
Matt
EOF

This is known as a bash HERE document.

Upvotes: 9

Related Questions