How to access config variables in exec_command()s?

Question:

I have a configuration function in my wscript:

def configure(ctx):
  ctx.env.V1 = 123

def build(ctx):
    def myfun(task):
        return task.exec_command('echo VAR=${V1}')
    ctx.exec_command('echo VAR=${V1}')
    ctx.add_post_fun(myfun)

But in build and in myfun (both) V1 is not available (it’s substituted to an empty string). I can store and load my own ConfigSet. I know that V1 is available in rule, but it seems it is not available in exec_command().

What is the convenient way to do it? To access my config vars in exec_command() in build() body and in pre-/post- commands?

Asked By: RandomB

||

Answers:

The docs for waflib.Context.Context.exec_command() specify it as a thin wrapper around either waflib.Utils.run_prefork_process() or waflib.Utils.run_regular_process(), which is a thin wrapper over subprocess.Popen(**kwargs).communicate().

Both of these let you set env= as a keyword argument, though it needs to have only values which can actually be stored in the environment (which integers, like your 123, cannot).

Thus:

env_safe_dict = dict(os.environ) # start with parent environment
for k, v in ctx.env:             # add things from context environment
  env_safe_dict[k] = str(v)      # ...after converting them to strings
ctx.exec_command('echo VAR=${V1}', env=env_safe_dict)
Answered By: Charles Duffy

You can also use v1 = task.env.V1 in your task to build your command. And use python to be portable : print(f"VAR = {v1}")

Answered By: neuro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.