Home » Linux/Unix » Linux/Unix: Call Python From Bash Shell Script

Linux/Unix: Call Python From Bash Shell Script

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


export var_name="Vinish"
python - <<END
import os
print "Hello ", os.environ['var_name']


chmod +x pytest1.sh


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


function current_date_time
python - <<START
import datetime
value = datetime.datetime.now()
print (value)

# calling function directly


# getting function output into a variable


echo "Date and time now = $Date_Time"


chmod +x pytest2.sh


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

# contents of the below pytest.py file is print "Hello World!"
python pytest.py


chmod +x pytest3.sh


Hello World!

See also:

1 thought on “Linux/Unix: Call Python From Bash Shell Script”

  1. 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.

Comments are closed.