简体   繁体   中英

How do I set environment variables in a new Python Process

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM