how to set environment variable in python script

守給你的承諾、 提交于 2019-12-25 01:49:52

问题


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.

For that we have 2 files.

  • 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. 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

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

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

But I am getting an error like Undefined variable SCONS_INC.

How to do this?


回答1:


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.

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

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

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.




回答2:


I once had a similar need, where the compiler was looking for a certain Env variable that hadnt been set. I was able to solve this problem as follows:

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


来源:https://stackoverflow.com/questions/16143971/how-to-set-environment-variable-in-python-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!