Command Line Arguments in Modelica
Command-line arguments are a common way to parameterize execution of programs. For example, runScript("hello.mos")
uses runScript
and "hello.mos"
arguments to execute a Modelica script.
model CommandLineArguments
import Modelica.Utilities.Streams;
import Modelica.Utilities.System;
function main
input String[:] args;
algorithm
// System.getArguments() provides access to command-line arguments.
// Note that the first value in this array is the path to the program,
// and args[2:end] holds the arguments to the program.
args := System.getArguments();
argsWithProg := args;
argsWithoutProg := args[2:end];
// You can get individual args with normal indexing.
arg := if size(args, 1) >= 4 then args[4] else "";
Streams.print(String(argsWithProg));
Streams.print(String(argsWithoutProg));
Streams.print(arg);
end main;
equation
main(System.getArguments());
end CommandLineArguments;
To experiment with command-line arguments, you’ll need to use a Modelica tool that supports command-line execution. The exact method may vary depending on your tool, but it might look something like this:
$ omc CommandLineArguments.mo -r=CommandLineArguments a b c d
{"CommandLineArguments.mo","a","b","c","d"}
{"a","b","c","d"}
c
In Modelica, we use the System.getArguments()
function to access command-line arguments. The first element is typically the name of the script or model being executed, and the rest are the actual arguments passed.
Note that Modelica doesn’t have a direct equivalent to Go’s os.Args
, so we’re using System.getArguments()
which is part of the Modelica Standard Library. The exact behavior might differ slightly depending on the Modelica tool you’re using.
Also, Modelica doesn’t have a built-in main()
function like many other languages. Instead, we’ve created a main()
function within our model and called it in the equation section. This is one way to structure a Modelica program that needs to perform a sequence of operations.
Next, we’ll look at more advanced ways to handle input parameters in Modelica models.