add

How to embed python script in you bash shell script?

combining the power of bash & python scripting

unix tips and trciks

SO you want to reuse a python code which is already written in your bash script ?

Instead of writing the entire python code in shell script, you can embed python code inside the bash shell script using here doc.

First lets write a working python code.

To demonstrate, let me write a small piece of Python code that just simply gets the file properties of a given file name.


$cat runPythonBash.py
import os.path
import time
path="./somefile.txt"
print('File Name :',path)
print('Access time of file :', time.ctime(os.path.getatime(path)))
print('Modified time of file :', time.ctime(os.path.getmtime(path)))
print('Change time of file :', time.ctime(os.path.getctime(path)))
print('Size of file :', os.path.getsize(path))

Lets test the code by creating a dummy text file using touch command.

$ touch somefile.txt

$ ls
runPythonBash.py somefile.txt

$ python3 runPythonBash.py
File Name : ./somefile.txt
Access time of file : Sat Apr 18 19:19:34 2020
Modified time of file : Sat Apr 18 19:19:34 2020
Change time of file : Sat Apr 18 19:19:34 2020
Size of file : 0

Now lets get into actual work by writing a small shell script that makes use of HERE doc as shown below:

$ ls
runPythonBash.py runPythonCode.sh somefile.txt

contents of Shell script :


$cat runPythonCode.sh


#!/bin/bash
function readFileAttributes
{
python3 - <<HERE
import datetime
import os.path
import time
varDate = datetime.datetime.now()
print (varDate)
path="./somefile.txt"
print('File Name :',path)
print('Access time of file :', time.ctime(os.path.getatime(path)))
print('Modified time of file :', time.ctime(os.path.getmtime(path)))
print('Change time of file :', time.ctime(os.path.getctime(path)))
print('Size of file :', os.path.getsize(path))
HERE
}
fileAttr=$(readFileAttributes)
echo "File attributes are : $fileAttr"

Now run the shell script and validate the output.

$ ./runPythonCode.sh
File attributes are :
2020-04-18 19:51:20.728757
File Name : ./somefile.txt
Access time of file : Sat Apr 18 19:19:34 2020
Modified time of file : Sat Apr 18 19:19:34 2020
Change time of file : Sat Apr 18 19:19:34 2020
Size of file : 0

HERE doc is a great handy tool when we want to switch into another program/tool mode.

Written by Ramesh Metta

Next Article