0

I am stuck on an environment variables mismatch.

I run a Python script on Windows 10 via a program called NSSM.

At runtime, I do the following:

  1. Load in parameters from a text file
  2. Put its contents into the environment using os.environ.setdefault(name, value).
  3. Try to load in environment variables using os.environ[name]

Result:any variables I added do not show up.

I am not sure why the variables I add aren't available. Can you please tell me what I am doing wrong?

A starting point is that NSSM uses environment variables from Windows HKLM registry: source (see bottom). I am not sure if this is the reason os.environ cannot see relevant variables.

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
  • 1
    Please provide a simplified example that reproduces the problem. I have no problem using `os.environ.setdefault` to add environment variables for the current process and child processes, in both Python 2.7 and 3.7, so there must be something particular in what you're doing here, or some misunderstanding about what you're trying to do. – Eryk Sun May 23 '19 at 02:24

2 Answers2

1

I've had trouble using os.environ.setdefault in the past as well. Instead of that, say you were trying to add to the PATH environment variable, do the following:

os.environ['PATH'] += ";" + the_path_to_the_file

EDIT:

Also, for creating a new variable:

os.environ['new_var'] = 'text'
Recessive
  • 1,780
  • 2
  • 14
  • 37
1

Well it turns out that my problem was outside of the scope of this question. @Recessive and @eryksun thank you both for answering, it put me "onto the scent".

It turns out my problem was using Python pathlib's Path.home().

  • When running via command prompt, it pulled HOMEPATH environment variable.
  • When running via NSSM, it pulled USERPROFILE environment variable.

This discrepancy in Path.home() was the real problem. It wasn't finding the environment variables because NSSM was looking in a totally different folder.

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119