Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform os.environ join in python?

I have a configuration of os.environ with default values (that cover 90% of my needs). I have a special application-framework-package, for example called SALOME, that does not provide package installation into system environment and tries to be self contained, it also requires use of special old technologies that rely on environmental variables thus sys.path and PYTHONPATH are not the only things it needs. I can get all variables it needs when it started calling os.environ inside an environment it creates. I can then serialize that os.environ dictionary.

I wonder how to apply a merge of os.environ I have on my currently running system with one I obtained by serializing?

like image 831
DuckQueen Avatar asked Mar 26 '16 04:03

DuckQueen


People also ask

How do I use environ in Python?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.

What is os environ in Python?

This module provides a portable way of using operating system dependent functionality. os. environ in Python is a mapping object that represents the user's environmental variables. It returns a dictionary having user's environmental variable as key and their values as value.

How do I set an environment variable in Python os?

With the environ dictionary variable value of the environment variable can be set by passing the key in the dictionary and assigning the value to it. With setdefault a default value can be assigned to the environment variable. Bypassing the key and the default value in the setdefault method.

How do you access an environment variable in Python?

Read Environment Variables in Python: The os module will require to import to read the environment variables. The os. environ object is used in Python to access the environment variable. The coder can set and get the value of any environment variable by using this object.


1 Answers

Let's assume you have done something like the following to serialize the environment:

import json
import os

with open('environ.json', 'w') as f:
    json.dump(dict(**os.environ), f)

You can now read those back like this (in another program)

import json
import os

with open('environ.json', 'r') as f:
    os.environ.update(json.load(f))

This will only add or change the current environment variables to match the saved ones, but any additional variables will remain.

If you want to update only specific variables by adding them (so for instance to add extra paths), you can do that explicitly:

with open('environ.json', 'r') as f:
    loadedenv = json.load(f)

pathvars = ['PATH', 'PYTHONPATH']

for p in pathvars:
    os.environ[p] += ':' + loadedenv[p]
like image 88
chthonicdaemon Avatar answered Nov 02 '22 01:11

chthonicdaemon