Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value from python script to shell script

I am new in Python. I am creating a Python script that returns a string "hello world." And I am creating a shell script. I am adding a call from the shell to a Python script.

  1. i need to pass arguments from the shell to Python.
  2. i need to print the value returned from Python in the shell script.

This is my code:

shellscript1.sh

#!/bin/bash # script for testing clear echo "............script started............" sleep 1 python python/pythonScript1.py exit 

pythonScript1.py

#!/usr/bin/python import sys  print "Starting python script!" try:     sys.exit('helloWorld1')  except:      sys.exit('helloWorld2')  
like image 715
Abdul Manaf Avatar asked Dec 09 '15 05:12

Abdul Manaf


People also ask

How do I pass the output of a Python script to a shell variable?

You ask: How do I pass the output of a Python script to a shell variable? You start your Python script from a shell script (or also from an interactive shell) and use command substitution. For POSIX shells (e.g. GNU Bash, Korn shell, etc), you could use: #!/bin/sh.

Can I use Python in shell script?

Python allows you to execute shell commands, which you can use to start other programs or better manage shell scripts that you use for automation. Depending on our use case, we can use os. system() , subprocess. run() or subprocess.

Can we use return in shell script?

return command is used to exit from a shell function. It takes a parameter [N], if N is mentioned then it returns [N] and if N is not mentioned then it returns the status of the last command executed within the function or script.


2 Answers

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 
like image 167
Ali Nikneshan Avatar answered Sep 18 '22 14:09

Ali Nikneshan


Pass command line arguments to shell script to Python like this:

python script.py $1 $2 $3 

Print the return code like this:

echo $? 
like image 45
aaron_world_traveler Avatar answered Sep 16 '22 14:09

aaron_world_traveler