Environment Variables in Modelica

Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in Modelica.

model EnvironmentVariables
  import Modelica.Utilities.System;
  import Modelica.Utilities.Strings;

equation
  // To set a key/value pair, use System.setEnvironmentVariable
  // To get a value for a key, use System.getEnvironmentVariable
  // This will return an empty string if the key isn't present in the environment
  System.setEnvironmentVariable("FOO", "1");
  Modelica.Utilities.Streams.print("FOO: " + System.getEnvironmentVariable("FOO"));
  Modelica.Utilities.Streams.print("BAR: " + System.getEnvironmentVariable("BAR"));

  // Use System.getEnvironmentVariables to list all key/value pairs in the environment
  // This returns a vector of strings in the form "KEY=value"
  // You can use Strings.find to split them and get the key and value
  // Here we print all the keys
  Modelica.Utilities.Streams.print("");
  for i in 1:size(System.getEnvironmentVariables(), 1) loop
    String e = System.getEnvironmentVariables()[i];
    Integer equalPos = Strings.find(e, "=");
    String key = Strings.substring(e, 1, equalPos - 1);
    Modelica.Utilities.Streams.print(key);
  end for;
end EnvironmentVariables;

Running the model shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running model picks that value up. In Modelica, you would typically set environment variables before running the simulation, either through the simulation environment or the operating system.

FOO: 1
BAR: 2
...

Note that the exact method of setting and getting environment variables may vary depending on the Modelica simulation environment you’re using. Some environments might provide more direct ways to interact with environment variables.