Running Python from a Bash Script

Running Python from a Bash Script

Sometimes, it isn't best to do everything via Python. In my case, due to multi-factor authentication, I couldn't send emails via Python and instead was able to use bash to run the python code and send an email if it failed.

Video version:

You can get the full code in the Gitlab repo here:


Bash

#!/bin/bash
python3 $1 $2

python_status=$?

current_date=`date "+%D %T"`

msg="A script has ran to error:  

Server: $HOSTNAME

Script Name: $1 

Time: $current_date"

echo "$python_status"
echo "$msg"

#msg="The following Script ran to error: $1 at $current_date"
#if [ $python_status -ne 0 ]; then
##    echo "$msg" | mailx -s "Script Failure"  vash@email;
#fi;
run_script.sh

To execute this code, you will need to make it executable. You can right click on the run_script.sh file and click properties.

In the permissions tab, make sure to check the 'Is executable' box.

Check the Is Executable box in the file permission screen.
Check the Is Executable box in the file permission screen.

Alternately, cd to the directory this is in and run chmod +x run_script.sh . You should not need elevated privilages if this script is in your home directory.


Python

import sys

print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument sent:', str(sys.argv[1]))
test.py

This section of the bash script is all about assigning some variables:

python3 $1 $2

python_status=$?

current_date=`date "+%D %T"`

The important thing here is python3 $1 $2 what that does is runs the command python3 then loads in 2 command line arguments.

In our case, we are inserting the name of the python script test.py and hi as a second argument.

The $? is special, it will receieve the status of our script. So in this case a 0 or 1. 0 means the script ran to success, 1 means it did not.

The full call for this run will be ./run_script.sh test.py hi

hi will be passed to the python script. It will be shown in the output due to line 3 print ('Argument sent:', str(sys.argv[1]))

Since the bash script only takes 2 arguments (the first is the name of the python script) we cannot get any other command line arugments.

extra command line argument doesn't work
Added third command line argument

Here's an example of the code running as expected: