1

I have started work with argparse because I have to write Unix-style argument parsing for mailer script.

With 'auto' option, which provides filename mailer, it will execute script received as filename, grabbing prepared mail and just sending it. In second mode --manual, it should be able to build any mail from scratch - one file as content, few attachments, few options to provide mailing list. I really wanted to use --long_opt convention (and maybe -short_opt too) there, but if I understand I should use subparsers.

Is it possible to name subparser like '--name' or even '-n'? For now, I guess not - I have an error.

EXAMPLE USECASES:

(1) python script.py --auto 'anotherScriptName.py'

(2) python script.py --manual --content 'htmlcontent.txt' --attach 'file1.jpg' 'file2.xlsx' --mail-All 

(3) python script.py --manual --content 'htmlcontent.txt' --mail-to 'mail1@gmail.com' 'mail2@yahoo.com'

(4) python script.py --manual --content 'htmlcontent.txt' --attach 'file1.txt' --mail-g ALL_DEVELOPERS

ad. 4) ALL_DEVELOPERS could be string or int (key for group in database)

Code below:

parser = argparse.ArgumentParser(description='Standard UNIX-like option parser for customizing script')

subparsers = parser.add_subparsers()
p = subparsers.add_parser('--manual') ### HERE '--manual'

That would be great, but i want to have many arguments to parse here (and there all will be required) and in second option I want just one path to file with script which will do all work:

parser.add_argument('--manual', action='store_true', dest = 'mode', default = False) 

What I have:

p.add_argument('--content', action = 'store', dest = 'content', require=True, help = "no help for you, it's just path to html content")
p.add_argument('--attach', action = 'store', dest = 'attachments', nargs='*', help = "attachments") 
p.add_argument('--mail', '-m', choices=['-All', '-fromFile', '-group', '-to'], dest = 'mailOpt', require=True)
p.add_argument( dest = 'mails', nargs='*') # 0 args if -All selected, raise error in other case

p2 = subparsers.add_parser('--auto') # Like '--manual'
p2.add_argument('--filename', action='store')

If it is not possbile, should I use _parse_known_args_ function or it's bad idea and just leave names 'manual' and 'auto' because they seems clear enough?

Izzy
  • 755
  • 2
  • 9
  • 17
  • It's not clear to me what you're trying to achieve. How should a user call your script, and what should happen when they do? – jonrsharpe Sep 11 '15 at 08:33
  • @Izzy update the question. – Peter Wood Sep 11 '15 at 08:40
  • Why not use a [sub-command](https://docs.python.org/2/library/argparse.html#sub-commands), `python myscript.py manual ...` vs `python myscript.py auto`? – jonrsharpe Sep 11 '15 at 08:44
  • It should be the best way, but I was wondering about naming them in more clear way (--option value or option=value seems more default for my mind, something is wrong with me? ) – Izzy Sep 11 '15 at 08:53

0 Answers0