40

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') 
aschultz
  • 1,658
  • 3
  • 20
  • 30
Abdul Manaf
  • 4,933
  • 8
  • 51
  • 95

3 Answers3

62

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
Ali Nikneshan
  • 3,500
  • 27
  • 39
10

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

python script.py $1 $2 $3

Print the return code like this:

echo $?
coffee-converter
  • 967
  • 4
  • 13
3

You can also use exit() without sys; one less thing to import. Here's an example:

$ python
>>> exit(1)
$ echo $?
1

$ python
>>> exit(0)
$ echo $?
0
Samuel
  • 8,063
  • 8
  • 45
  • 41
  • The exit() is defined in site.py and it works only if the site module is imported so it should be used in the interpreter only. https://www.scaler.com/topics/exit-in-python/ https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/ – bgrupczy May 16 '23 at 01:03