Skip to content

Interpret '-' as a new optional argument in a quoted string #401

@ojamond

Description

@ojamond

In the program I am working on, I would like to define an optional argument whose values are then forwarded to another library (PETSc). PETSc CLI options start with a -. The I would like to use my program with something like:

./myprog --petsc-options  '-ksp_view -ksp_type preonly'

The problem is that argparse (version 3.2) interpret the first - of -ksp_view as a new optional argument and so detect no value for the argument petsc-options.

Here is a basic illustrating snippet:

#include <argparse/argparse.hpp>
#include <iostream>
#include <string>
#include <vector>

int main(int argc, const char **argv) {

  argparse::ArgumentParser program("myprog");

  std::vector<std::string> petsc_options;

  program.add_argument("--petsc-options")
      .help("PETSc options")
      .nargs(1)
      .action([&](std::string value) {
        std::cout << "catch arg:" << value << std::endl;
        petsc_options.push_back(value);
      });

  try {
    program.parse_args(argc, argv);
  } catch (const std::exception &e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  }

  for (auto v : petsc_options) {
    std::cout << "PETSc options: " << v << std::endl;
  }

  return 0;
}
./myprog --petsc-options  '-ksp_view -ksp_type preonly'

gives:

Error: Too few arguments for '--petsc-options'.

Further -in the quoted string are not interpreted by argparse as the first one:

./myprog --petsc-options  'ksp_view -ksp_type preonly'

gives:

catch arg:ksp-view -ksp_type preonly
PETSc options: ksp-view -ksp_type preonly

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions