-2

Shell script: Hello.sh

#!/bin/bash
echo "Enter your name: "
read name
echo "Hello $name"

I want to invoke Hello.sh from within python and fill variable "name" non-interactively. How can it be done?

1
  • This is the same as your previous question. Commented Mar 21, 2013 at 15:26

2 Answers 2

3

You should be able to Popen.communicate with the subprocess:

from subprocess import Popen,PIPE
p = Popen(['bash','./Hello.sh'],stdin=PIPE,stderr=PIPE,stdout=PIPE)
stdout_data,stderr_data = p.communicate("Hello World!\n")
Sign up to request clarification or add additional context in comments.

Comments

1

+1 on the pipes. A more "shell-ish" approach would be:

import subprocess

the_name = 'the_name'
myproc = subprocess.Popen(['echo %s | bash Hello.sh' % the_name], stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell=True)
out, err = myproc.communicate()

print out

3 Comments

with shell=True, I believe that it is preferred to pass a string, not a list.
@mgilson when shell=True: If args is a string, the string specifies the command to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. So it doesn't really matter.
Thanks it worked the way I wanted it to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.