Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse with different modes

I have some difficulties to use argparse. I have a GUI application that I want to use like this:

  1. GUI.exe => open GUI application
  2. GUI.exe -s file_directory1 => play GUIX.exe without open it
  3. GUI.exe -s file_directory1 -o file_directory2 => same as 2.

It is not allowed to do : GUI.exe -o file_directory

I know how to do 1 and 2 but not 3

Is there someone who already did this or can give me some clues?

Thank you by advance for your help.

like image 838
Plump69 Avatar asked Nov 22 '25 05:11

Plump69


1 Answers

It's not possible to achieve what you want simply using add_argument and without manual checks. As maggick already said, you can always just check after the parsing of the command line whether the user used the correct options, by manually doing so:

if args.option1 and not args.option2:
    parser.error('some error')

However I believe your -s option is acting a bit like a subcommand. If this is the case it would be better to use add_subparsers and have file_directory1 as required argument for it while -o as its option:

import argparse

parser = argparse.ArgumentParser()
subs = parser.add_subparsers()

s_parser = subs.add_parser('sname')
s_parser.add_argument('file_directory1')
s_parser.add_argument('-o', dest='file_directory2')

And use it as:

prog   # -> launch gui
prog sname file_directory1
prog sname file_directory1 -o file_directory2
like image 167
Bakuriu Avatar answered Nov 24 '25 22:11

Bakuriu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!