Here I am giving some examples to demonstrate how to call Python from a bash shell script in Linux/Unix environments.
Calling Python from Bash Shell Examples
In the following example, it will call the Python program which will access the variable (var_name) declared in the bash shell environment.
Example 1. pytest1.sh
#!/bin/bash
export var_name="Vinish"
python - <<END
import os
print "Hello ", os.environ['var_name']
END
Test
chmod +x pytest1.sh
./pytest1.sh
Output
Hello Vinish
Below shell script is using a function to call the Python program to get the current date and time value.
Example 2. pytest2.sh
#!/bin/bash
function current_date_time
{
python - <<START
import datetime
value = datetime.datetime.now()
print (value)
START
}
# calling function directly
current_date_time
# getting function output into a variable
Date_Time=$(current_date_time)
echo "Date and time now = $Date_Time"
Test
chmod +x pytest2.sh
./pytest2.sh
Output
2019-04-24 12:52:01.026882
Date and time now = 2019-04-24 12:52:01.183022
Calling Python script (.py) from the shell script.
Example 3. pytest3.sh
#!/bin/bash
# contents of the below pytest.py file is print "Hello World!"
python pytest.py
Test
chmod +x pytest3.sh
./pytest3.sh
Output
Hello World!
Thanks for the tip. I have a python script that accepts several positional and optional arguments. I would like to run several of those like in a batch file in windows, obviously withing a bash script.