[PYTHON] How to use OptParse

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from optparse import OptionParser
 
if __name__ == '__main__':
 
    """Character string to be displayed when a command error occurs"""
    usage = u'%prog [Args] [Options]\nDetailed options -h or --help'
 
    version = 0.1
    parser = OptionParser(usage=usage, version=version)
 
    """ test.py -If you want to enter an integer value after the option, as in d 20111201"""
    parser.add_option(
        '-d', '--date',
        action = 'store',
        type = 'int',               #Specify the type of value to receive
        dest = 'download_date',     #Save destination variable name
        help = 'Set date(yyyymmdd) you want to download.(ex.20110811)'  # --Sentence to be displayed at the time of help (can you see it?)
    )
     
    """If you want a string(test.py -f hoge.txt) """
    parser.add_option(
        '-f', '--file',
        action = 'store',
        type = 'str',           #Type specification
        dest = 'file_name',     #Save destination variable name
        help = 'Set filename (ex. hoge.txt)'
    )
 
    """ -Saves true if s is specified"""
    parser.add_option(
        '-s', '--sleep',
        action = 'store_true',      # store_If true, then True'dest'It is stored in the variable specified by.(store when false_false)
        dest = 'hoge_flg',
        help = 'set sleep flag'
    )
 
    """Set the default value for each option"""
    parser.set_defaults(
        download_date = None,
        file_name = None,
        hoge_flg = False
    )
 
    """Perspective options"""
    options, args = parser.parse_args()
 
    """Simple arguments(Example: test.py a b)Is args[index]Can be obtained with"""
    if len(args) > 0:
        for i, v in enumerate(args):
            print 'Args[%s] is: %s' % (i, v)
 
    """The value specified in the option is options.<Variable name>Can be obtained with"""
    date = options.download_date
    if date:
        if len(str(date)) != 8:
            #When generating an error ↓ Like this
            parser.error('Date must be yyyymmdd')
 
    print 'date: %s, file: %s, sleep: %s' % (options.download_date, options.file_name, options.hoge_flg)

If you run this file with the –help option

$ python test.py --help
 
Usage: test.py [Args] [Options]
Detailed options -h or --help
 
Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -d DOWNLOAD_DATE, --date=DOWNLOAD_DATE
                        Set date(yyyymmdd) you want to download.(ex.20110811)
  -f FILE_NAME, --file=FILE_NAME
                        Set filename (ex. hoge.txt)
  -s, --sleep           set sleep flag

Recommended Posts

How to use OptParse
How to use the optparse module
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 Pandas 2
How to use Virtualenv
How to use pytest_report_header
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 virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use python-kabusapi
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
[Python] How to use list 1
How to use FastAPI ③ OpenAPI
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
Python: How to use pydub
[Python] How to use checkio
How to use Django's GeoIp2
[Python] How to use input ()
How to use the decorator
[Introduction] How to use open3d
How to use Python lambda
How to use Jupyter Notebook
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Google Colaboratory
How to use Python bytes
How to use argparse and the difference between optparse
How to use cron (personal memo)
Python: How to use async with
How to use the zip function
How to use SWIG from waf
Summary of how to use pandas.DataFrame.loc
How to use classes in Theano