简体   繁体   中英

Command line arguments parsing in ballerina similar to argparse in python

Is there any way to parse the command line arguments in ballerina? From what I have seen you can use only positional arguments. What I would like to do is something like this:

//main.bal
public function main(string? name, int? age) returns error? {
    if (name is string && age is int) {
        io:println("Hello " + name);
        io:println("Age " + age.toString());
    }
}

And then run the programm as follows:

bal run main.bal -- --name John --age=18

But this does not work, because it takes "--name" as the first positional argument and "John" as the second positional argument. So it throws an error:

error: invalid argument 'John' for parameter 'age', expected integer value

And if I run it as follows then it runs:

bal run main.bal -- John 18

The arguments can be passed by name if they are specified for options.

If the arguments are part of a record like

public type Details record {|
    string name?;
    int age?;
|};

and the main function has an included record parameter of this type to specify options

public function main(*Details f) {
    string? name = f?.name;
    int? age = f?.age;

    if name is string && age is int {
        io:println("Hello ", name);
        io:println("Age ", age);
    }
}

it can be run as follows

$ bal run main.bal -- --name=Jo --age=25

This was introduced in Swan Lake Alpha5 and the release note provides more information - https://ballerina.io/downloads/swan-lake-release-notes/swan-lake-alpha5/#improved-command-line-argument-parsing .

You can use configurable support for this. Check this example:

import ballerina/io;

configurable string name = ?;
configurable int age = ?;

public function main() returns error? {
    io:println("Hello " + name);
    io:println("Age " + age.toString());
}

Then while running you can provide values as following:

bal run main.bal -- -Cname="Ballerina" -Cage=5

The result is

Hello Ballerina
Age 5

Check this guide for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM