Eli Berkowitz
Eli Berkowitz

Reputation: 349

Directory-specific environment variable

I have a directory system like this:

|- /root/path
  |- config.json
  |- script1.py
  |- a
    |- script2.py
  |- b
    |- c
      |- d
         |- script3.py

script1.py, script2.py, and script3.py both use the "root path" (/root/path) to operate. Right now I have "/root/path" hard coded into the py files. Say, however, I moved or renamed the root path; I would have to go back into all of those scripts and change the root path.

I know one way to 'solve' this is to give the .py files a sense of their relative position, so for example script3.py reads from ../../../config.json. However, at some point this becomes really tedious especially if there's a lot of scripts being set up.

I'm wondering if there's a way of saying "any script that is in this directory that is run from wherever will have access to some environment variable". The "from wherever" is italicized because without this restriction I think direnv would work fine.

Upvotes: 0

Views: 268

Answers (1)

Prem
Prem

Reputation: 85

You can define a variable such as my_root = '/root/path' and define all other paths in your script relative to my_root. For example,

config_json_path = os.path.join(my_root, 'config.json')

Upvotes: 1

Related Questions