如何在python脚本中设置环境变量

如何在python脚本中设置环境变量

问题描述:

我正在使用 SCONS 构建工具.
我无法使用在 python 脚本中初始化的环境变量.

i am using SCONS Construction tool.
i am unable to use the environment variable which is initialized in python script.

在我的项目中,用户可以更改一些变量以使用编译器.

In My project USER can change some variables to work with the compiler.

为此,我们有 2 个文件.

For that we have 2 files.

  • 配置文件
  • 构造

Config.py 包含所有变量,例如 Include 目录、CFLAGS、CPPPDEFINES 等.因此,在这里我们可以设置一些变量.我需要在 Sconstruct 文件中使用的那些变量.在 config.py 中,我设置了一个如下所示的变量

Config.py is having all the variables which are like Include directories, CFLAGS , CPPDEFINES etc. So, Here we can set some variables. Those variables i need to use in Sconstruct file. In config.py i set a variable like below

SCONS_INC = "Include files"
os.environ["SCONS_INC"] = SCONS_INC

我需要在 Sconstruct 文件中使用这些变量.代码是

I need to use those variables in Sconstruct File. The code is

env["CPPPATH"] = os.environ["SCONS_INC"] 

但我收到了一个类似未定义变量 SCONS_INC 的错误.

But I am getting an error like Undefined variable SCONS_INC.

如何做到这一点?

SCons 默认不使用被调用的环境,这是为了确保无论你的环境有什么配置,你都可以重现构建.

SCons by default does not use the invoked environment, this is to make sure that you can reproduce the build no matter which configurations your environment have.

环境变量存储在键 ENV 下的 scons 环境中,因此您可以像这样访问一般环境变量:

The environment variables are stored within the scons environment under the key ENV so you access the general environment variables like this:

env = Environment()
variable = env['ENV']['SomeVariable']
env['ENV']['SomeVariable'] = SomeValue

我理解你的问题,就像你需要在 SCons 中使用 python 脚本中设置的变量一样.为此,您需要结合使用您描述的两种方法来传输它们.

I understand your question like you need to use variables set in the python script within SCons. To do this you need to transfer them using the two method you describe in combination.

env = Enviroment()
python_variable = os.environ['SomeVariable']
env['ENV']['SomeVariable'] = python_variable

不过,我可能会推荐其他控制构建的方法,这样您就不必费心转移环境变量.恕我直言,使用参数更简单.参数只是一个由调用 scons 生成的字典,所以当你说:

I would however perhaps recommend other ways of controlling the build, so you do not have to go with the hassle of transferring environment variable. IMHO using arguments are simpler. The arguments are simply a dict that are generated by the invocation of scons, so when you say:

scons -D some_argument=blob

您可以通过简单的方式获得该参数:

You can get that argument by simply:

some_variable = ARGUMENTS["some_argument"]

当然我不知道你为什么需要环境变量,所以这对你来说可能完全无关.

Of course I do not know why you need the environment variables, so this might be completely irrelevant for you.