#!/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