1

I have a python script that could up end up in different directories on different servers. My script has sys.path.insert line where it look's for libraries and also looks for config.ini file in the same directory as the script. I want to be able to run the script with the full path.

example.py:

#!/usr/local/bin/python3.6
import sys, getopt, configparser
sys.path.insert(0, '../lib/')
from myFunctions import mySendmail, remoteFileChkSum, sendfile
...
def main():
    config = configparser.ConfigParser()
    # username and encrupted passwords are in config.ini
    # keys for encryption are in .keys
    config.read('config.ini')
    config.read('.keys')

On some hosts the file is in /export/apps/bin/ with the lib folder in /export/apps/lib. On other hosts it's in /export/home/ray/bin with the lib folder in /export/home/ray/lib.

What is the best practice so I can run the script from anywhere on any host?? Should I find the directory/location of the script at the beginning and perform a os.chdir('<DIR>')?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ravi M
  • 71
  • 7
  • You could get the current working directory as follows `cwd = os.getcwd()` @Ravi – Vishnudev Krishnadas Jul 07 '21 at 17:03
  • @Vishnudev that gives me the current working directory. But I need dir where the script is located since the references to lib and config file are in reference to that – Ravi M Jul 07 '21 at 17:20
  • 1
    The best current practice is to make your module installable, and have `pip` install its data files to a system-dependent location which can be retrieved from the package's metadata. For a quick and dirty solution, looks like you can use `pathlib.Path(__file__).parent() / 'lib' / 'config.ini'` – tripleee Jul 07 '21 at 17:50
  • If you start the program from the commandline and if you use `sys.argv` the the first argument will be the path where the program is running, see [this question](https://stackoverflow.com/questions/4117530/sys-argv1-meaning-in-script) – Papageno Jul 07 '21 at 17:54
  • 1
    You can get the directory of the currently running script with `os.dirname(__file__)` — which is a very common way to do this sort of thing. – martineau Jul 07 '21 at 18:12

1 Answers1

0

This is what I did and it works.

import os, sys
script_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_dir)

sys.path.insert(0, '../lib/')
from myFunctions import mySendmail, remoteFileChkSum, sendfile

Ravi M
  • 71
  • 7