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.
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')
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.
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.
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.
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
Pass command line arguments to shell script to Python like this:
python script.py $1 $2 $3
Print the return code like this:
echo $?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With