Hello,
I’ve been working on some gvm-scripts with using argparse and up to this point everything was going great. As my scripts grow I would like to use subparsers to tidy them up by making them multi use. For example I would like to use ports.py list
to list ports lists and ports.py create --name ...
to create them.
I know this is not 100% related to Greenbone, but I searched the web far and wide to find a solution and nothing seems to work. This is the snippet of code I’m struggling with:
def main(gmp: Gmp, args: argparse.Namespace) -> None:
print(args)
parser = argparse.ArgumentParser(prog='ports.py')
subparsers = parser.add_subparsers()
parser_list = subparsers.add_parser('list')
args, unknown = parser.parse_args()
When I run it with gvm-script --gmp-username <user_name> socket --socketpath /tmp/gvm/gvmd/gvmd.sock ports.py list
I get an error:
usage: ports.py [-h] {list} ...
ports.py: error: argument {list}: invalid choice: 'admin' (choose from 'list')
I understand that it catches the --gmp-username
argument, but if I restrict the parsed arguments by using parser.parse_args(['list'])
then I get an error:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/gvmtools/script.py", line 113, in main
run_script(args.scriptname, global_vars)
File "/usr/local/lib/python3.10/dist-packages/gvmtools/helper.py", line 216, in run_script
exec(file, global_vars) # pylint: disable=exec-used
File "<string>", line 37, in <module>
File "<string>", line 34, in main
TypeError: cannot unpack non-iterable Namespace object
What am I doing wrong? Is there a way to use subparser for gvm-scripts?
I will appreciate any guidance on this as I’ve been trying to make it work for over a day now.