How do I set environment variables in a new Python Process

Viewed 795

I'm making a new process in Python using the "spawn" multiprocessing context

import multiprocessing
ctx = multiprocessing.get_context("spawn")

proc = ctx.Process(target=my_func)
proc.start()

I would like for this process to have a set of environment variables. Ideally I would specify this when creating the process, like this:

proc = ctx.Process(target=my_func, environment={"MY_NAME": "MY_VALUE"})

Is there some way to do this? I would like for the Python runtime to do this so that I can be ensured that these environment variables get set before any of my Python code runs.

2 Answers

If you are developing locally, you can export the variables into your local environment.

export MY_NAME='Matt'

You can access and set environment variables via the os package.

import os

print(os.environ)
os.environ['test'] = 1
Related