Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value from a shell script in a python script

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??

like image 984
user2475677 Avatar asked Jul 25 '26 10:07

user2475677


1 Answers

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
like image 126
Ashwini Chaudhary Avatar answered Jul 27 '26 23:07

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!