简体   繁体   English

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

[英]how to set environment variable in python script

i am using SCONS Construction tool. 我正在使用SCONS施工工具。
i am unable to use the environment variable which is initialized in python script. 我无法使用在python脚本中初始化的环境变量。

In My project USER can change some variables to work with the compiler. 在“我的项目”中,USER可以更改一些变量以与编译器一起使用。

For that we have 2 files. 为此,我们有2个文件。

  • Config.py 配置文件
  • Sconstruct 构造

Config.py is having all the variables which are like Include directories, CFLAGS , CPPDEFINES etc. So, Here we can set some variables. Config.py具有所有变量,例如包含目录,CFLAGS,CPPDEFINES等。因此,在这里我们可以设置一些变量。 Those variables i need to use in Sconstruct file. 这些变量我需要在Sconstruct文件中使用。 In config.py i set a variable like below 在config.py我设置如下变量

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

I need to use those variables in Sconstruct File. 我需要在Sconstruct File中使用这些变量。 The code is 该代码是

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

But I am getting an error like Undefined variable SCONS_INC. 但是我收到了类似未定义变量SCONS_INC的错误。

How to do this? 这个怎么做?

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. 默认情况下,SCons不使用调用的环境,这是为了确保无论环境具有哪种配置,都可以重现构建。

The environment variables are stored within the scons environment under the key ENV so you access the general environment variables like this: 环境变量存储在scons环境中,位于键ENV下,因此您可以像这样访问常规环境变量:

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

I understand your question like you need to use variables set in the python script within SCons. 我理解您的问题,就像您需要在SCons中使用python脚本中设置的变量一样。 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

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调用生成的dict,因此当您说:

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. 当然,我不知道为什么需要环境变量,因此这可能与您完全无关。

I once had a similar need, where the compiler was looking for a certain Env variable that hadnt been set. 我曾经有过类似的需求,其中编译器正在寻找尚未设置的某个Env变量。 I was able to solve this problem as follows: 我能够解决此问题,如下所示:

env = Environment()
env['ENV']['THE_VARIABLE'] = 'SomeValue'

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

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