Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python argparse custom categories

# Short answer:
# With argparse, parameters starting with - or -- are considered optional by
# default.

# Longer answer:
# With argparse, parameters starting with - or -- are considered optional by
# default. All other parameters are positional parameters and are required
# by default. It is possible to require optional arguments, but this is a bit
# against their design. Since they are still part of the non-positional
# arguments, they will still be listed under the confusing header 
# “optional arguments” even if they are required. The missing square brackets
# in the usage part however show that they are indeed required.

# Solution:
# I create three categories as follows:
parser._action_groups.pop() # remove existing groups
required_pos = parser.add_argument_group('Required Positional Arguments')
required_nam = parser.add_argument_group('Required Named Arguments')
optional = parser.add_argument_group('Optional Arguments')

# To add arguments to the relevant category, use syntax like:
required_pos.add_argument('dataset', help='path to dataset')
required_nam.add_argument('-o', '--outfile', required=True, 
                          help='path to output file')
optional.add_argument('-t', '--threads', type=int, default=10,
                      help='number of CPUs to use. [default: %(default)s]')

# This creates help messages like:
Required Positional Arguments:
  dataset               path to dataset

Required Named Arguments:
  -o OUTFILE, --outdir OUTFILE
                        path to output file

Optional Arguments:
  -t THREADS, --threads THREADS
                        number of CPUs to use. [default: 10]
Comment

PREVIOUS NEXT
Code Example
Python :: python int to string 
Python :: Returns the first n rows 
Python :: jsonschema in python 
Python :: Sending POST request in Django 
Python :: flatten tf keras 
Python :: Matplotlib rotated x tick labels 
Python :: python sum of list 
Python :: insert data in django models 
Python :: python see if a number is greater than other 
Python :: find highest correlation pairs pandas 
Python :: remove zeros from decimal python 
Python :: how to change port in flask app 
Python :: pandas xa0 
Python :: strftime python multiple formats 
Python :: list comprehension if elseif 
Python :: jupyter dark theme vampire 
Python :: find string in string python 
Python :: python iterate through objects attributes 
Python :: python merge list of lists 
Python :: sentence similarity spacy 
Python :: tree to tuple python 
Python :: pandas dataframe.to_dict 
Python :: python planet list 
Python :: reverse python 
Python :: delete cell in jupyter notebook 
Python :: import all csv as append dataframes python 
Python :: python uppercase 
Python :: circle circumference python 
Python :: double in python 
Python :: manage.py startapp not working in django 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =