2

I have a python script which requires a value from a shell script.

Following is the shell script (a.sh):

#!/bin/bash
return_value(){
  value=$(///some unix command)
  echo "$value"
}

return_value

Following is the python script:

Import subprocess
answer = Subprocess.call([‘./a.sh’])
print("the answer is %s % answer")  

But its not working.The error is "ImportError : No module named subprocess ". I guess my verison (Python 2.3.4) is pretty old. Is there any substitute for subprocess that can be applied in this case??

2 Answers 2

9

Use subprocess.check_output:

import subprocess
answer = subprocess.check_output(['./a.sh'])
print("the answer is {}".format(answer))

help on subprocess.check_output:

>>> print subprocess.check_output.__doc__
Run command with arguments and return its output as a byte string.

Demo:

>>> import subprocess
>>> answer = subprocess.check_output(['./a.sh'])
>>> answer
'Hello World!\n'
>>> print("the answer is {}".format(answer))
the answer is Hello World!

a.sh :

#!/bin/bash
STR="Hello World!"
echo $STR
Sign up to request clarification or add additional context in comments.

4 Comments

thanks ashwini for the answer.. The statement inside the python script is not actually a print statment but a cvs command. I had simplified it just for the sake of asking. So in that case can we use {} for interpolating the answer variable or we need to use %s ???
@user2475677 str.format is called new-style string formatting, if you're using string formatting only then both options are fine.
Thanks a lot ashwini, but I just realised that , my version of Python (2.3.4) is pretty old!! It does not have "subprocess"
What if this "a.sh" script is an interactive script which prompts user few question. In that case how can we capture those values in python script...?
3

use Subprocess.check_output instead of Subprocess.call.

Subprocess.call returns return code of that script.
Subprocess.check_output returns byte stream of script output.

Subprocess.check_output on python 3.3 doc site

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.