How to Return a Value from a Shell Script in a Python Script

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

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

return value from python script to shell script

You can't return message as exit code, only numbers. In bash it can accessible via $?. Also you can use sys.argv to access code parameters:

import sys
if sys.argv[1]=='hi':
print 'Salaam'
sys.exit(0)

in shell:

#!/bin/bash
# script for tesing
clear
echo "............script started............"
sleep 1
result=`python python/pythonScript1.py "hi"`
if [ "$result" == "Salaam" ]; then
echo "script return correct response"
fi

How to access python return value from bash script

Add a proper exit code from your script using the sys.exit() module. Usually commands return 0 on successful completion of a script.

import sys

def main():
print ("exec main..")
sys.exit(0)

and capture it in shell script with a simple conditional. Though the exit code is 0 by default and need not be passed explicitly, using sys.exit() gives control to return non-zero codes on error cases wherever applicable to understand some inconsistencies with the script.

if python foo.py 2>&1 >/dev/null; then
echo 'script ran fine'
fi

Grab return value from python with Shell Script

The

outputString=$(python swdl_number_receiver.py)

construction captures text sent to stdout. If you want your script to print information to the terminal then you can send it to stderr. Here's a simple demo.

qtest.py

import sys

print >>sys.stderr, "this is sent to stderr"
print "this is sent to stdout"

In Bash:

$ outputString=$(python qtest.py);echo "ok";echo "$outputString"

output

this is sent to stderr
ok
this is sent to stdout


Here's a version of qtest.py that works on Python 2 and Python 3:

from __future__ import print_function
import sys

print("this is sent to stderr", file=sys.stderr)
print("this is sent to stdout")

If you also want to capture the output sent to stderr in a variable, one way to do that, without changing "qtest.py", is to redirect stderr in Bash to a file:

$ outputString=$(python qtest.py 2>qtemp);echo "ok";stderrString=$(<qtemp);echo "STDOUT: $outputString";echo "STDERR: $stderrString"
ok
STDOUT: this is sent to stdout
STDERR: this is sent to stderr

A better way is to write directly to the file in Python:

qtest.py

from __future__ import print_function

with open("qtemp", "w") as f:
print("this is sent to qtemp", file=f)
print("this is sent to stdout")

bash

$ outputString=$(python qtest.py);echo "ok";qtempString=$(<qtemp);echo "STDOUT: $outputString";echo "qtemp: $qtempString"
ok
STDOUT: this is sent to stdout
qtemp: this is sent to qtemp

store return value of a Python script in a bash script

sys.exit(myString) doesn't mean "return this string". If you pass a string to sys.exit, sys.exit will consider that string to be an error message, and it will write that string to stderr. The closest concept to a return value for an entire program is its exit status, which must be an integer.

If you want to capture output written to stderr, you can do something like

python yourscript 2> return_file

You could do something like that in your bash script

output=$((your command here) 2> &1)

This is not guaranteed to capture only the value passed to sys.exit, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.

example:

test.py

print "something"
exit('ohoh')

t.sh

va=$(python test.py 2>&1)                                                                                                                    
mkdir $va

bash t.sh

edit

Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.

import script1
import script2

if __name__ == '__main__':
filename = script1.run(sys.args)
script2.run(filename)

Assign return value from python method to a variable in bash script

When you run this:

password_check=$(python password.py $password)

You are assigning the output of the password.py program to the password_check variable. The problem is that your password.py program doesn't produce any output: in fact, it never even runs the passwordCheck function, because your Python script never calls passwordCheck. Do make things work the way you're trying to use the script, you would need to modify it to (a) actually call the passwordCheck method and (b) print output instead of returning a value:

import re, sys
password = sys.argv[1]
def passwordCheck():
if re.match(r'(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])(?=.*[^A-Za-z0-9]).{14,}', password):
print 'okay'
return True
else:
print 'fail'
return False

passwordCheck()

And then check for that value in your shell script:

#!bin/sh

password="Testing@2134testing"
password_check=$(python password.py $password)
if [ "$password_check" == "okay" ];then
echo "Correct"
else
echo "Incorrect"
fi

Note that Python doesn't require a terminal ; on lines, so instead
of:

return False;

You should write:

return False

Additionally, in this example we're using the output of the script
to determine success/failure. A slightly more robust solution is to
use the exit code of the script instead. You can probably find a
variety of examples of using this technique if you explore online a
bit.

Capture return value from python script in command line

If the return value (which is unclear in the question) is a single line of output you could simply:

./script.py | tail -n 1

This will output the last line generated from the script (adjust the number as needed).

If you want to save to a file either > to create a new file, or >> to append to a file:

./script.py | tail -n 1 > file 

How to return result from python script to shell script?

You can do something like this:

{ a.py; result=$?; } || true
# the result of a.py is in $result

|| true temporarily disables set -e, and the $? special variable gets stored to $result before it gets overwritten by the next command.

The downside is that, if your script actually fails (e.g. by raising an exception), you won't notice that. A more robust solution would be to print the needed result and catch it as output, and print the other output to the standard error.



Related Topics



Leave a reply



Submit