Home > Net >  Making the original linked excutable directory accessible
Making the original linked excutable directory accessible

Time:06-13

I have a python script program.py and I wanted to have access to it everywhere in the system. Therefore, I used chmod x and used a hard link to put it in the /somewhere/bin/.

This successfully made the program.py executable anywhere, but at the same time I lost access to the original directory where the program resides /original/dir/program.py.

There is a configuration file in the original directory, in a folder: /original/dir/configurations/cfg.txt and I want to also access it everywhere in the system, example: program.py configurations/cfg.txt. How can I achieve this?

CodePudding user response:

You can't do it with a hard link (because a hard link is indistinguishable from any other hard link of the same file, including the original name; for all practical purposes, it is an "original" name), but if you use a symlink, you can drill through it to find the real directory with os.path.realpath.

from os.path import dirname, join, realpath

realdir = dirname(realpath(__file__))
cfgfile = join(realdir, 'configurations', 'cfg.txt')

or with pathlib, using Path.resolve for similar effect:

from pathlib import Path

realdir = Path(__file__).resolve().parent
cfgfile = realdir / 'configurations' / 'cfg.txt'

CodePudding user response:

It seems kind of overkill to need to access the folder anywhere in the system. Why not just have the user provide the command-line argument of the configuration they want (e.g. python program.py cfg1.txt) and then have some basic logic in the program to get the file:

import os
cfgArg = # string command line argument
cfgPath = os.path.join('configurations', cfgArg)
  • Related