Launching a python script via a symbolic link

Mike picture Mike · Oct 28, 2013 · Viewed 8.6k times · Source

I have an executable python script that exists in a "scripts" directory, and there's a symbolic link to that script (used to launch the file) in a root directory. Something like:

.
├── scripts
│   ├── const.py
│   ├── fops.py
│   ├── i_build.py
│   └── i_Props.ini
└── build_i -> scripts/i_build.py

I would like to be able to launch/run my scripts via:

python build_i

From the root directory. The i_build.py script will attempt to open i_Props.ini and do some magic based on what's in there.

The issue is that when the i_build.py script is launched via the symlink in the root directory, the i_build.py script will look in the root directory for the other files (not the /scripts directory where i_build.py is stored).

The i_build.py file has the props file location as:

PROP_FILE = "i_Props.ini"

and attempts to open that, and then fails. I do not want to hardcode a path for obvious reasons.

A quick test adding os.getcwd() in the main file confirms my suspicions that it thinks the CWD is the root directory, and a check of __file__ says it is the symbolic link ("build_i").

Is there anything I can do to have python use the destination of the symbolic like for the __file__ name and CWD?

Answer

Ronald Portier picture Ronald Portier · Nov 5, 2013

You can use __file__, but you have to take some precautions to get the real path:

import os
base_dir = os.path.dirname(os.path.realpath(__file__))

Then load your other files / resources relative to base_dir:

some_subdir = 'my_subdir'
some_file = 'my.ini'

ini_path = os.path.join(base_dir, some_subdir, some_file)