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.
- i need to pass arguments from the shell to Python.
- 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,6983 gold badges23 silver badges32 bronze badges
asked Dec 9, 2015 at 5:46
Abdul Manaf
5,01311 gold badges57 silver badges99 bronze badges
3 Answers 3
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
answered Dec 9, 2015 at 6:13
Ali Nikneshan
3,51231 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Abdul Manaf
thanks ali. this code is working fine. but i need to return a string value. how it will be possible?
Ali Nikneshan
you should capture python result: a=`python python/pythonScript1.py "test"``; echo $a will print what you print in python code
zhangboyu
In my case, sys.exit(0) doesn't return anything and the shell script stops as well. But print(0) works well. What happens in my case?
Ali Nikneshan
@zhangboyu , I guess you use ' instead of `
zhangboyu
@AliNikneshan I really used `
|
Pass command line arguments to shell script to Python like this:
python script.py 1ドル 2ドル 3ドル
Print the return code like this:
echo $?
answered Dec 9, 2015 at 6:02
coffee-converter
9774 silver badges13 bronze badges
Comments
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
answered Feb 24, 2022 at 22:14
Samuel
9,1389 gold badges51 silver badges42 bronze badges
1 Comment
bgrupczy
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. scaler.com/topics/exit-in-python geeksforgeeks.org/…
default