Пример #1
0
def _setup_grepy_parser():
    """
    Sets up an optparse-command line parser specific for grepy.
    """
    usage  = "%prog [OPTIONS] PATTERN FILE [FILE...]"
    versn  = "%prog version 1.1 jk"
    descr  = "%prog searches the named input FILEs for lines containing "\
            +"a match to the given PATTERN and prints them. "\
            +"Links and non-readable files are ignored!"
    parser = OptionParser(usage=usage, version=versn, description=descr)
    # change conflict handler, so "-?" option can be added to "help" action
    parser.set_conflict_handler(handler="resolve")
    parser.add_option("-h", "-?", "--help", action="help",
                      help="show this help message and exit")
    parser.add_option("-c", "--color", dest="colorize_output",
                      default=False, action="store_true",
                      help="highlight the matching string in color")
    parser.add_option("-n", "--line-number", dest="print_line_number",
                      default=False, action="store_true",
                      help="prefix output line with the line number")
    parser.add_option("-f", "--filenames", dest="print_filenames",
                      default=False, action="store_true",
                      help="print filenames before occurence of PATTERN")
    parser.add_option("-R", "--recursive", dest="traverse_recursively",
                      default=False, action="store_true",
                      help="recursively read all files under each directory")
    parser.add_option("-b", "--binary", dest="ignore_binary_files",
                      default=True, action="store_false",
                      help="do not ignore binary files")
    return parser
Пример #2
0
class TestConflictOverride(BaseTest):
    def setUp(self):
        self.parser = OptionParser(usage=SUPPRESS_USAGE)
        self.parser.set_conflict_handler("resolve")
        self.parser.add_option("-n", "--dry-run",
                               action="store_true", dest="dry_run",
                               help="don't do anything")
        self.parser.add_option("--dry-run", "-n",
                               action="store_const", const=42, dest="dry_run",
                               help="dry run mode")

    def test_conflict_override_opts(self):
        opt = self.parser.get_option("--dry-run")
        self.assertEqual(opt._short_opts, ["-n"])
        self.assertEqual(opt._long_opts, ["--dry-run"])

    def test_conflict_override_help(self):
        self.assertStdoutEquals(["-h"], """\
options:
  -h, --help     show this help message and exit
  -n, --dry-run  dry run mode
""")

    def test_conflict_override_args(self):
        self.assertParseOK(["-n"],
                           {'dry_run': 42},
                           [])
Пример #3
0
def main():
    # Usage syntax:
    # grepy PATTERN FILE [FILE] [Options]
    # Command line args:
    # -c --color: print matches in color
    # -h -? --help: print help (automatic optparse?). also print this with no args
    # -n --line-number: prefix output lines with linenumberh
    # -f --filenames: print filenames before occurences
    # -R --recursive: recursively process directories
    # -v: Print author details and version number
    start_time = time.time()
    # set usage info string and version string and create optparser
    usage = "%prog PATTERN FILE [FILE] [Options]"
    version = "%prog 0.1-mr"
    desc = "Finds and outputs patterns in specified file(s)"
    parser = OptionParser(usage=usage, version=version, description=desc, add_help_option=False)
    # we suppress adding the help option to manually set it later

    # we're gonna overwrite --version, so make optparse stop moaning
    # this will also allow us to print --version at the end of the option list
    # by default, optparse puts this at the top of the option list, which is ugly
    parser.set_conflict_handler(handler="resolve")

    parser.add_option("-c", "--color", action="store_true", dest="color", \
                       help="Highlight pattern matches with color")
    # define the custom help switch
    parser.add_option("-h", "-?", "--help", action="help", help="Display this help page")
    parser.add_option("-n", "--line-numbers", action="store_true", dest="println", \
                       help="Print line-numbers of matches")
    parser.add_option("-f", "--filenames", action="store_true", dest="printfn", \
                       help="Print file names before matches")
    parser.add_option("-R", "--recursive", action="store_true", dest="recursive", \
                       help="Recursively process directories in the file list")
    parser.add_option("-v", "--version", action="version", \
                       help="Show author and version information and exit.")
    parser.add_option("-t", "--time", action="store_true", dest="time", \
                       help="Print out the processing time at the end of script run")

    # get options and arguments from argv
    (options, args) = parser.parse_args()

    # print usage information if no or too less arguments are supplied
    if len(args) < 2:
        parser.print_help()
        exit(0) # and quit

    pattern = args[0] # first argument is the regex pattern
    reg = re.compile(pattern) # precompile the pattern (more efficient)
    files = args[1:] # all other arguments are filenames

    # Everything's set up, so start working
    grepy(files, reg, options)

    if options.time:
        end_time = time.time()
        print "Script run took %.3f sec" %(end_time - start_time)
Пример #4
0
 def get_parser(kls):
     from optparse import OptionParser
     parser = OptionParser()
     parser.set_conflict_handler("resolve")
     parser.add_option("--port",  dest="port",
                       default='', help="server listen port")
     parser.add_option("--shell", dest="shell",
                       default=False, help="application shell",
                       action='store_true')
     parser.add_option("--config", dest='config',
                       default="",
                       help="use config file")
     parser.add_option("--encode", dest='encode',
                       default="",
                       help="encode password hash using werkzeug")
     return parser
Пример #5
0
def mainparser(harvest=None,with_stdopts=True,**kwargs):
  """setup option parser"""
  from optparse import OptionParser

  kwargs.setdefault('usage','usage: %prog [options] [file(s)]')
  kwargs.setdefault('version','%prog ' + __version__)
  parser = OptionParser(**kwargs)
  parser.set_conflict_handler('resolve')
      
  if with_stdopts:
    parser.add_options(stdopts)

  if harvest is not None:
    for optlist in harvest_options(harvest):
      parser.add_options(optlist)

  return parser
Пример #6
0
        if kinds_of_coins == 1:
            return 1
        elif kinds_of_coins == 2:
            return 5
        elif kinds_of_coins == 3:
            return 10
        elif kinds_of_coins == 4:
            return 25
        elif kinds_of_coins == 5:
            return 50

# 
# Parse the command line arguments
#
parser = OptionParser()
parser.set_conflict_handler("resolve")
parser.add_option("-c","--coins",dest="coins",help="amount to change",metavar="<amount>")
parser.add_option("-a","--animated",action="store_true",dest="animated",help="animate graphing?",metavar="<animated?>")
parser.add_option("-g","--graph",action="store_true",dest="graph",help="use graphing?",metavar="<graph?>")
parser.add_option("-l","--label",action="store_true",dest="label",help="use label?",metavar="<label?>")
parser.add_option("-d","--delay",dest="delay",help="animation delay",metavar="<animation delay>")
(options, args) = parser.parse_args()

#
# Set the arguments we will use
#
c = DEFAULT_COINS if options.coins is None else int(options.coins)
a = True if options.animated else False
g = True if options.graph else False
l = True if options.label else False
d = DEFAULT_DELAY if options.delay is None else float(options.delay)