Python short-trick to load any local directory as python module in script

Hi Folks,

As DevOps Engineer/ Python Developer, we often have been asked to write script which should perform some task through Azure DevOps or Jenkins.

As we all know These DevOps tools Azure DevOps/ Jenkins etc have been hosted upon some VM instances in Any one of Cloud Provider for high availability & other benefits.

While you as developer write python scripts and consume your local(custom) python packages and modules it gets loaded in script but the same thing don’t work upon these DevOps tools, reason “path not found , module not available”.

Even though those python packages / modules are available in another directory where script resides. So here I am sharing a short trick to solve that problem. Hope it may help you.

E.g : Suppose you have written test.py script and executing from your local path.

cmd (local path)> python test.py

import logging
from pathlib import Path
# add this section to your script before listing your cutom modules
script_parent_package_path = Path(__file__).resolve().parents[1] # get one level above folder path
# add current directory
if script_parent_package_path:
sys.path.append(str(script_parent_package_path))y
# load your custom modules# write your code

in snippet , Path(__file__).resolve().parents[1] is return the parent folder path where your script and custom packages reside.

While script gets executed, it loads all custom packages you have mentioned in script and the script will perform all the task as per workflow you have written in script.

Please give claps to this post if you like it. Also please follow me. I would love to be connected with you.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
SaurabhG

I am an enthusiastic learner. Always want to challenge my last learning & keep hunting for new learning. about.me/saurabh.gangrade