Using rust to open applications with environment variables

Hi all,

I am looking to use rust to open applications each with specific environment variables.
This would be the behaviour I am looking for:

my_rust_application.exe opens some_application_a.exe with variables variable_a variable_b

later,

my_rust_application.exe opens some_application_b.exe with variables variable_c variable_d

This would happen within a single run of my_rust_application.exe so it would require changing of variables midway through.
I have done this before in Python using virtual environments, but am uncertain where to start in rust

The relevant APIs for this are found in std::process. It works with a builder type called Command. [Create] (Command in std::process - Rust) one for the process you want to spawn, configure it via various methods to do things like passing arguments to the process, setting up how it's stdin and std out are to be defined, and in particular this also allows setting environment variables for the to-be-spawned process via the .env(key, val) method, then spawn it to run in the background, or perhaps use this method to run it synchronously, waiting for the process to finish and returning it's output.

2 Likes

I somehow had found the process module, but had missed the env method!
I'm guessing this means the environment variables stay contained to the constructed Command instance?

Yes indeed, the environment variables defined this way are only for the specific command. Also it will, by default "Inherit the current process’s environment", as the documentation specifies, which could be prevented e. g. by a call to env_clear.

That is perfect, thank you so much for the blazing fast response!
Have a good day/evening!