[PYTHON] How to use argparse and the difference between optparse

Previously, I wrote an article as How to use OptParser, but apparently argparse.ArgumentParser is better.

So a note on how to use argparse.ArgumentParser

# -*- coding:utf-8 -*-
from optparse import OptionParser
from argparse import ArgumentParser
 
if __name__ == '__main__':
 
    """Character string to be displayed when a command error occurs"""
    desc = u'{0} [Args] [Options]\nDetailed options -h or --help'.format(__file__)
    # %prog cannot be output
    # usage = u'%prog [Args] [Options]\nDetailed options -h or --help'

    parser = ArgumentParser(description=desc)
    # _parser = OptionParser(usage=usage, version=1.0)
 
    #String
    parser.add_argument(
        '-q', '--query',
        type = str,         #Specify the type of value to receive
        dest = 'query',     #Save destination variable name
        required = True,    #Required item
        help = 'Word to search' # --Statement to display when helping
    )
    # _parser.add_argument(
    #     '-q', '--query',
    #     action = 'store',
    #     type = 'str',               #Specify the type of value to receive
    #     dest = 'download_date',     #Save destination variable name
    #     help = 'Word to search'  # --Statement to display when helping
    # )

    #Numerical value
    parser.add_argument(
        '-w', '--worker',
        type = int,
        dest = 'worker',
        default = 1,
        help = 'Number of multi-processes'
    ) 
    #Boolean value
    parser.add_argument(
        '-b', '--bool',
        action = 'store_true', # store_True puts True in dest(store_There is also false)
        dest = 'bool'
    )
 
    # """Set the default value for each option"""
    # _parser.set_defaults(worker = 1)
 
    """Perspective options"""
    args = parser.parse_args()
    # _options, _args = _parser.parse_args()
 

    """The value specified in the option is args.<Variable name>Can be obtained with"""
    query, worker, bool = args.query, args.worker, args.bool
    # query, worker, bool = _options.query, _options.worker, _options.bool
    if worker > 100
        #When generating an error ↓ Like this
        parser.error('Too many processes')
 
    print args

I don't think optparse and argparse will change that much It seems that various functions have been added to argparse, as the details have changed, but basically this is enough.

reference

http://docs.python.jp/2/library/argparse.html

Recommended Posts

How to use argparse and the difference between optparse
How to use the optparse module
How to use OptParse
How to use the generator
How to use Python argparse
How to use the decorator
How to use the grep command and frequent samples
How to use the zip function
How to install and use Tesseract-OCR
How to use .bash_profile and .bashrc
How to use the ConfigParser module
Understand the difference between cumulative assignment to variables and cumulative assignment to objects
How to use the Spark ML pipeline
How to install and use pandas_datareader [Python]
[Linux] How to use the echo command
How to use the Linux grep command
Difference in how to write if statement between ruby ​​and python
python: How to use locals () and globals ()
How to use Python zip and enumerate
How to use the IPython debugger (ipdb)
How to use is and == in Python
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
How to use pandas Timestamp and date_range
[Introduction to Python] What is the difference between a list and a tuple?
How to get the date and time difference in seconds with python
[Python] How to use the enumerate function (extract the index number and element)
How to use the C library in Python
How to use lists, tuples, dictionaries, and sets
What is the difference between `pip` and` conda`?
How to use MkDocs for the first time
Introducing Sinatra-style frameworks and how to use them
How to use the graph drawing library Bokeh
About the difference between "==" and "is" in python
How to use the NHK program guide API
[Algorithm x Python] How to use the list
How to switch between Linux and Mac shells
How to install Cascade detector and how to use it
About the difference between PostgreSQL su and sudo
What is the difference between Unix and Linux?
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use shogun
How to use Pandas 2
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv