I'm very new to this module so please bear with me. I have the following code:
reader.py
import argparse
parent_parser = argparse.ArgumentParser(description="Read text files.")
parent_parser.add_argument('filename', help='TXT file', type=file, nargs='+')
parent_parser.add_argument('--verbose', '-v', action='store_true',
help="Verbosity on")
child_parser = parent_parser.add_subparsers(title="subcommand",
help="Subcommand help")
new_file_command = child_parser.add_parser('new', help="New text file")
edit_file_command = child_parser.add_parser('edit', help="Edit existing text file")
args = parent_parser.parse_args()
What I'm trying to achieve might not be the standard way of how parsers and unix command line utilities work. If that is true, please correct me as I'd like to have standardized app.
This is what I'm trying to achieve:
- if you run bare script with positional argument(s) like this:
python reader.py some.txt
I'd like to be able to just parse it and pass it to function that reads the text file, of course I want to accept optional argverbose
as well - if you run subcommand 'new' (
new_file_command
), I do not want to have positional argumentfilename
to be required, instead I want to pass a string and create new text file like this:python reader.py new another.txt
- if you run subcommand 'edit' (
edit_file_command
) I want to pass existing file in path and check for it (like you usetype=int
inadd_argument
) and then maybe pass it to function that opens editor, something like this:python reader.py edit some.txt
Again, I'm not sure if this is how command line apps/scripts are supposed to behave. I read the docs and looked at examples but it's still isn't clear to me how sub parsers work. I tried looking at Click module but that seems to me even more complicated.
Any help appreciated. Thanks!