简体   繁体   English

如何在新的 Python 进程中设置环境变量

[英]How do I set environment variables in a new Python Process

I'm making a new process in Python using the "spawn" multiprocessing context我正在使用"spawn"多处理上下文在 Python 中创建一个新进程

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.我希望 Python 运行时执行此操作,以便确保在我的任何 Python 代码运行之前设置这些环境变量。

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.您可以通过os package 访问和设置环境变量。

import os

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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