5

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.
3
  • 3
    echo "read this!" | python hello.py - what shell are we talking about anyway? Commented Feb 19, 2013 at 19:05
  • That looks like a UUOE (closely related to UUOC) Commented Feb 19, 2013 at 19:07
  • Also have a look at this answer on automated testing and stdin input in Python. Commented Feb 19, 2013 at 19:20

2 Answers 2

9

Do you mean something like:

python hello.py <<EOF
Matt
EOF

This is known as a bash HERE document.

Sign up to request clarification or add additional context in comments.

Comments

5

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"

4 Comments

the second one is a useless use of cat ... python hello.py < john.txt
@mgilson Indeed...old habits die hard.
I still do that (pretty frequently).
I can't actually change the python files: I'm grading for an intro CS class, and they aren't teaching sys. I'm just trying to save myself time so I'm not giving manually input to 94 students' python scripts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.