From fd04c036139f150be79801e5fd3b49086e5d7263 Mon Sep 17 00:00:00 2001 From: Ander Punnar Date: Fri, 16 Oct 2020 13:42:16 +0300 Subject: [PATCH] add parent dir to module search path only when importing fails --- bin/cdist | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/bin/cdist b/bin/cdist index 2ce40ae0..66ccbb5a 100755 --- a/bin/cdist +++ b/bin/cdist @@ -25,13 +25,19 @@ import logging import os import sys -cdist_bin = os.path.abspath(__file__) -if os.path.islink(cdist_bin): - cdist_bin = os.readlink(cdist_bin) -cdist_dir = os.path.abspath(os.path.join(os.path.dirname(cdist_bin), os.pardir)) -sys.path.insert(0, cdist_dir) +# try to import cdist and if that fails, then add this file's parent dir to +# module search path and try again. additionally check if this file is +# symlinked, so user can symlink this file to, for example, ~/.local/bin. +try: + import cdist +except ModuleNotFoundError: + cdist_bin = os.path.abspath(__file__) + if os.path.islink(cdist_bin): + cdist_bin = os.readlink(cdist_bin) + cdist_dir = os.path.abspath(os.path.join(os.path.dirname(cdist_bin), os.pardir)) + sys.path.insert(0, cdist_dir) + import cdist -import cdist import cdist.argparse import cdist.banner import cdist.config