Exemple #1
0
def main():
    p = OptionParser(
        "%prog SERVER:/PATH [options] flags|testcodes\n"
        "       %prog --help\n"
        "       %prog SHOWOPTION",
        version="%prog " + VERSION,
        formatter=IndentedHelpFormatter(2, 25))
    opt, args = scan_options(p)
    nfs4lib.SHOW_TRAFFIC = opt.showtraffic

    # Create test database
    tests, fdict, cdict = testmod.createtests('servertests')

    # Deal with any informational options
    if opt.showflags:
        printflags(fdict.keys())
        sys.exit(0)

    if opt.showcodes:
        codes = cdict.keys()
        codes.sort()
        for c in codes:
            print c
        sys.exit(0)

    # Grab server info and set defaults
    if not args:
        p.error("Need a server")
    url = args.pop(0)
    opt.server, opt.port, opt.path = parse_url(url)
    if not opt.server:
        p.error("%s not a valid server name" % url)
    if not opt.port:
        opt.port = 2049
    else:
        opt.port = int(opt.port)
    if not opt.path:
        opt.path = []
    else:
        opt.path = unixpath2comps(opt.path)

    # Check --use* options are valid
    for attr in dir(opt):
        if attr.startswith('use') and attr != "usefh":
            path = getattr(opt, attr)
            #print attr, path
            if path is None:
                path = opt.path + ['tree', attr[3:]]
            else:
                # FIXME - have funct that checks path validity
                if path[0] != '/':
                    p.error("Need to use absolute path for --%s" % attr)
                # print path
                if path[-1] == '/' and attr != 'usedir':
                    p.error("Can't use dir for --%s" % attr)
                try:
                    path = unixpath2comps(path)
                except Exception, e:
                    p.error(e)
            setattr(opt, attr, [comp for comp in path if comp])
Exemple #2
0
def main():
    global conf
    command_container = BeakerCommandContainer(conf=conf)
    formatter = IndentedHelpFormatter(max_help_position=60, width=120)
    parser = BeakerOptionParser(version=__version__,
                                conflict_handler='resolve',
                                command_container=command_container,
                                default_command="help",
                                formatter=formatter)

    # Need to deal with the possibility that requests is not importable...
    try:
        import requests
        maybe_http_error = (requests.HTTPError, )
    except ImportError:
        maybe_http_error = ()

    # This is parser.run(), but with more sensible error handling
    cmd, cmd_opts, cmd_args = parser.parse_args()
    try:
        return cmd.run(*cmd_args, **cmd_opts.__dict__)
    except krbV.Krb5Error, e:
        if e.args[0] == krbV.KRB5KRB_AP_ERR_TKT_EXPIRED:
            sys.stderr.write(
                'Kerberos ticket expired (run kinit to obtain a new ticket)\n')
            return 1
        elif e.args[0] == krbV.KRB5_FCC_NOFILE:
            sys.stderr.write(
                'No Kerberos credential cache found (run kinit to create one)\n'
            )
            return 1
        else:
            raise
Exemple #3
0
def getArguments():
    ''' Gets command-line arguments and handles validation '''
    parser = OptionParser("%prog [options] file", formatter=IndentedHelpFormatter(4,80))
    parser.add_option("-d", "--database-name", dest="dbname",      help="Database name.", default="helioviewer", metavar="DB_Name")
    parser.add_option("-u", "--database-user", dest="dbuser",      help="Database username.", default="helioviewer", metavar="Username")
    parser.add_option("-p", "--database-pw",   dest="dbpass",      help="Database password.", default="helioviewer", metavar="Password")
    parser.add_option("-t", "--table-name",    dest="tablename",   help="Table name.", default="image", metavar="Table_Name")
    parser.add_option("-n", "--num-queries",   dest="numqueries",  help="Number of queries to simulate.", default=100)
    parser.add_option("-m", "--num-threads",   dest="numthreads",  help="Number of simultaneous threads to execute", default = 1)
    parser.add_option("-c", "--count",         dest="count",       help="Number of rows in the database (queried with COUNT if not specified, which is slow on many transaction safe databases, e.g. postgres)")
    parser.add_option("", "--timing-method",   dest="timingmethod", help="Timing method, possible options are timeit and now", default="timeit")
    parser.add_option("", "--multiple-connections", dest="multipleconnections", help="Use one connection per query", action="store_true")
    parser.add_option("", "--postgres",        dest="postgres",    help="Whether output should be formatted for use by a PostgreSQL database.", action="store_true")
    
    try:                                
        options, args = parser.parse_args()
                    
    except:
        sys.exit(2)

    # check for filename
    if len(args) != 1:
        usage(parser)
        print "Error: Output file not specified"
        sys.exit(2)
    else:
        options.filename = args[0]

    return options
Exemple #4
0
def getArguments():
    ''' Gets command-line arguments and handles validation '''
    parser = OptionParser("%prog [options] file",
                          formatter=IndentedHelpFormatter(4, 80, 130))
    parser.add_option("-n",
                      "--num-records",
                      dest="numrecords",
                      help="Number of records per table.",
                      default=1000000)
    parser.add_option("-c",
                      "--cadence",
                      dest="cadence",
                      help="Record cadence in seconds.",
                      default=10)
    parser.add_option("-d",
                      "--database-name",
                      dest="dbname",
                      help="Database name.",
                      default="helioviewer")
    parser.add_option(
        "-t",
        "--table-name",
        dest="tablename",
        help=
        "Table name (If multiple tables are requested, a number will be affixed to each table).",
        default="images")
    parser.add_option(
        "-i",
        "--insert-size",
        dest="insertsize",
        help="How many records should be included in each INSERT statement",
        default=10)
    parser.add_option("-u",
                      "--num-tables",
                      dest="numtables",
                      help="The number of tables to create.",
                      default=1)
    parser.add_option(
        "",
        "--postgres",
        dest="postgres",
        help=
        "Whether output should be formatted for use by a PostgreSQL database.",
        action="store_true")

    try:
        options, args = parser.parse_args()

    except:
        sys.exit(2)

    # check for filename
    if len(args) != 1:
        usage(parser)
        print "Error: Output file not specified"
        sys.exit(2)
    else:
        options.filename = args[0]

    return options
Exemple #5
0
def get_options():
    '''Gets command-line parameters'''
    parser = OptionParser('%prog [options]', 
                          formatter=IndentedHelpFormatter(4,100))
    
    params = [
        ('-d', '--database-name', 'dbname', 'Database to insert images into'),
        ('-u', '--database-user', 'dbuser', 'Helioviewer.org database user'),
        ('-p', '--database-pass', 'dbpass', 'Helioviewer.org database password'),
        ('-i', '--input-dir', 'source', 'Directory containing files to process'),
        ('-o', '--output-dir', 'destination', 'Directory to move files to')
    ]
    
    for param in params:
        parser.add_option(param[0], param[1], dest=param[2], help=param[3])

    try:
        options, args = parser.parse_args()

        for param in params:
            if getattr(options, param[2]) is None:
                raise Exception("ERROR: missing required parameter %s.\n" % param[2])
    except Exception, e:
        print_help(parser)
        print e
        sys.exit(2)
Exemple #6
0
def parse_options():
    """
    Parse command line options
    """
    import version
    tmp = os.environ.has_key('TEMP') and os.environ['TEMP'] or '/tmp'
    formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0)
    parser = OptionParser(conflict_handler='resolve', formatter=formatter,
        usage="freevo %prog [options]",
        version='%prog ' + str(version.version))
    parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    parser.description = "Helper to convert a favorites.txt to a favorites.pickle"
    parser.add_option('-v', '--verbose', action='count', default=0,
        help='set the level of verbosity [default:%default]')
    parser.add_option('--favorites-txt', metavar='FILE', default=config.TV_RECORD_FAVORITES_LIST,
        help='the favorites.txt file to read and process [default:%default]')
    parser.add_option('--favorites-pickle-out', metavar='FILE', default=os.path.join(tmp, 'favorites.pickle'),
        help='the reritten favorites.pickle file [default:%default]')
    parser.add_option('--favorites-txt-out', metavar='FILE', default=os.path.join(tmp, 'favorites.txt'),
        help='the reritten favorites.txt file [default:%default]')
    parser.add_option('--schedule-pickle-out', metavar='FILE', default=os.path.join(tmp, 'schedule.pickle'),
        help='the reritten schedule.pickle file [default:%default]')

    opts, args = parser.parse_args()
    return opts, args
    def parse_options():
        """
        Parse command line options
        """
        import version
        formatter = IndentedHelpFormatter(indent_increment=2,
                                          max_help_position=32,
                                          width=100,
                                          short_first=0)
        parser = OptionParser(conflict_handler='resolve',
                              formatter=formatter,
                              usage="freevo %prog [options]",
                              version='%prog ' + str(version.version))
        parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        parser.description = "Convert station list (TV_CHANNELS) from local_conf.py for tvtime"
        parser.add_option(
            '--band',
            choices=bands,
            default=bands[0],
            metavar='BAND',
            help='Select the TV band [default:%default], choose from: "' +
            '", "'.join(bands) + '"')

        opts, args = parser.parse_args()
        return opts, args
Exemple #8
0
    def parse_options():
        """
        Parse command line options
        """
        import version
        formatter = IndentedHelpFormatter(indent_increment=2,
                                          max_help_position=32,
                                          width=100,
                                          short_first=0)
        parser = OptionParser(conflict_handler='resolve',
                              formatter=formatter,
                              usage="freevo %prog [options]",
                              version='%prog ' + str(version.version))
        prog = os.path.basename(sys.argv[0])
        parser.prog = os.path.splitext(prog)[0]
        parser.description = "Downloads the listing for xmltv and cache the data"
        parser.add_option(
            '-u',
            '--update',
            action='store_true',
            default=False,
            help=
            'Update the database only, do not attempt to retrieve listings. [default:%default]'
        )

        opts, args = parser.parse_args()
        return opts, args
Exemple #9
0
def parse_options():
    """
    Parse command line options
    """
    import version
    formatter = IndentedHelpFormatter(indent_increment=2,
                                      max_help_position=36,
                                      width=100,
                                      short_first=0)
    parser = OptionParser(conflict_handler='resolve',
                          formatter=formatter,
                          usage="""
Freevo helper script to start Freevo on lirc command.  Everytime Freevo is not
running and EXIT or POWER is pressed, this script will start Freevo. If the
display in freevo.conf is x11 or dga, this script will start Freevo in a new X
session.""",
                          version='%prog ' + version.version)
    parser.add_option('--start',
                      action='store_true',
                      default=False,
                      help='start the daemon [default:%default]')
    parser.add_option('--stop',
                      action='store_true',
                      default=False,
                      help='stop the daemon [default:%default]')
    return parser.parse_args()
 def __init__(self, prog=None, usage=None):
     formatter = IndentedHelpFormatter(
              indent_increment=2,
              max_help_position=80,
              width=100,
              short_first=1)
     optparse.OptionParser.__init__(self, prog=prog, usage=usage,
                                    formatter=formatter)
 def standalone_help(self):
     help_text = self.name_with_arguments().ljust(
         len(self.name_with_arguments()) + 3) + self.help_text + "\n\n"
     if self.long_help:
         help_text += "%s\n\n" % self.long_help
     help_text += self.option_parser.format_option_help(
         IndentedHelpFormatter())
     return help_text
Exemple #12
0
def parse_options():
    """
    Parse command line options
    """
    import version
    thumbsize = config.WWW_IMAGE_THUMBNAIL_SIZE
    imagesize = config.WWW_IMAGE_SIZE
    formatter = IndentedHelpFormatter(indent_increment=2,
                                      max_help_position=36,
                                      width=100,
                                      short_first=0)
    parser = OptionParser(conflict_handler='resolve',
                          formatter=formatter,
                          usage="""
Make image MRSS feed for CoolIris (http://www.cooliris.com/site/support/download-all-products.php)

Usage: %prog [options]""",
                          version='%prog ' + version.version)
    parser.add_option('-v',
                      '--verbose',
                      action='count',
                      default=0,
                      help='set the level of verbosity')
    parser.add_option(
        '-r',
        '--rebuild',
        action='store_true',
        dest='force',
        default=False,
        help='rebuild the thumbnails and images [default:%default]')
    parser.add_option('-t',
                      '--thumb-size',
                      action='store',
                      dest='thumbsize',
                      default=thumbsize,
                      metavar='SIZE',
                      help='size of thumbnail images [default:%default]')
    parser.add_option('-i',
                      '--image-size',
                      action='store',
                      dest='imagesize',
                      default=imagesize,
                      metavar='SIZE',
                      help='size of images [default:%default]')
    parser.add_option('-T',
                      '--no-thumbs',
                      action='store_true',
                      dest='nothumbs',
                      default=False,
                      help='do not build thumbnail images [default:%default]')
    parser.add_option('-I',
                      '--no-images',
                      action='store_true',
                      dest='noimages',
                      default=False,
                      help='Do not build images [default:%default]')
    return parser.parse_args()
def MyOptionParser(prog, usage):
    formatter = IndentedHelpFormatter(indent_increment=2,
                                      max_help_position=80,
                                      width=100,
                                      short_first=1)

    parser = LenientOptionParser(prog=prog, formatter=formatter, usage=usage)
    parser.disable_interspersed_args()
    return parser
Exemple #14
0
 def __init__(self):
     # instance attributes, feels safer
     self.options = None
     self.args = None
     self.__verbose = None
     self.__verbose_default = 0
     self.__timeout = None
     self.__timeout_default = 10
     self.__timeout_max = 86400
     self.topfile = get_topfile()
     # this gets utrunner.py in PyCharm and runpy.py from unittest
     if os.path.basename(self.topfile) in ('utrunner.py', 'runpy.py'):
         self.topfile = __file__
     #print('topfile = %s' % self.topfile)
     self._docstring = get_file_docstring(self.topfile)
     if self._docstring:
         self._docstring = '\n' + self._docstring.strip() + '\n'
     if self._docstring is None:
         self._docstring = ''
     self._topfile_version = get_file_version(self.topfile)
     # this doesn't work in unit tests
     # if self._topfile_version:
     #     raise CodingError('failed to get topfile version - did you set a __version__ in top cli program?') # pylint: disable=line-too-long
     self._cli_version = self.__version__
     self._utils_version = harisekhon.utils.__version__
     # returns 'python -m unittest' :-/
     # prog = os.path.basename(sys.argv[0])
     self._prog = os.path.basename(self.topfile)
     self._github_repo = get_file_github_repo(self.topfile)
     # if not self.github_repo:
     #     self.github_repo = 'https://github.com/harisekhon/pytools'
     if self._github_repo:
         self._github_repo = ' - ' + self._github_repo
     # _hidden attributes are shown in __dict__
     self.version = '%(_prog)s version %(_topfile_version)s ' % self.__dict__ + \
                    '=>  CLI version %(_cli_version)s  =>  Utils version %(_utils_version)s' % self.__dict__
     self.usagemsg = 'Hari Sekhon%(_github_repo)s\n\n%(_prog)s\n%(_docstring)s\n' \
                     % self.__dict__
     self.usagemsg_short = 'Hari Sekhon%(_github_repo)s\n\n' % self.__dict__
     # set this in simpler client programs when you don't want to exclude
     # self.__parser = OptionParser(usage=self.usagemsg_short, version=self.version)
     # self.__parser = OptionParser(version=self.version)
     # will be added by default_opts later so that it's not annoyingly at the top of the option help
     # also this allows us to print full docstring for a complete description and not just the cli switches
     # description=self._docstring # don't want description printed for option errors
     width = os.getenv('COLUMNS', None)
     if not isInt(width) or not width:
         width = Terminal().width
     width = min(width, 200)
     self.__parser = OptionParser(add_help_option=False, formatter=IndentedHelpFormatter(width=width))
     # duplicate key error or duplicate options, sucks
     # self.__parser.add_option('-V', dest='version', help='Show version and exit', action='store_true')
     self.setup()
Exemple #15
0
def main():
    """
    The method called when running this script
    """
    usage = """calc_histogram.py --expr "expresion"
A command-line tool to test similarity to Microsoft's Academic Knowledge."""

    fmt = IndentedHelpFormatter(max_help_position=50, width=100)
    parser = OptionParser(usage=usage, formatter=fmt)
    group = OptionGroup(
        parser, 'Query arguments',
        'These options define search query arguments and parameters.')
    group.add_option('-e',
                     '--expresion',
                     metavar='EXPR',
                     default=None,
                     help='Expression')
    group.add_option('-a',
                     '--attributes',
                     metavar='ATTR',
                     default='Id',
                     help='Expression')
    parser.add_option_group(group)
    options, _ = parser.parse_args()

    # Show help if we have not an expression
    if len(sys.argv) == 1:
        parser.print_help()
        return 1
    if options.expresion is None:
        print('Expression is mandatory!')
        return 1

    query = inquirer.AcademicQuerier(inquirer.AcademicQueryType.HISTOGRAM, {
        'expr': options.expresion,
        'attributes': options.attributes
    })
    if query is not None:
        histograms = query.post()
        for histogram in histograms:
            data = histogram['data']
            rng = range(1, len(data) + 1)
            labels = [val['value'] for val in data]
            plt.bar(rng, [val['count'] for val in data])
            plt.xticks(rng, labels, rotation='vertical')
            plt.margins(0.2)
            plt.subplots_adjust(bottom=0.15)
            plt.legend()
            plt.xlabel(histogram['attribute'])
            plt.ylabel('count')
            plt.title('Histogram for {}'.format(histogram['attribute']))
            plt.show()
Exemple #16
0
def main():
    p = OptionParser(
        "%prog SERVER:/PATH [options] flags|testcodes\n"
        "       %prog --help\n"
        "       %prog SHOWOPTION",
        formatter=IndentedHelpFormatter(2, 25))
    opt, args = scan_options(p)

    # Create test database
    tests, fdict, cdict = testmod.createtests('client41tests')

    # Deal with any informational options
    if opt.showflags:
        printflags(fdict.keys())
        sys.exit(0)

    if opt.showcodes:
        codes = cdict.keys()
        codes.sort()
        for c in codes:
            print c
        sys.exit(0)

    # Grab server info and set defaults
    if not args:
        p.error("Need a server")
    url = args.pop(0)
    print "url", url
    opt.path = nfs4lib.path_components(url)
    print "Set opt.path", opt.path

    # Check --use* options are valid
    for attr in dir(opt):
        if attr == 'useparams':
            opt.useparams = parse_useparams(opt.useparams)
        elif attr.startswith('use') and attr != "usefh":
            path = getattr(opt, attr)
            #print attr, path
            if path is None:
                path = opt.path + ['tree', attr[3:]]
            else:
                # FIXME - have funct that checks path validity
                if path[0] != '/':
                    p.error("Need to use absolute path for --%s" % attr)
                # print path
                if path[-1] == '/' and attr != 'usedir':
                    p.error("Can't use dir for --%s" % attr)
                try:
                    path = nfs4lib.path_components(path)
                except Exception, e:
                    p.error(e)
            setattr(opt, attr, [comp for comp in path if comp])
Exemple #17
0
 def __init__(self, prog, usage, args):
     self.given = args
     
     formatter = IndentedHelpFormatter(
                  indent_increment=2,
                  max_help_position=80,
                  width=100,
                  short_first=1)
     
     LenientOptionParser.__init__(self, prog=prog,
                                  usage=usage,
                                  formatter=formatter)
     self.disable_interspersed_args()
Exemple #18
0
def scan_options():
    from optparse import OptionParser, OptionGroup, IndentedHelpFormatter
    p = OptionParser("%prog [--dport=<?> --port=<?>] --dserver=<?>",
                    formatter = IndentedHelpFormatter(2, 25)
                    )
    p.add_option("--dserver", dest="dserver", help="IP address to connect to")
    p.add_option("--dport", dest="dport", default="2049", type=int, help="Set port to connect to")
    p.add_option("--port", dest="port", type=int, default="2049", help="Set port to listen on (2049)")

    opts, args = p.parse_args()
    if args:
        p.error("Unhandled argument %r" % args[0])
    return opts
Exemple #19
0
def option_parser():
    from optparse import OptionParser, make_option, IndentedHelpFormatter

    help_fmt = ('Method of traversing errors and files to use with autopep8; '
                'choose from: {0}; '
                'default is {1}')

    option_list = [
        make_option('-r',
                    '--recurse',
                    dest='recurse',
                    action='store_true',
                    default=False,
                    help='Recurse down directories from STARTDIR'),
        make_option('-d',
                    '--dryrun',
                    dest='dryrun',
                    action='store_true',
                    default=False,
                    help='Do dry run -- do not modify files'),
        make_option('-v',
                    '--verbose',
                    dest='verbose',
                    action='store_true',
                    default=False,
                    help='Verbose output'),
        make_option('-a',
                    '--autopep8',
                    dest='autopep8',
                    action='store',
                    default="autopep8",
                    help='Specify path to autopep8 instance'),
        make_option('-s',
                    '--select',
                    dest='errors',
                    default=None,
                    action='store',
                    help='Select specific errors'),
        make_option('-m',
                    '--method',
                    dest='method',
                    default=METHODS[0],
                    type="choice",
                    choices=METHODS,
                    help=help_fmt.format(", ".join(METHODS), METHODS[0])),
    ]

    return OptionParser(option_list=option_list,
                        formatter=IndentedHelpFormatter(width=60))
    def format_help(self, formatter=None):
        class Positional(object):
            def __init__(self, args):
                self.option_groups = []
                self.option_list = args

        positional = Positional(self.positional)
        formatter = IndentedHelpFormatter()
        formatter.store_option_strings(positional)
        output = ['\n', formatter.format_heading("Positional Arguments")]
        formatter.indent()
        pos_help = [formatter.format_option(opt) for opt in self.positional]
        pos_help = [line.replace('--', '') for line in pos_help]
        output += pos_help
        return OptionParser.format_help(self, formatter) + ''.join(output)
    def parse_options():
        """
        Parse command line options
        """
        import version
        formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0)
        parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [--daemon|--stop]",
            version='%prog ' + str(version.version))
        parser.prog = appname
        parser.description = "start or stop the commercial detection server"
        parser.add_option('-d', '--debug', action='store_true', dest='debug', default=False,
            help='enable debugging')

        opts, args = parser.parse_args()
        return opts, args
Exemple #22
0
    def parse_arguments(self):
        ''' Gets command-line arguments and handles validation '''
        parser = OptionParser("%prog [options]",
                              formatter=IndentedHelpFormatter(4, 80))
        parser.add_option("-s",
                          "--scale-factor",
                          dest="scale_factor",
                          type="int",
                          help="factor to scale tests by",
                          metavar="NUM",
                          default=1)

        options, args = parser.parse_args()  # pylint: disable=W0612

        return options
Exemple #23
0
def main():
    """
    The method called when running this script
    """
    usage = """author.py --author "albert einstein"
A command-line interface to Microsoft's Academic Knowledge."""

    fmt = IndentedHelpFormatter(max_help_position=50, width=100)
    parser = OptionParser(usage=usage, formatter=fmt)
    group = OptionGroup(
        parser, 'Query arguments',
        'These options define search query arguments and parameters.')
    group.add_option('-a',
                     '--author',
                     metavar='AUTHORS',
                     default=None,
                     help='Author name(s)')
    parser.add_option_group(group)
    options, _ = parser.parse_args()

    # Show help if we have no author name
    if len(sys.argv) == 1:
        parser.print_help()
        return 1

    for i in range(NUM_QUERIER_THREADS):
        worker = Thread(target=querier_enclosure, args=(
            i,
            THE_QUEUE,
        ))
        worker.setDaemon(True)
        worker.start()

    ROOT['author'] = options.author
    THE_QUEUE.put({
        'query_type': maka.AcademicQueryType.INTERPRET,
        'payload': {
            'query': 'papers by {}'.format(options.author)
        }
    })
    print('*** Main thread waiting')
    THE_QUEUE.join()
    with open('{}.json'.format(ROOT['author'].replace(' ', '')),
              'w') as outfile:
        json.dump(ROOT, outfile, cls=maka.classes.AcademicEncoder, indent=4)
    print('*** Done')
Exemple #24
0
    def format_help(self, formatter=None):
        """ Create a help text based on the options defined.
        The -- that is added to the options is automatically removed """
        class Positional(object):
            def __init__(self, args):
                self.option_groups = []
                self.option_list = args

        positional = Positional(self.positional)
        formatter = IndentedHelpFormatter()
        formatter.store_option_strings(positional)
        output = ['\n', formatter.format_heading("Commands")]
        formatter.indent()
        pos_help = [formatter.format_option(opt) for opt in self.positional]
        pos_help = [line.replace('--', '') for line in pos_help]
        output += pos_help
        return OptionGroup.format_help(self, formatter) + ''.join(output)
Exemple #25
0
def parse_options():
    """
    Parse command line options
    """
    import version
    formatter = IndentedHelpFormatter(indent_increment=2,
                                      max_help_position=32,
                                      width=100,
                                      short_first=0)
    parser = OptionParser(conflict_handler='resolve',
                          formatter=formatter,
                          usage="freevo %prog [options]",
                          version='%prog ' + str(version.version))
    parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    parser.description = "release the vt in case freevo crashed and still locks the framebuffer"

    opts, args = parser.parse_args()
    return opts, args
Exemple #26
0
    def parse_options():
        """
        Parse command line options
        """
        import version
        formatter = IndentedHelpFormatter(indent_increment=2,
                                          max_help_position=32,
                                          width=100,
                                          short_first=0)
        parser = OptionParser(conflict_handler='resolve',
                              formatter=formatter,
                              usage="freevo %prog [--daemon|--stop]",
                              version='%prog ' + str(version.version))
        parser.prog = appname
        parser.description = "start or stop the internal webserver"

        opts, args = parser.parse_args()
        return opts, args
Exemple #27
0
    def parse_options():
        """
        Parse command line options
        """
        import version
        formatter = IndentedHelpFormatter(indent_increment=2,
                                          max_help_position=32,
                                          width=100,
                                          short_first=0)
        parser = OptionParser(conflict_handler='resolve',
                              formatter=formatter,
                              usage="freevo %prog [options]",
                              version='%prog ' + str(version.version))
        parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        parser.description = "Helper to convert the record_schedule.xml to favorites.pickle"
        parser.add_option('-v',
                          '--verbose',
                          action='count',
                          default=0,
                          help='set the level of verbosity [default:%default]')
        parser.add_option('-i',
                          '--schedule',
                          metavar='FILE',
                          default=config.TV_RECORD_SCHEDULE,
                          help='the record schedule file [default:%default]')
        parser.add_option('-o',
                          '--favorites',
                          metavar='FILE',
                          default=config.TV_RECORD_FAVORITES,
                          help='the record favorites file [default:%default]')

        opts, args = parser.parse_args()

        if not os.path.exists(opts.schedule):
            parser.error('%r does not exist.' % (opts.schedule, ))

        if os.path.exists(opts.favorites):
            parser.error('%r exists, please remove.' % (opts.favorites, ))

        if os.path.splitext(opts.schedule)[1] != '.xml':
            parser.error('%r is not an XML file.' % (opts.schedule, ))

        return opts, args
Exemple #28
0
    def parse_options():
        """
        Parse command line options
        """
        import version
        formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0)
        parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]",
            version='%prog ' + str(version.version))
        parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        parser.description = "Parse the input header file for event data"
        parser.add_option('-v', '--verbose', action='count', default=0,
            help='set the level of verbosity [default:%default]')
        parser.add_option('--device', metavar='DEVICE', default='/dev/input/event0',
            help='device [default:%default] information will be also written to stdout')
        parser.add_option('--input', metavar='INPUT', default='/usr/include/linux/input.h',
            help='parse the imput header [default:%default] and write the event' \
                'data to stdout, this can be redirected to the linuxevent.py')

        opts, args = parser.parse_args()
        return opts, args
Exemple #29
0
def parse_options(defaults, version):
    """
    Parse command line options
    """
    print 'version:', version
    formatter = IndentedHelpFormatter(indent_increment=2,
                                      max_help_position=32,
                                      width=100,
                                      short_first=0)
    parser = OptionParser(conflict_handler='resolve',
                          formatter=formatter,
                          usage=main_usage,
                          version='freevo-' + version)
    #parser.add_option('-v', '--verbose', action='count', default=0,
    #    help='set the level of verbosity [default:%default]')
    parser.add_option('-d',
                      '--debug',
                      action='count',
                      dest='debug',
                      default=0,
                      help='set the level of debuging')
    parser.add_option(
        '--trace',
        action='append',
        default=[],
        help='activate tracing of one or more modules (useful for debugging)')
    parser.add_option(
        '--daemon',
        action='store_true',
        default=False,
        help='run freevo or a helper as a daemon [default:%default]')
    parser.add_option('-f',
                      '--force-fs',
                      action='store_true',
                      default=False,
                      help='force X11 to start full-screen [default:%default]')
    parser.add_option('--doc',
                      action='store_true',
                      default=False,
                      help='generate API documentation [default:%default]')
    return parser.parse_args()
Exemple #30
0
def parse_options():
    """
    Parse command line options
    """
    import version
    formatter = IndentedHelpFormatter(indent_increment=2,
                                      max_help_position=32,
                                      width=100,
                                      short_first=0)
    parser = OptionParser(conflict_handler='resolve',
                          formatter=formatter,
                          usage="freevo %prog [options] [BUTTON=EVENT]",
                          version='%prog ' + str(version.version))
    parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    parser.description = "Helper to write the freevo lircrc file"
    parser.add_option('-v',
                      '--verbose',
                      action='count',
                      default=0,
                      help='set the level of verbosity [default:%default]')
    parser.add_option('--lircrc',
                      metavar='FILE',
                      default=config.LIRCRC,
                      help='the lircrc file [default:%default]')
    parser.add_option(
        '-r',
        '--remote',
        metavar='NAME',
        default=None,
        help='the name of the remote in the lircrc file [default:%default]')
    parser.add_option(
        '-w',
        '--write',
        action='store_true',
        default=False,
        help='write the lircrc file, this will overwrite an existing file!')

    opts, args = parser.parse_args()
    return opts, args