def ParseInputs():
  """Interprets command line parameters and checks for required parameters."""

  parser = OptionParser()
  parser.add_option('-d', dest='domain',
                    help='The domain name in which to add groups.')
  parser.add_option('-u', dest='admin_user',
                    help='The admin user to use for authentication.')
  parser.add_option('-p', dest='admin_pass',
                    help="The admin user's password")
  parser.add_option('-g', dest='groups_file',
                    help='The input file containing groups to create.')
  parser.add_option('-m', dest='members_file',
                    help="""The input file containing the members
                            to add to the groups.""")

  (options, args) = parser.parse_args()
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

  if options.domain is None:
    print '-d (domain) is required'
    sys.exit(1)
  if options.admin_user is None:
    print '-u (admin user) is required'
    sys.exit(1)
  if options.admin_pass is None:
    print '-p (admin password) is required'
    sys.exit(1)
  if options.groups_file is None and options.members_file is None:
    print 'Either -g (groups file) or -m (members file) is required'
    sys.exit(1)

  return options
Beispiel #2
0
 def exit(self, status = 0, msg = None):
     debug("Explicit exit called from command")
     try :
         OptionParser.exit(self, status, msg)
     except SystemExit, e :
         # Wrapping SistemExit exception with our own exception
         raise Exceptions.ExplicitExit(e, e.code)
def set_options():
    """Create parser to process command line options, returns a dictionary.

    :Return:
        dictionary with parsed options.
    """
    parser = OptionParser(usage='%prog [options]')
    # defining required options
    parser.add_option('-v', '--verbose', action='store_true', default=False,
                      help='print info and warning messages [default: %default]'
                           ' log will include only critical and error messages'
                           ' by default')
    # parser.add_option('-v', '--verbose', help="verbosity level (0..2)",
    #                   choices=['0', '1', '2'])
    parser.add_option('-o', '--operation',
                      help="choose operation to perform: 'add', 'edit',"
                           " 'delete', 'retrieve'",
                      choices=['add', 'edit', 'delete', 'retrieve'])
    parser.add_option('-f', '--flag', help='flag value')

    (options, args) = parser.parse_args()
    if options.operation is None:
        parser.print_usage()
        parser.exit('Please, choose operation.')
    else:
        return options
Beispiel #4
0
def main():
    from optparse import OptionParser
    parser = OptionParser(version="%%prog v%s" % __version__)
    #parser.add_option('-v', '--verbose', action="store_true", dest="verbose",
    #    default=False, help="Increase verbosity")
    parser.add_option('-m', '--initial-mode',
                      action="store", dest="mode", default="sleep",
                      metavar="MODE", help="start in MODE. (Use 'help' for a list)")

    opts, args = parser.parse_args()
    if opts.mode == 'help':
        print "Valid mode names are: %s" % ', '.join(MODE_NAMES)
        parser.exit(0)
    elif (opts.mode not in MODE_NAMES):
        print "Mode '%s' not recognized, defaulting to sleep." % opts.mode
        opts.mode = "sleep"
    app = TimeClock(default_mode=opts.mode)

    # Make sure that state is saved to disk on exit.
    sys.exitfunc = app.doSave
    signal.signal(signal.SIGTERM, lambda signum, stack_frame: sys.exit(0))
    signal.signal(signal.SIGHUP, lambda signum, stack_frame: sys.exit(0))
    signal.signal(signal.SIGQUIT, lambda signum, stack_frame: sys.exit(0))
    signal.signal(signal.SIGINT, lambda signum, stack_frame: sys.exit(0))

    try:
        gtk.main()
    except KeyboardInterrupt:
        sys.exit(0)
Beispiel #5
0
def CHECK_ARGV():
    argv_dict = {}
    usage = "usage: %prog [options] arg1 arg2" 
    parser = OptionParser(usage)
    parser.add_option("-H","--host",dest="hostname",help="hostname,you DB Hostname or IP")
    
    parser.add_option("-d","--database",dest="db",help="read database ")
    parser.add_option("-t","--table",dest="tb",help="read table")
    parser.add_option("-u","--user",dest="user",help="conn user")
    parser.add_option("-p","--passwd",dest="passwd",help="conn passwd")
    parser.add_option("-P","--port",dest="port",default=3306,help="MySQL Port")
    parser.add_option("-C","--character",dest="character",default='utf8',help="MySQL Charset") 
    parser.add_option("-w","--where",dest="where",default="",help="Input U Where")
    
    
    (options,args)=parser.parse_args()
    
    len_argv=len(sys.argv[1:])
    if len_argv == 0 :
        print parser.print_help()
        parser.exit(1)
    if not options.db or not options.tb or not options.hostname:
        print 'Need database and table'
    else:
        exec("argv_dict ="+str(options))
        return argv_dict
Beispiel #6
0
def cli():
    parser = OptionParser(usage='%prog [options] <test_file> <test_file> ...')
    parser.add_option("--binary",
                      action="store", dest="binary",
                      default=None,
                      help="path to B2G desktop build binary")
    parser.add_option("--profile",
                      action="store", dest="profile",
                      default=None,
                      help="path to gaia profile directory")

    options, tests = parser.parse_args()

    if not options.binary or not options.profile:
        parser.print_usage()
        parser.exit('--binary and --profile required')

    if not tests:
        # Read in a list of tests to skip from disabled.json, if it exists;
        # disabled.json should contain filenames with paths relative to the
        # apps directory, e.g., "wallpaper/test/unit/pick_test.js".
        disabled = []
        disabled_file = os.path.join(os.path.dirname(__file__), 'disabled.json')
        if os.access(disabled_file, os.F_OK):
            with open(disabled_file, 'r') as f:
                disabled_contents = f.read()
                try:
                    disabled = json.loads(disabled_contents)
                except:
                    traceback.print_exc()
                    print "Error while decoding disabled.json; please make sure this file has valid JSON syntax."
                    sys.exit(1)

        # build a list of tests
        appsdir = os.path.join(os.path.dirname(os.path.abspath(options.profile)), 'apps')
        for root, dirs, files in os.walk(appsdir):
            for file in files:
                full_path = os.path.relpath(os.path.join(root, file), appsdir)
                if full_path[-8:] == '_test.js' and full_path not in disabled:
                    tests.append(full_path)

    runner = GaiaUnitTestRunner(binary=options.binary,
                                profile=options.profile)
    runner.run()

    # Lame but necessary hack to prevent tornado's logger from duplicating
    # every message from mozlog.
    logger = logging.getLogger()
    handler = logging.NullHandler()
    logger.addHandler(handler)

    print 'starting WebSocket Server'
    application = tornado.web.Application([
        (r"/", TestAgentServer, {'tests': tests,
                                 'runner': runner,
                                 'logger': mozlog.getLogger('gaia-unit-tests')}),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8789)
    tornado.ioloop.IOLoop.instance().start()
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option("-d", dest="domain", help="The domain name in which to add groups.")
    parser.add_option("-u", dest="admin_user", help="The admin user to use for authentication.")
    parser.add_option("-p", dest="admin_pass", help="The admin user's password")
    parser.add_option(
        "-m",
        dest="member",
        help="""The member of the group for which we want to
                            find all groups where they are owner.""",
    )

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg="\nUnexpected arguments: %s\n" % " ".join(args))

    if options.domain is None:
        print "-d (domain) is required"
        sys.exit(1)
    if options.admin_user is None:
        print "-u (admin user) is required"
        sys.exit(1)
    if options.admin_pass is None:
        print "-p (admin password) is required"
        sys.exit(1)
    if options.member is None:
        print "-m (member) is required"
        sys.exit(1)

    return options
def ParseInputs():
  """Interprets command line parameters and checks for required parameters."""

  parser = OptionParser()
  parser.add_option('-d', dest='domain',
                    help='The domain name in which to add groups.')
  parser.add_option('-u', dest='admin_user',
                    help='The admin user to use for authentication.')
  parser.add_option('-p', dest='admin_pass',
                    help="The admin user's password")
  parser.add_option('-g', dest='groups_output_filename', default='groups.csv',
                    help='The output file to write the group data to.')
  parser.add_option('-m', dest='members_output_filename', default='members.csv',
                    help="""The output file to write the members data to.""")
  parser.add_option('-n', dest='new_domain_name',
                    help="""If present, will replace the domain (-d) with
                            this new domain name in the email addresses for the
                            groups as well as members.""")

  (options, args) = parser.parse_args()
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

  if options.domain is None:
    print '-d (domain) is required'
    sys.exit(1)
  if options.admin_user is None:
    print '-u (admin user) is required'
    sys.exit(1)
  if options.admin_pass is None:
    print '-p (admin password) is required'
    sys.exit(1)

  return options
Beispiel #9
0
def main():
    cli = OptionParser(usage='%prog [options]',
                       description='Limits execution of SSH commands to rsync only')
    cli.add_option('-g', '--debug', dest='debug', action='store_true',
                   help='Turn on debugging mode')

    (options, args) = cli.parse_args()

    try:
        # Require Python >= 2.4
        if sys.version_info[0] < 2 or sys.version_info[1] < 4:
            raise StandardError("Python 2.4.0 or higher is required")

        # If SSH_ORIGINAL_COMMAND is not specified, then the user is assuming
        # this is a normal login shell.
        if not os.environ.has_key('SSH_ORIGINAL_COMMAND'):
            raise StandardError("This is not a login shell. You can only use rsync.")

        rsync = RsyncWrapper(os.environ['SSH_ORIGINAL_COMMAND'])
        retval = rsync.execute()
        cli.exit(retval)

    except StandardError, e:
        if options.debug:
            raise
        else:
            cli.exit(1, "%s\n" % e)
def ParseInputs():
  """Interprets command line parameters and checks for required parameters."""

  parser = OptionParser()
  parser.add_option('--user', dest='oauth_requestor_id',
                    help='The target user/requestor_id to list contacts.')
  parser.add_option('--key', dest='oauth_consumer_key',
                    help='The OAuth consumer key')
  parser.add_option('--secret', dest='oauth_consumer_secret',
                    help='The The OAuth consumer secret.')

  (options, args) = parser.parse_args()
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

  invalid_args = False
  if options.oauth_consumer_key is None:
    print '--key (consumer_key) is required'
    invalid_args = True
  if options.oauth_consumer_secret is None:
    print '--secret (consumer_secret) is required'
    invalid_args = True
  if options.oauth_requestor_id is None:
    print '--user (target user/requestor_id) is required'
    invalid_args = True

  if invalid_args:
    sys.exit(4)

  return options
Beispiel #11
0
def main(args=sys.argv[1:]):
    
    # parse command line options
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-p', '--port', dest='port', 
                      type="int", default=8888,
                      help="port to run the server on [DEFAULT: %default]")
    parser.add_option('-H', '--host', dest='host',
                      default='127.0.0.1',
                      help="host [DEFAULT: %default]")
    parser.add_option('-d', '--docroot', dest='docroot',
                      default=os.getcwd(),
                      help="directory to serve files from [DEFAULT: %default]")
    options, args = parser.parse_args(args)
    if args:
        parser.print_help()
        parser.exit()

    # create the server
    kwargs = options.__dict__.copy()
    server = MozHttpd(**kwargs)

    print "Serving '%s' at %s:%s" % (server.docroot, server.host, server.port)
    server.start(block=True)
Beispiel #12
0
def cli():
    parser = OptionParser(usage="%prog [options] <test_file> <test_file> ...")
    parser.add_option("--binary", action="store", dest="binary", default=None, help="path to B2G desktop build binary")
    parser.add_option("--profile", action="store", dest="profile", default=None, help="path to gaia profile directory")

    options, tests = parser.parse_args()

    if not options.binary or not options.profile:
        parser.print_usage()
        parser.exit("--binary and --profile required")

    if not tests:
        # build a list of tests
        appsdir = os.path.join(os.path.dirname(os.path.abspath(options.profile)), "apps")
        for root, dirs, files in os.walk(appsdir):
            for file in files:
                if file[-8:] == "_test.js":
                    tests.append(os.path.relpath(os.path.join(root, file), appsdir))

    runner = GaiaUnitTestRunner(binary=options.binary, profile=options.profile)
    runner.run()

    # Lame but necessary hack to prevent tornado's logger from duplicating
    # every message from mozlog.
    logger = logging.getLogger()
    handler = logging.NullHandler()
    logger.addHandler(handler)

    print "starting WebSocket Server"
    application = tornado.web.Application(
        [(r"/", TestAgentServer, {"tests": tests, "runner": runner, "logger": mozlog.getLogger("gaia-unit-tests")})]
    )
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8789)
    tornado.ioloop.IOLoop.instance().start()
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option("-d", dest="domain", help="The domain name to list sotes for.")
    parser.add_option("-u", dest="oauth_requestor_id", help="The admin user to use for authentication.")
    parser.add_option("-k", dest="oauth_consumer_key", help="The OAuth consumer key")
    parser.add_option("-s", dest="oauth_consumer_secret", help="The The OAuth consumer secret.")

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg="\nUnexpected arguments: %s\n" % " ".join(args))

    if options.domain is None:
        print "-d (domain) is required"
        sys.exit(1)
    if options.oauth_requestor_id is None:
        print "-u (admin user) is required"
        sys.exit(1)
    if options.oauth_consumer_key is None:
        print "-k (consumer_key) is required"
        sys.exit(1)
    if options.oauth_consumer_secret is None:
        print "-s (consumer_secret) is required"
        sys.exit(1)

    return options
Beispiel #14
0
def parse_args():
    """Parse command-line arguments."""
    parser = OptionParser(usage='%prog [options] <name>',
                          description='create a VM using the SDK')
    parser.add_option('-U', '--url', help='the API entry point URL')
    parser.add_option('-u', '--username', help='the user to connect as')
    parser.add_option('-p', '--password', help='the user\'s password')
    parser.add_option('-m', '--memory', type='int', help='memory size in MB')
    parser.add_option('-D', '--disk', type='int', help='disk size in GB')
    parser.add_option('-c', '--cluster', help='the cluster to add the VM to')
    parser.add_option('-t', '--template', help='base the VM off this template')
    parser.add_option('-N', '--network', help='the network to connect to')
    parser.add_option('-d', '--debug', action='store_true',
                      help='enable debugging')
    for key in ('url', 'username', 'password'):
        name = 'RHEV_%s' % key.upper()
        parser.set_default(key, os.environ.get(name))
    parser.set_default('cluster', 'Default')
    parser.set_default('template', 'Blank')
    parser.set_default('memory', 512)
    parser.set_default('disk', 8)
    parser.set_default('network', 'rhevm')
    opts, args = parser.parse_args()
    for key in ('url', 'username', 'password'):
        if getattr(opts, key) is None:
            name = 'RHEV_%s' % key.upper()
            parser.error('please specify --%s or set $%s' % (key, name))
    if len(args) != 1:
        parser.print_usage()
        parser.exit()
    return opts, args
Beispiel #15
0
def main(args=sys.argv[1:]):

    # parse command line options
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-p', '--port', dest='port',
                      type="int", default=8888,
                      help="port to run the server on [DEFAULT: %default]")
    parser.add_option('-H', '--host', dest='host',
                      default='127.0.0.1',
                      help="host [DEFAULT: %default]")
    parser.add_option('-i', '--external-ip', action="store_true",
                      dest='external_ip', default=False,
                      help="find and use external ip for host")
    parser.add_option('-d', '--docroot', dest='docroot',
                      default=os.getcwd(),
                      help="directory to serve files from [DEFAULT: %default]")
    options, args = parser.parse_args(args)
    if args:
        parser.error("mozhttpd does not take any arguments")
        parser.print_help()
        parser.exit()

    if options.external_ip:
        host = iface.get_lan_ip()
    else:
        host = options.host

    # create the server
    server = MozHttpd(host=host, port=options.port, docroot=options.docroot)

    print "Serving '%s' at %s:%s" % (server.docroot, server.host, server.port)
    server.start(block=True)
Beispiel #16
0
def cli_deploy(argv):
    parser = OptionParser()

    parser.add_option(
        "-c",
        "--conf",
        dest="deploy_conf",
        help="FILENAME of zdd configuration. [default %default]",
        default="deploy.conf",
        metavar="FILENAME",
    )

    parser.add_option(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="Enable verbose logging of the actions zdd takes.",
    )

    options, args = parser.parse_args(argv)

    settings.VERBOSE = options.verbose

    if not os.path.exists(options.deploy_conf):
        print "ERROR: Unable to read zdd configuration file: %s" % options.deploy_conf
        print
        parser.print_help()
        parser.exit()

    deploy(options.deploy_conf)
def ParseInputs():
  """Interprets command line parameters and checks for required parameters."""

  parser = OptionParser()
  parser.add_option('-d', dest='domain',
                    help='The domain name in which to add groups.')
  parser.add_option('-u', dest='admin_user',
                    help='The admin user to use for authentication.')
  parser.add_option('-p', dest='admin_pass',
                    help="The admin user's password")

  (options, args) = parser.parse_args()
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

  if options.domain is None:
    print '-d (domain) is required'
    sys.exit(1)
  if options.admin_user is None:
    print '-u (admin user) is required'
    sys.exit(1)
  if options.admin_pass is None:
    print '-p (admin password) is required'
    sys.exit(1)

  return options
Beispiel #18
0
def main(args=sys.argv[1:]):
    
    # parse command line options
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-p', '--port', dest='port', 
                      type="int", default=8888,
                      help="port to run the server on [DEFAULT: %default]")
    parser.add_option('-H', '--host', dest='host',
                      default='127.0.0.1',
                      help="host [DEFAULT: %default]")
    parser.add_option('-d', '--docroot', dest='docroot',
                      default=os.getcwd(),
                      help="directory to serve files from [DEFAULT: %default]")
    parser.add_option('--test', dest='test',
                      action='store_true', default=False,
                      help='run the tests and exit')
    options, args = parser.parse_args(args)
    if args:
        parser.print_help()
        parser.exit()

    # create the server
    kwargs = options.__dict__.copy()
    test = kwargs.pop('test')
    server = MozHttpd(**kwargs)

    if test:
        server.start()
        server.testServer()
    else:
        server.start(block=True)
Beispiel #19
0
def parse_command_line_args():
    """ Parse arguments given in command line """
    usage = "%prog [options] file_name"
    desc = "Load and run the xml sequence given by the file-name parameter"
    parser = OptionParser(usage=usage, description=desc, version='%prog v1.0')

    msg = "Define the maximum backup depth"
    parser.add_option('-d', '--depth', metavar='DEP',
                      type='int', help=msg)

    msg = "File name of a special backup sequence"
    parser.add_option('-b', '--back', metavar='FILE',
                      type='str', help=msg)

    msg = "Level of the logging messages (from 1 for debug to 5 for critical)"
    parser.add_option('-l', '--log', metavar='LVL',
                      type='int', help=msg, default=2)

    options, args = parser.parse_args()

    if len(args) == 0:
        parser.print_help()
        parser.exit()

    if len(args) > 1:
        parser.error("incorrect number of arguments")

    if options.log not in range(1, 5):
        parser.error("invalid value for logging level")

    res = args[0], options.depth, options.back, options.log*10
    return res
Beispiel #20
0
    def parse_args(self, argv, stdout=io2bytes(sys.stdout)):
        """
        :param argv: list of str
        :param stdout: binary-data stdout output
        """
        parser = OptionParser(version=self.VERSION, usage=self.USAGE)

        parser.add_option(
            '-l', '--label', dest='label', default=b'', type='string', metavar='LABEL',
            help='set label name to LABEL'
        )
        parser.add_option(
            '-c', '--color', dest='color', default=None, type='string', metavar='COLOR',
            help='set output color to COLOR (available colors: %s)' % ', '.join(sorted(COLOR_NAMES.keys()))
        )
        parser.add_option(
            '-s', '--separator', dest='separator', default=b'|', type='string', metavar='SEPARATOR',
            help='set separator string to SEPARATOR (default: "|")'
        )

        option, args = parser.parse_args(argv[1:])

        # encode each arg string to bytes if Python3
        color = COLOR_NAMES.get(option.color.lower()) if option.color else self._get_color(option.label)
        if color is None:
            stdout.write(arg2bytes(parser.format_help().encode('utf-8')))
            stdout.write(b'\nInvalid color name: ' + arg2bytes(option.color) + b'\n')
            parser.exit(2)

        self.prefix = self._make_prefix(option.label, color, option.separator)
        self.paths = [arg2bytes(arg) for arg in args] or [None]
        return self
Beispiel #21
0
def main(args=sys.argv[1:]):
    """console_script entry point"""

    # set up an option parser
    usage = "%prog [options] [command] ..."
    description = "%s. Use `help` to display commands" % __doc__.strip()
    parser = OptionParser(usage=usage, description=description)
    parser.add_option(
        "-s", "--strict", dest="strict", action="store_true", default=False, help="adhere strictly to errors"
    )
    parser.disable_interspersed_args()

    options, args = parser.parse_args(args)

    if not args:
        HelpCLI(parser)(options, args)
        parser.exit()

    # get the command
    command = args[0]
    if command not in commands:
        parser.error("Command must be one of %s (you gave '%s')" % (", ".join(sorted(commands.keys())), command))

    handler = commands[command](parser)
    handler(options, args[1:])
def main(args=sys.argv[1:]):
    """console_script entry point"""

    # set up an option parser
    usage = '%prog [options] [command] ...'
    description = __doc__
    parser = OptionParser(usage=usage, description=description)
    parser.add_option('-s', '--strict', dest='strict',
                      action='store_true', default=False,
                      help='adhere strictly to errors')
    parser.disable_interspersed_args()

    options, args = parser.parse_args(args)

    if not args:
        HelpCLI(parser)(options, args)
        parser.exit()

    # get the command
    command = args[0]
    if command not in commands:
        parser.error("Command must be one of %s (you gave '%s')" % (', '.join(sorted(commands.keys())), command))

    handler = commands[command](parser)
    handler(options, args[1:])
Beispiel #23
0
def parse_cmdline():
    parser_opts = {
        'usage': 'usage: %prog [options] repo_folder ics_outfile',
        'description': 'Export daily commits count from git repo history' \
            ' as daily calendar events',
        'version': __version__
    }
    parser = OptionParser(**parser_opts)
    parser.add_option('-a', '--split-authors', action='store_true', \
        dest='split_authors', default=False, help='split events by author')
    parser.add_option('-d', '--days', type='int', dest='last_days', \
        default=30, metavar='INT', help='output last INT days, 0=today,' \
        '1=today+yesterday, etc. (default 30)')
    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.print_usage()
        parser.exit(2)

    repo = args[0]
    outfile = args[1]
    if not exists(join(repo, 'config')) or not exists(join(repo, 'refs')):
        repo = join(repo, '.git')
        if not exists(join(repo, 'config')) or not exists(join(repo, 'refs')):
            parser.exit(2, 'Specified path does not seem like a git repo\n')

    return options.split_authors, options.last_days, repo, outfile
def ParseInputs():
  """Interprets command line parameters and checks for required parameters.

  Returns:
    The options object of parsed command line options.
  """

  parser = OptionParser()
  parser.add_option('--consumer_key', dest='consumer_key',
                    help='The OAuth consumer key for the domain')
  parser.add_option('--consumer_secret', dest='consumer_secret',
                    help='The OAuth consumer secret for the domain')
  parser.add_option('--user', dest='user',
                    help='The email address of the user to reinject messages')
  parser.add_option('--query', dest='query',
                    help='A Gmail query to identify messages for reinjection')
  parser.add_option('--restrict_domains_file', dest='restrict_domains_file',
                    help='A file containing a list of domains to restrict '
                    'reinjection to')
  parser.add_option('--completed_label', dest='completed_label',
                    help='A label to add to all reinjected messages')
  parser.add_option('--remove_from_subject', dest='remove_from_subject',
                    help='Text to remove from the subject header')
  parser.add_option('--threads', dest='threads', default=1,
                    help='The number of IMAP connections to open. Default = 1'
                    'simultaneously', type='int')
  parser.add_option('--imap_debug_level', dest='imap_debug_level', default=0,
                    help='[OPTIONAL] Sets the imap debug level\n'
                    '   Change this to a higher number to enable console debug',
                    type='int')

  (options, args) = parser.parse_args()
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

  invalid_arguments = False
  search_terms = 0

  if options.consumer_key is None:
    print '--consumer_key is required'
    invalid_arguments = True

  if options.consumer_secret is None:
    print '--consumer_secret is required'
    invalid_arguments = True

  if options.user is None:
    print '--user is required'
    invalid_arguments = True

  if options.query is None:
    print '--query is required'
    invalid_arguments = True

  if invalid_arguments:
    sys.exit(1)

  return options
Beispiel #25
0
def main():
    parser = OptionParser(usage="%prog <options>")
    parser.add_option("--offline", action="store_true", dest="offline", default=False, help="Start without using pulse")
    parser.add_option(
        "--test-manifest",
        action="store",
        dest="testmanifest",
        default=os.path.join("tests", "all-tests.ini"),
        help="Specify the test manifest, defaults to tests/all-tests.ini",
    )
    parser.add_option(
        "--log-file",
        action="store",
        dest="logfile",
        default="b2gautomation.log",
        help="Log file to store results, defaults to b2gautomation.log",
    )

    LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR")
    LEVEL_STRING = ", ".join(LOG_LEVELS)
    parser.add_option(
        "--log-level",
        action="store",
        type="choice",
        dest="loglevel",
        default="DEBUG",
        choices=LOG_LEVELS,
        help="One of %s for logging level, defaults  to debug" % LEVEL_STRING,
    )
    options, args = parser.parse_args()

    if not options.testmanifest:
        parser.print_usage()
        parser.exit()

    if not os.path.exists(options.testmanifest):
        print "Could not find manifest file: %s" % options.testmanifest
        parser.print_usage()
        parser.exit()

    # Set up the logger
    if os.path.exists(options.logfile):
        os.remove(options.logfile)

    logger = mozlog.getLogger("B2G_AUTOMATION", options.logfile)
    if options.loglevel:
        logger.setLevel(getattr(mozlog, options.loglevel, "DEBUG"))

    try:
        b2gauto = B2GAutomation(options.testmanifest, offline=options.offline)
        # this is test code
        d = b2gauto.install_build("http://10.242.30.20/out/qemu_package.tar.gz")
        b2gauto.run_marionette(d)
    except:
        s = traceback.format_exc()
        logger.error(s)
        return 1
    return 0
Beispiel #26
0
def main():
    parser = OptionParser("%prog [OPTIONS] [LOCALES...] - create multilocale Gaia")
    parser.add_option("-v", "--verbose", 
                      action="count", dest="verbose", default=2,
                      help="use more to make louder")
    parser.add_option("-i", "--ini", 
                      action="store_true", dest="onlyini",  default=False,
                      help=("just edit the ini files and exit; "
                            "use this with DEBUG=1 make profile"))
    parser.add_option("--target", 
                      action="append", dest="target",
                      help=("path to directory to make changes in "
                            "(more than one is fine)"))
    parser.add_option("--source", 
                      action="store", dest="source",
                      help="path to the l10n basedir")
    parser.add_option("--config", 
                      action="store", dest="config_file",
                      help=("path to the languages.json config file; "
                            "will be used instead of LOCALES"))

    options, locales = parser.parse_args()

    setup_logging(volume=options.verbose)
    log = logging.getLogger(__name__)

    if options.config_file is not None:
        locales = _get_locales(options.config_file)
        log.debug("config file specified; ignoring any locales passed as args")
    elif len(locales) == 0:
        parser.error("You need to specify --config or pass the list of locales")
    if options.target is None:
        parser.error("You need to specify at least one --target")
    if options.source is None and not options.onlyini:
        parser.error("You need to specify --source (unless you meant --ini)")

    if "en-US" in locales:
        locales.remove("en-US")
    ini_files = find_files(options.target, "*.ini")

    # 1. link properties files from the inis
    for ini_file in ini_files:
        log.info("########## adding locale import rules to %s" % ini_file)
        add_locale_imports(locales, ini_file)

    if options.onlyini:
        parser.exit(1)

    # 2. copy properties files as per the inis
    for ini_file in ini_files:
        log.info("########## copying locale files as per %s" % ini_file)
        copy_properties(options.source, locales, ini_file)

    # 3. edit manifests
    manifest_files = find_files(options.target, 'manifest.webapp')
    for manifest_file in manifest_files:
        log.info("########## adding localized names to %s" % manifest_file)
        add_locale_manifest(options.source, locales, manifest_file)
def ParseInputs():
  """Interprets command line parameters and checks for required parameters.

  Returns:
    The options object of parsed command line options.
  """

  parser = OptionParser()
  parser.add_option('-u', dest='admin_user',
                    help="""The admin user. Use full email address.
                            Operator will be prompted for password.""")
  parser.add_option('-d', dest='domain',
                    help='The Google Apps domain name.')
  parser.add_option('-f', dest='sender_address',
                    help='The address to include in the from address.')
  parser.add_option('--generate_password', action='store_true', default=False,
                    help="""OPTIONAL: If specified, password column in input
                            file will be ignored and password will be generated
                            for each user.""")
  parser.add_option('-l', dest='generated_password_length',
                    default=8, type='int',
                    help="""OPTIONAL: The generated password length desired.
                            Defaults to 8 characters.""")
  parser.add_option('-i', dest='input_file',
                    help="""CSV file with list of users.
                            File must have a header with the fields:
                               username, password""")

  (options, args) = parser.parse_args()
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

  invalid_arguments = False
  if options.admin_user is None:
    print '-u (admin_user) is required'
    invalid_arguments = True
  if options.domain is None:
    print '-d (domain) is required'
    invalid_arguments = True
  if options.sender_address is None:
    print '-f (sender_address) is required'
    invalid_arguments = True
  if options.input_file is None:
    print '-i (input_file) is required'
    invalid_arguments = True

  # Verify that password length is > 8 chars
  # which is required by Provisioning API
  if options.generated_password_length < 8:
    print 'Passwords must be at least 8 characters'
    invalid_arguments = True

  if invalid_arguments:
    sys.exit(1)

  return options
Beispiel #28
0
def main(argv):
	parser = OptionParser()
	parser.add_option("-f", "--firmware", action="store", dest="firmware", help="path to firmware", metavar="FILE")
	(options, args) = parser.parse_args()
	if options.firmware == None:
		parser.exit("Path to firmware not supplied, exiting")
	if os.path.isdir(options.firmware):
		print >>sys.stderr, "%s is not a file" % options.firmware
		sys.exit(1)

	findpadding(options.firmware)
def ParseInputs():
  """Interprets command line parameters and checks for required parameters."""
  usage = """%prog -d <domain> -u <admin user> -p <admin password>
               -i <input_file>
              [-t <# threads> -r <max_retries>]"""
  parser = OptionParser(usage=usage)
  parser.add_option('-d', dest='domain',
                    help="""The Google Apps domain.""")
  parser.add_option('-u', dest='admin_user',
                    help="""Admin user for the Provisioning API,
                            e.g. [email protected].""")
  parser.add_option('-p', dest='admin_pass',
                    help="""Admin password for the Provisioning API.""")
  parser.add_option('-i', dest='input_file',
                    help="""Input file containing forwarding mappings..""")
  parser.add_option('-t', dest='threads', default=1, type='int',
                    help="""Number of threads to spawn, max of 100.""")
  parser.add_option('-r', dest='max_retries', default=12, type='int',
                    help="""Maximum number of retries before skipping user.""")

  (options, args) = parser.parse_args()

  # series of if's to check our flags
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))
  if not options:
    parser.print_help()
    sys.exit(1)

  invalid_args = False
  if options.domain is None:
    print '-d (domain) is required'
    invalid_args = True
  if options.admin_user is None:
    print '-u ([email protected]) is required'
    invalid_args = True
  if options.admin_pass is None:
    print '-p (admin pass) is required'
    invalid_args = True
  if options.input_file is None:
    print '-i (input_file) is required'
    invalid_args = True

  if invalid_args:
    sys.exit(4)

  # A check on the MAX_THREAD_VALUE from above
  if options.threads > MAX_THREAD_VALUE:
    logging.info('Threads cannot exceed %d, using %d threads instead of %d',
                 MAX_THREAD_VALUE, MAX_THREAD_VALUE, options.threads)
    options.threads = MAX_THREAD_VALUE

  return options
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option("-d", dest="domain", help="The domain name to log into.")
    parser.add_option("-u", dest="admin_user", help="The admin user to use for authentication.")
    parser.add_option("-p", dest="admin_pass", help="The admin user's password")
    parser.add_option(
        "--mailuser",
        dest="mailuser",
        help="""Username to add Send Mail As setting to.
                            (just username without domain)""",
    )
    parser.add_option("-n", dest="name", help="""Name to be given to email address.""")
    parser.add_option("--email_address", dest="email_address", help="""Email address to set as a Send Mail As.""")
    parser.add_option(
        "--make_default",
        dest="make_default",
        action="store_true",
        default=False,
        help="""Makes this email address the default Send Mail As.
                            DEFAULT: is False""",
    )

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg="\nUnexpected arguments: %s\n" % " ".join(args))

    invalid_args = False
    if options.domain is None:
        print "-d (domain) is required"
        invalid_args = True
    if options.admin_user is None:
        print "-u (admin user) is required"
        invalid_args = True
    if options.admin_pass is None:
        print "-p (admin password) is required"
        invalid_args = True
    if options.mailuser is None:
        print "--mailuser (mailuser) is required"
        invalid_args = True
    if options.name is None:
        print "-n (name) is required"
        invalid_args = True
    if options.email_address is None:
        print "--email_address (email_address) is required"
        invalid_args = True

    if invalid_args:
        sys.exit(4)

    return options
def ParseInputs():
  """Interprets command line parameters and checks for required parameters."""
  usage = """%prog -k <consumer key> -s <consumer secret> -u <admin user> -p
              <admin password>"""
  parser = OptionParser(usage=usage)
  parser.add_option('-k', dest='consumer_key',
                    help='The consumer key.')
  parser.add_option('-s', dest='consumer_secret',
                    help='The consumer secret.')
  parser.add_option('-u', dest='calendar_user',
                    help='The calendar user to change defaults on.')
  parser.add_option('-b', dest='begin_date',
                    help='Begin Date for calendar range query in YYYY-MM-DD')
  parser.add_option('-e', dest='end_date',
                    help='End Date for calendar range query in YYYY-MM-DD')

  (options, args) = parser.parse_args()

  # series of if's to check our flags
  invalid_args = False
  if args:
    parser.print_help()
    parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))
  if not options:
    parser.print_help()
    invalid_args = True
  if options.consumer_key is None:
    print '-k (consumer_key) is required'
    invalid_args = True
  if options.consumer_secret is None:
    print '-s (consumer_secret) is required'
    invalid_args = True
  if options.calendar_user is None:
    print '-u (calendar_user) is required'
    invalid_args = True
  if options.begin_date is None:
    print '-b (begin_date) is required'
    invalid_args = True
  if options.end_date is None:
    print '-e (end_date) is required'
    invalid_args = True

  if invalid_args:
    sys.exit(1)

  return options
Beispiel #32
0
def parse_args():
    parser = OptionParser(
        usage='%prog [options] <directory>',
        version='Repository Sorter',
        description='Search files in a repository for ident strings'
        ' and order the files by the date of their last change.')

    parser.add_option('-t',
                      '--type',
                      choices=TYPES.keys() + ['auto'],
                      dest='type',
                      default='auto',
                      help='repository type: %s or auto (default)' %
                      ', '.join(TYPES.keys()))

    parser.add_option('-a',
                      '--authors',
                      action='store_true',
                      dest='authors',
                      default=False,
                      help='display last authors')

    parser.add_option('-n',
                      '--num-lines',
                      dest='num_lines',
                      type='int',
                      default=10,
                      help='maximum number of lines to scan')

    # Process options and arguments.
    opts, args = parser.parse_args()
    if len(args) != 1:
        parser.print_help()
        parser.exit()

    # Autodetect repository type.
    if opts.type == 'auto':
        opts.type = autodetect_type(args[0])
        if opts.type is None:
            parser.exit(msg='Auto-detection of repository type failed.'
                        ' Please specify a type.\n')
        print('Auto-detection assumes this is a %s repository.\n' %
              opts.type.upper())

    return opts, args
def CHECK_ARGV():
    m_argv = {}
    usage = "usage: %prog [options] arg1 arg2" 
    parser = OptionParser(usage=usage,version="%prog 1.0")
    parser.add_option("-w","--url",dest="url",
           help=" url. like http://www.me.com",metavar="WEBURL")
    parser.add_option("-t","--top",dest="topmeizi",
            help="show the top of dbmeizi,default use page options",metavar="TOPMEIZI")
    parser.add_option("-p","--page",dest="page",default="1-3",
            help="dbmeizi page you can like --page=4 or --page=1-3,default --page=1-3",metavar="PAGE")
    (options,args) = parser.parse_args()
    len_argv=len(sys.argv[1:])
    if len_argv == 0 :
        print parser.print_help()
        parser.exit(1)
    m_argv=str(parser.values)
    exec("m_argv="+m_argv)
    return m_argv
Beispiel #34
0
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option('-d',
                      dest='domain',
                      help='The domain name in which to add groups.')
    parser.add_option('-u',
                      dest='admin_user',
                      help='The admin user to use for authentication.')
    parser.add_option('-p',
                      dest='admin_pass',
                      help="The admin user's password")
    parser.add_option('-o',
                      dest='users_output_filename',
                      default='users.csv',
                      help='The output file to write the user data to.')
    parser.add_option('-k', dest='consumer_key', help="""The consumer key.""")
    parser.add_option('-s',
                      dest='consumer_secret',
                      help="""The consumer secret.""")

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

    if options.domain is None:
        print '-d (domain) is required'
        sys.exit(1)
    if options.admin_user is None:
        print '-u (admin user) is required'
        sys.exit(1)
    if options.admin_pass is None:
        print '-p (admin password) is required'
        sys.exit(1)
    if options.consumer_key is None:
        print '-k (consumer_key) is required'
        sys.exit(1)
    if options.consumer_secret is None:
        print '-s (consumer_secret) is required'
        sys.exit(1)

    return options
Beispiel #35
0
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option('-d',
                      dest='domain',
                      help='The domain name in which to add groups.')
    parser.add_option('-u',
                      dest='admin_user',
                      help='The admin user to use for authentication.')
    parser.add_option('-p',
                      dest='admin_pass',
                      help="The admin user's password")
    parser.add_option('-g',
                      dest='groups_output_filename',
                      default='groups.csv',
                      help='The output file to write the group data to.')
    parser.add_option('-m',
                      dest='members_output_filename',
                      default='members.csv',
                      help="""The output file to write the members data to.""")
    parser.add_option('-n',
                      dest='new_domain_name',
                      help="""If present, will replace the domain (-d) with
                            this new domain name in the email addresses for the
                            groups as well as members.""")

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

    if options.domain is None:
        print '-d (domain) is required'
        sys.exit(1)
    if options.admin_user is None:
        print '-u (admin user) is required'
        sys.exit(1)
    if options.admin_pass is None:
        print '-p (admin password) is required'
        sys.exit(1)

    return options
def main(args=sys.argv[1:]):

    # parse command line options
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-p',
                      '--port',
                      dest='port',
                      type="int",
                      default=8888,
                      help="port to run the server on [DEFAULT: %default]")
    parser.add_option('-H',
                      '--host',
                      dest='host',
                      default='127.0.0.1',
                      help="host [DEFAULT: %default]")
    parser.add_option('-i',
                      '--external-ip',
                      action="store_true",
                      dest='external_ip',
                      default=False,
                      help="find and use external ip for host")
    parser.add_option('-d',
                      '--docroot',
                      dest='docroot',
                      default=os.getcwd(),
                      help="directory to serve files from [DEFAULT: %default]")
    options, args = parser.parse_args(args)
    if args:
        parser.error("mozhttpd does not take any arguments")
        parser.print_help()
        parser.exit()

    if options.external_ip:
        host = iface.get_lan_ip()
    else:
        host = options.host

    # create the server
    server = MozHttpd(host=host, port=options.port, docroot=options.docroot)

    print "Serving '%s' at %s:%s" % (server.docroot, server.host, server.port)
    server.start(block=True)
Beispiel #37
0
def main():
    parser = OptionParser(
        usage="Usage: renderxml.py map.xml",
        description="Renders a mapgen2 XML file using Panda3D")
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.print_help()
        parser.exit(1, "Wrong number of arguments.\n")

    if not os.path.isfile(args[0]):
        parser.print_help()
        parser.exit(1, "Input file '%s' is not a valid file.\n" % args[0])

    fname = args[0]
    map = MapGenXml(fname)

    map.print_info()
    visualize(map.centers, map.corners, map.edges)
Beispiel #38
0
    def get_option_parser(self, program_name):
        from optparse import OptionParser, SUPPRESS_HELP

        parser = OptionParser(prog=program_name,
                              usage="%prog [OPTION]... FILE...",
                              description="Put files in trash",
                              version="%%prog %s" % version,
                              formatter=NoWrapFormatter(),
                              epilog="""\
To remove a file whose name starts with a '-', for example '-foo',
use one of these commands:

    trash -- -foo

    trash ./-foo

Report bugs to https://github.com/andreafrancia/trash-cli/issues""")

        parser.add_option("-d", "--directory",
                          action="store_true",
                          help="ignored (for GNU rm compatibility)")
        parser.add_option("-f", "--force",
                          action="store_true",
                          dest="ignore_missing",
                          help="silently ignore nonexistent files")
        parser.add_option("-i", "--interactive",
                          action="store_true",
                          help="ignored (for GNU rm compatibility)")
        parser.add_option("-r", "-R", "--recursive",
                          action="store_true",
                          help="ignored (for GNU rm compatibility)")
        parser.add_option("--trash-dir",
                          type='string',
                          action="store", dest='trashdir',
                          help='use TRASHDIR as trash folder')
        parser.add_option("-v",
                          "--verbose",
                          action="store_true",
                          dest="verbose",
                          help="explain what is being done")
        original_print_help = parser.print_help
        def patched_print_help():
            original_print_help(self.stdout)
        def patched_error(msg):
            parser.print_usage(self.stderr)
            parser.exit(2, "%s: error: %s\n" % (program_name, msg))
        def patched_exit(status=0, msg=None):
            if msg: self.stderr.write(msg)
            import sys
            sys.exit(status)

        parser.print_help = patched_print_help
        parser.error = patched_error
        parser.exit = patched_exit
        return parser
def getOptions():
    optParser = OptionParser()
    optParser.add_option("-v", "--verbose", action="store_true", default=False,
                         help="tell me what you are doing")
    optParser.add_option("-n", "--net-file", dest="netfile", help="the network to read lane and edge permissions")
    optParser.add_option("-o", "--output", help="output taz file")
    optParser.add_option("-w", "--grid-width", dest="gridWidth", type="float", default=100.0,
                         help="width of gride cells in m")
    optParser.add_option("-u", "--hue", default="random",
                         help="hue for taz (float from [0,1] or 'random')")
    optParser.add_option("-s", "--saturation", default=1,
                         help="saturation for taz (float from [0,1] or 'random')")
    optParser.add_option("-b", "--brightness", default=1,
                         help="brightness for taz (float from [0,1] or 'random')")
    (options, args) = optParser.parse_args()
    if not options.netfile or not options.output:
        optParser.print_help()
        optParser.exit("Error! net-file and output file")
    options.colorgen = Colorgen((options.hue, options.saturation, options.brightness))
    return options
Beispiel #40
0
def main(args=sys.argv[1:]):

    # parse command line options
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-p',
                      '--port',
                      dest='port',
                      type="int",
                      default=8888,
                      help="port to run the server on [DEFAULT: %default]")
    parser.add_option('-H',
                      '--host',
                      dest='host',
                      default='127.0.0.1',
                      help="host [DEFAULT: %default]")
    parser.add_option('-d',
                      '--docroot',
                      dest='docroot',
                      default=os.getcwd(),
                      help="directory to serve files from [DEFAULT: %default]")
    parser.add_option('--test',
                      dest='test',
                      action='store_true',
                      default=False,
                      help='run the tests and exit')
    options, args = parser.parse_args(args)
    if args:
        parser.print_help()
        parser.exit()

    # create the server
    kwargs = options.__dict__.copy()
    test = kwargs.pop('test')
    server = MozHttpd(**kwargs)

    if test:
        server.start()
        server.testServer()
    else:
        server.start(block=True)
def ParseInputs():
    parser = OptionParser()
    parser.add_option('-d', dest='domain', help="""Domain""")
    parser.add_option('-u', dest='admin_user', help="""Admin user""")
    parser.add_option('-p', dest='admin_pass', help="""Admin password""")
    parser.add_option(
        '--profile_to_change',
        dest='profile_to_change',
        help="""OPTIONAL:Single username (without domain) to search.
                            Otherwise this will search all profiles.""")
    parser.add_option('-a',
                      dest='apply',
                      action='store_true',
                      default=False,
                      help="""Unless this flag is present, this runs
                            in a Dry Run mode making no changes""")

    (options, args) = parser.parse_args()

    # series of if's to check our flags
    invalid_args = False
    if args:
        parser.print_help()
        parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))
    if not options:
        parser.print_help()
        invalid_args = True
    if options.domain is None:
        print '-d (domain) is required'
        invalid_args = True
    if options.admin_user is None:
        print '-u ([email protected]) is required'
        invalid_args = True
    if options.admin_pass is None:
        print '-p (admin pass) is required'
        invalid_args = True

    if invalid_args:
        sys.exit(3)

    return options
Beispiel #42
0
def parse_args():
    parser = OptionParser(usage='usage: %prog [options] <filename>')

    parser.add_option(
        '-g', '--group',
        dest='group',
        action='store_true',
        help='list contacts by groups')

    parser.add_option(
        '-j', '--jids-only',
        dest='jids_only',
        action='store_true',
        help='only show JIDs (overrides `-g`)')

    opts, args = parser.parse_args()
    if not args:
        parser.print_help()
        parser.exit()

    return opts, args
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option('-d',
                      dest='domain',
                      help='The domain name in which to add groups.')
    parser.add_option('-u',
                      dest='admin_user',
                      help='The admin user to use for authentication.')
    parser.add_option('-p',
                      dest='admin_pass',
                      help="The admin user's password")
    parser.add_option('-g',
                      dest='groups_file',
                      help='The input file containing groups to create.')
    parser.add_option('-m',
                      dest='members_file',
                      help="""The input file containing the members
                            to add to the groups.""")

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

    if options.domain is None:
        print '-d (domain) is required'
        sys.exit(1)
    if options.admin_user is None:
        print '-u (admin user) is required'
        sys.exit(1)
    if options.admin_pass is None:
        print '-p (admin password) is required'
        sys.exit(1)
    if options.groups_file is None and options.members_file is None:
        print 'Either -g (groups file) or -m (members file) is required'
        sys.exit(1)

    return options
Beispiel #44
0
def main():
    parser = OptionParser(
        usage="Usage: map2collada.py -o file.dae map.xml",
        description="Converts mapgen2 XML file to COLLADA using pycollada")
    parser.add_option("-o",
                      "--outfile",
                      dest="outfile",
                      help="write DAE to FILE",
                      metavar="OUTFILE")
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.print_help()
        parser.exit(1, "Wrong number of arguments.\n")

    if not os.path.isfile(args[0]):
        parser.print_help()
        parser.exit(1, "Input file '%s' is not a valid file.\n" % args[0])

    if options.outfile is None:
        parser.print_help()
        parser.exit(1, "Must specify an output file.\n")

    fname = args[0]
    map = MapGenXml(fname)
    map.print_info()
    dae, texture = tocollada(map.centers, map.corners, map.edges)

    generateNormals(dae)
    dae.write(options.outfile)

    texpath = os.path.join(os.path.dirname(options.outfile), 'texture.jpg')
    texture.save(texpath, format="JPEG", quality=95, optimize=True)
Beispiel #45
0
def cli():
    parser = OptionParser(usage='%prog gaia_atoms_path app_name [app_name] ...')

    options, args = parser.parse_args()

    if not args:
        parser.print_usage()
        parser.exit()

    if not os.path.isdir(args[0]):
        parser.print_usage()
        print 'must specify valid path for gaia atoms'
        parser.exit()

    if len(args) != 2:
        parser.print_usage()
        print 'must specify at one app name'
        parser.exit()

    marionette = Marionette(host='localhost', port=2828)  # TODO command line option for address
    marionette.start_session()
    launchApp(
        marionette,
        gaia_atoms=args[0],
        app_name=args[1])
def main():
    parser = OptionParser(
        usage="Usage: generate-scene.py -o scene map.xml",
        description=
        "Generates a JSON scene based on mapgen2 XML output, using meshes from open3dhub"
    )
    parser.add_option(
        "-o",
        "--outname",
        dest="outname",
        help=
        "write JSON scene to {outname}.json and Emerson script to {outname}.em",
        metavar="OUTNAME")
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.print_help()
        parser.exit(1, "Wrong number of arguments.\n")

    if not os.path.isfile(args[0]):
        parser.print_help()
        parser.exit(1, "Input file '%s' is not a valid file.\n" % args[0])

    if options.outname is None:
        parser.print_help()
        parser.exit(1, "Must specify an output name.\n")

    fname = args[0]
    map = MapGenXml(fname)
    models = get_models()

    terrain = scene.SceneModel(TERRAIN_PATH,
                               x=0,
                               y=0,
                               z=0,
                               scale=1000,
                               model_type='terrain')
    json_out = []
    print 'Generated (1) terrain object'
    json_out.append(terrain.to_json())

    generate_houses_and_trees(models, terrain, map, json_out)
    generate_winter(models, terrain, map, json_out)
    generate_roads(models, terrain, map, json_out)
    generate_vehicles(models, terrain, map, json_out)
    generate_flying(models, terrain, map, json_out)
    generate_boats(models, terrain, map, json_out)

    json_str = json.dumps(json_out, indent=2)

    json_name = options.outname + '.json'
    with open(json_name, 'w') as f:
        f.write(json_str)

    em_name = options.outname + '.em'
    with open(em_name, 'w') as f:
        f.write('var OBJECTS = ')
        f.write(json_str)
        f.write(';\n')
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option('--domain', dest='domain', help='The target domain.')
    parser.add_option('--id',
                      dest='oauth_client_id',
                      help='The OAuth client id')
    parser.add_option('--secret',
                      dest='oauth_client_secret',
                      help='The OAuth client secret.')
    parser.add_option('--refresh_token',
                      dest='oauth_refresh_token',
                      help='The OAuth 2.0 refresh token to use.'
                      ' (to bypass the auth flow)')
    parser.add_option('--access_token',
                      dest='oauth_access_token',
                      help='The OAuth 2.0 access token to use.'
                      ' (to bypass the auth flow)')

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

    missing_args = False
    if options.domain is None:
        print '--domain is required'
        missing_args = True
    if options.oauth_client_id is None:
        print '--id (client_id) is required'
        missing_args = True
    if options.oauth_client_secret is None:
        print '--secret (client_secret) is required'
        missing_args = True
    if missing_args:
        sys.exit(4)

    return options
def parse_args():
    usage = "usage: %prog [options] module function"
    parser = OptionParser(usage=usage,
                          version="%prog 1.0",
                          conflict_handler="resolve")
    parser.add_option("--run",
                      dest="run",
                      action='store_true',
                      help="Execute",
                      default=False)

    module, function = get_modfunc(sys.argv[1:])
    parser, interface = add_options(parser, module, function)
    (options, args) = parser.parse_args()
    if options.run and interface:
        #assign inputs
        run_instance(interface, options)
    else:
        parser.print_help()
        if module and not function:
            listClasses(module)
        parser.exit()
Beispiel #49
0
def main():
    parser = OptionParser(usage="Usage: renderscene.py scene.json",
                          description="Renders a JSON scene file")
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.print_help()
        parser.exit(1, "Wrong number of arguments.\n")

    if not os.path.isfile(args[0]):
        parser.print_help()
        parser.exit(1, "Input file '%s' is not a valid file.\n" % args[0])

    fname = args[0]
    json_data = json.load(open(fname))

    print 'Fetching models'
    models = [scene.SceneModel.from_json(j) for j in json_data]

    print 'Starting scene'
    r = SceneRenderer(models)
    r.run()
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option('-d',
                      dest='domain',
                      help='The domain name in which to add groups.')
    parser.add_option('-u',
                      dest='admin_user',
                      help='The admin user to use for authentication.')
    parser.add_option('-p',
                      dest='admin_pass',
                      help="The admin user's password")
    parser.add_option('-m',
                      dest='member',
                      help="""The member of the group for which we want to
                            find all groups where they are owner.""")

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

    if options.domain is None:
        print '-d (domain) is required'
        sys.exit(1)
    if options.admin_user is None:
        print '-u (admin user) is required'
        sys.exit(1)
    if options.admin_pass is None:
        print '-p (admin password) is required'
        sys.exit(1)
    if options.member is None:
        print '-m (member) is required'
        sys.exit(1)

    return options
Beispiel #51
0
    def get_option_parser(self, program_name):
        from optparse import OptionParser

        parser = OptionParser(prog=program_name,
                              usage="%prog [OPTION]... FILE...",
                              description="Put files in trash",
                              version="%%prog %s" % version,
                              formatter=NoWrapFormatter(),
                              epilog=epilog)
        parser.add_option("-d",
                          "--directory",
                          action="store_true",
                          help="ignored (for GNU rm compatibility)")
        parser.add_option("-f",
                          "--force",
                          action="store_true",
                          help="ignored (for GNU rm compatibility)")
        parser.add_option("-i",
                          "--interactive",
                          action="store_true",
                          help="ignored (for GNU rm compatibility)")
        parser.add_option("-r",
                          "-R",
                          "--recursive",
                          action="store_true",
                          help="ignored (for GNU rm compatibility)")
        parser.add_option("-v",
                          "--verbose",
                          action="store_true",
                          help="explain what is being done",
                          dest="verbose")

        def patched_print_help():
            encoding = parser._get_encoding(self.stdout)
            self.stdout.write(parser.format_help().encode(encoding, "replace"))

        def patched_error(msg):
            parser.print_usage(self.stderr)
            parser.exit(2, "%s: error: %s\n" % (program_name, msg))

        def patched_exit(status=0, msg=None):
            if msg: self.stderr.write(msg)
            import sys
            sys.exit(status)

        parser.print_help = patched_print_help
        parser.error = patched_error
        parser.exit = patched_exit
        return parser
Beispiel #52
0
def cmd_handler():
    parser = OptionParser()
    parser.add_option('--start',
                      dest='start',
                      default=False,
                      action='store_true',
                      help='start the api server.')
    parser.add_option('--stop',
                      dest='stop',
                      default=False,
                      action='store_true',
                      help='stop the api server.')
    parser.add_option('--restart',
                      dest='restart',
                      default=False,
                      action='store_true',
                      help='restart the api server.')

    (options, args) = parser.parse_args()

    if len(sys.argv) == 1:
        parser.print_help()
        parser.exit()
    return options, args
def ParseInputs():
    """Interprets command line parameters and checks for required parameters."""

    parser = OptionParser()
    parser.add_option('-d',
                      dest='domain',
                      help='The domain name to list sotes for.')
    parser.add_option('-u',
                      dest='oauth_requestor_id',
                      help='The admin user to use for authentication.')
    parser.add_option('-k',
                      dest='oauth_consumer_key',
                      help="The OAuth consumer key")
    parser.add_option('-s',
                      dest='oauth_consumer_secret',
                      help='The The OAuth consumer secret.')

    (options, args) = parser.parse_args()
    if args:
        parser.print_help()
        parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))

    if options.domain is None:
        print '-d (domain) is required'
        sys.exit(1)
    if options.oauth_requestor_id is None:
        print '-u (admin user) is required'
        sys.exit(1)
    if options.oauth_consumer_key is None:
        print '-k (consumer_key) is required'
        sys.exit(1)
    if options.oauth_consumer_secret is None:
        print '-s (consumer_secret) is required'
        sys.exit(1)

    return options
Beispiel #54
0
def main(args=None):
    "Entry-point for ``python -m mpi4py``"
    from optparse import OptionParser
    from . import __name__ as prog
    from . import __version__ as version
    parser = OptionParser(prog=prog,
                          version='%prog ' + version,
                          usage="%prog [options] <command> [args]")
    parser.add_option("--no-threads",
                      action="store_false",
                      dest="threads",
                      default=True,
                      help="initialize MPI without thread support")
    parser.add_option("--thread-level",
                      type="choice",
                      metavar="LEVEL",
                      choices=["single", "funneled", "serialized", "multiple"],
                      action="store",
                      dest="thread_level",
                      default="multiple",
                      help="initialize MPI with required thread support")
    parser.add_option("--mpe",
                      action="store_true",
                      dest="mpe",
                      default=False,
                      help="use MPE for MPI profiling")
    parser.add_option("--vt",
                      action="store_true",
                      dest="vt",
                      default=False,
                      help="use VampirTrace for MPI profiling")
    parser.disable_interspersed_args()
    (options, args) = parser.parse_args(args)

    from . import rc, profile
    rc.threads = options.threads
    rc.thread_level = options.thread_level
    if options.mpe:
        profile('mpe', logfile='mpi4py')
    if options.vt:
        profile('vt', logfile='mpi4py')

    from . import MPI
    comm = MPI.COMM_WORLD
    if not args:
        if comm.rank == 0:
            parser.print_usage()
        parser.exit()
    command = args.pop(0)
    if command not in main.commands:
        if comm.rank == 0:
            parser.error("unknown command '%s'" % command)
        parser.exit(2)
    command = main.commands[command]
    command(comm, args=args)
    parser.exit()
Beispiel #55
0
def parse_options(args):
    """ Parses command line options """
    usage = 'usage: %prog [options] visio_filename image_filename'
    parser = OptionParser(usage=usage)
    parser.add_option('-p', '--page', action='store',
                      type='int', dest='pagenum',
                      help='pick a page by page number')
    parser.add_option('-n', '--name', action='store',
                      type='string', dest='pagename',
                      help='pick a page by page name')
    options, argv = parser.parse_args(args)

    if options.pagenum and options.pagename:
        parser.error('options --page and --name are mutually exclusive')

    if len(argv) != 2:
        parser.print_usage(sys.stderr)
        parser.exit()

    output_ext = os.path.splitext(argv[1])[1].lower()
    if output_ext not in ('.gif', '.jpg', '.png'):
        parser.error('Unsupported image format: %s' % argv[1])

    return options, argv
Beispiel #56
0
def main():
    parser = OptionParser(usage="usage: %prog options",
                          version="%prog " + version)
    parser.add_option("-d",
                      "--musicDirectory",
                      action="store",
                      dest="musicdir",
                      help="Der Ordner mit der Weckmusik")
    parser.add_option("-t",
                      "--wakeUpTime",
                      action="store",
                      dest="wakeuptime",
                      help="Die Weckzeit (z.B.: \"06:10:15\")")
    parser.add_option("-i",
                      "--snoozeInterval",
                      action="store",
                      dest="snoozeinterval",
                      help="Das Snooze-Interval in Sekunden")

    (options, args) = parser.parse_args()

    if args or not options.musicdir or not options.wakeuptime or not options.snoozeinterval:
        parser.print_help()
        parser.exit(1, "Bitte alle Optionen angeben! STOP\n")

    try:
        snoozeInterval = int(options.snoozeinterval)
    except:
        parser.exit(1, "Snooze-Interval war keine gültige Zahl!\n")

    try:
        wakeupTime_dt = time.strptime(options.wakeuptime, '%H:%M:%S')
        wakeupTime = time.strftime("%H:%M:%S", wakeupTime_dt)
        #str(wakeupTime_dt.tm_hour)+":"+str(wakeupTime_dt.tm_min)+":"+str(wakeupTime_dt.tm_sec)

    except:
        parser.exit(
            1,
            "Angegebene Weckzeit war ungültig!\n\t Weckzeit-Format: \"HH:MM:SS\", z.B.:\"06:10:15\"\n"
        )

    player = MP3Player(options.musicdir)
    alarm_clock(wakeupTime, player, snoozeInterval)
Beispiel #57
0
optParser.add_option("-d",
                     "--delta",
                     default="1",
                     type="float",
                     help="maximum distance between end points")
optParser.add_option("-o",
                     "--output",
                     dest="output",
                     help="(base) name for the output",
                     metavar="FILE")
optParser.add_option("--edges1", help="matched edges in net 1", metavar="FILE")
optParser.add_option("--edges2", help="matched edges in net 2", metavar="FILE")
(options, args) = optParser.parse_args()

if not options.output or not options.net1 or not options.net2:
    optParser.exit("missing input or output")

# read networks
if options.verbose:
    print("Reading net#1...")
net1 = sumolib.net.readNet(options.net1)
net1.move(-net1.getLocationOffset()[0], -net1.getLocationOffset()[1])

if options.verbose:
    print("Reading net#2...")
net2 = sumolib.net.readNet(options.net2)
net2.move(-net2.getLocationOffset()[0], -net2.getLocationOffset()[1])

f = open(options.output, "w")

matchedEdges1 = set()
Beispiel #58
0
def cli():
    parser = OptionParser(usage='%prog [options] <test_file> <test_file> ...')
    parser.add_option("--binary",
                      action="store",
                      dest="binary",
                      default=None,
                      help="path to B2G desktop build binary")
    parser.add_option("--profile",
                      action="store",
                      dest="profile",
                      default=None,
                      help="path to gaia profile directory")

    options, tests = parser.parse_args()

    if not options.binary or not options.profile:
        parser.print_usage()
        parser.exit('--binary and --profile required')

    if not tests:
        # Read in a list of tests to skip from disabled.json, if it exists;
        # disabled.json should contain filenames with paths relative to the
        # apps directory, e.g., "wallpaper/test/unit/pick_test.js".
        disabled = []
        disabled_file = os.path.join(os.path.dirname(__file__),
                                     'disabled.json')
        if os.access(disabled_file, os.F_OK):
            with open(disabled_file, 'r') as f:
                disabled_contents = f.read()
                try:
                    disabled = json.loads(disabled_contents)
                except:
                    traceback.print_exc()
                    print "Error while decoding disabled.json; please make sure this file has valid JSON syntax."
                    sys.exit(1)

        # build a list of tests
        appsdir = os.path.join(
            os.path.dirname(os.path.abspath(options.profile)), 'apps')
        for root, dirs, files in os.walk(appsdir):
            for file in files:
                # only include tests in a 'unit' directory
                if os.path.basename(root) == 'unit':
                    full_path = os.path.relpath(os.path.join(root, file),
                                                appsdir)
                    if full_path.endswith(
                            '_test.js') and full_path not in disabled:
                        tests.append(full_path)

    runner = GaiaUnitTestRunner(binary=options.binary, profile=options.profile)
    runner.run()

    # Lame but necessary hack to prevent tornado's logger from duplicating
    # every message from mozlog.
    logger = logging.getLogger()
    handler = logging.NullHandler()
    logger.addHandler(handler)

    print 'starting WebSocket Server'
    application = tornado.web.Application([
        (r"/", TestAgentServer, {
            'tests': tests,
            'runner': runner,
            'logger': mozlog.getLogger('gaia-unit-tests')
        }),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8789)
    tornado.ioloop.IOLoop.instance().start()
Beispiel #59
0
        # Test the masters, once normally and onces as a universal master
        for m in masters:
            rc, logfile, dir = m.testMaster(
                options.buildbot, error_logs=options.error_logs)
            if rc != 0:
                failing_masters.append((m.name, logfile, dir))
        # Print a summary including a list of useful output
        log.info("TEST-SUMMARY: %s tested, %s failed" % (len(
            master_list), len(failing_masters)))
        for rc, logfile, dir in failing_masters:
            def s(n):
                if n is not None:
                    return n[len(os.getcwd()) + 1:]
            log.info("FAILED-MASTER %s, log: '%s', dir: '%s'" %
                     (rc, s(logfile), s(dir)))
        exit(len(failing_masters))
    elif len(args) == 2:
        master_dir, master_name = args[:2]

        if options.universal:
            master_name = master_name + '-universal'

        if master_name not in master_map:
            log.error("Unknown master %s" % master_name)

        m = master_map[master_name]
        m.createMaster(master_dir, options.buildbot)
    else:
        parser.print_usage()
        parser.exit()
Beispiel #60
0
def parse_options():
    parser = OptionParser(usage='%prog [options] test_file_or_dir <test_file_or_dir> ...')
    parser.add_option("--autolog",
                      action = "store_true", dest = "autolog",
                      default = False,
                      help = "send test results to autolog")
    parser.add_option("--revision",
                      action = "store", dest = "revision",
                      help = "git revision for autolog/perfdata submissions")
    parser.add_option("--testgroup",
                      action = "store", dest = "testgroup",
                      help = "testgroup names for autolog submissions")
    parser.add_option("--emulator",
                      action = "store", dest = "emulator",
                      default = None, choices = ["x86", "arm"],
                      help = "If no --address is given, then the harness will launch a B2G emulator "
                      "on which to run emulator tests. If --address is given, then the harness assumes you are "
                      "running an emulator already, and will run the emulator tests using that emulator. "
                      "You need to specify which architecture to emulate for both cases.")
    parser.add_option("--emulator-binary",
                      action = "store", dest = "emulatorBinary",
                      default = None,
                      help = "Launch a specific emulator binary rather than "
                      "launching from the B2G built emulator")
    parser.add_option('--emulator-img',
                      action = 'store', dest = 'emulatorImg',
                      default = None,
                      help = "Use a specific image file instead of a fresh one")
    parser.add_option('--emulator-res',
                      action = 'store', dest = 'emulator_res',
                      default = None, type= 'str',
                      help = 'Set a custom resolution for the emulator. '
                      'Example: "480x800"')
    parser.add_option("--no-window",
                      action = "store_true", dest = "noWindow",
                      default = False,
                      help = "when Marionette launches an emulator, start it "
                      "with the -no-window argument")
    parser.add_option('--logcat-dir', dest='logcat_dir', action='store',
                      help='directory to store logcat dump files')
    parser.add_option('--address', dest='address', action='store',
                      help='host:port of running Gecko instance to connect to')
    parser.add_option('--device', dest='device', action='store',
                      help='serial ID of a device to use for adb / fastboot')
    parser.add_option('--type', dest='type', action='store',
                      default='browser+b2g',
                      help = "The type of test to run, can be a combination "
                      "of values defined in unit-tests.ini; individual values "
                      "are combined with '+' or '-' chars.  Ex:  'browser+b2g' "
                      "means the set of tests which are compatible with both "
                      "browser and b2g; 'b2g-qemu' means the set of tests "
                      "which are compatible with b2g but do not require an "
                      "emulator.  This argument is only used when loading "
                      "tests from .ini files.")
    parser.add_option('--homedir', dest='homedir', action='store',
                      help='home directory of emulator files')
    parser.add_option('--binary', dest='bin', action='store',
                      help='gecko executable to launch before running the test')
    parser.add_option('--profile', dest='profile', action='store',
                      help='profile to use when launching the gecko process. If not '
                      'passed, then a profile will be constructed and used.')
    parser.add_option('--perf', dest='perf', action='store_true',
                      default = False,
                      help='send performance data to perf data server')
    parser.add_option('--perf-server', dest='perfserv', action='store',
                      default=None,
                      help='dataserver for perf data submission. Entering this value '
                      'will overwrite the perfserv value in any passed .ini files.')
    parser.add_option('--repeat', dest='repeat', action='store', type=int,
                      default=0, help='number of times to repeat the test(s).')
    parser.add_option('-x', '--xml-output', action='store', dest='xml_output',
                      help='XML output.')
    parser.add_option('--gecko-path', dest='gecko_path', action='store',
                      default=None,
                      help='path to B2G gecko binaries that should be '
                      'installed on the device or emulator')
    parser.add_option('--testvars', dest='testvars', action='store',
                      default=None,
                      help='path to a JSON file with any test data required')
    parser.add_option('--tree', dest='tree', action='store',
                      default='b2g',
                      help='the tree that the revsion parameter refers to')

    options, tests = parser.parse_args()

    if not tests:
        parser.print_usage()
        parser.exit()

    if not options.emulator and not options.address and not options.bin:
        parser.print_usage()
        print "must specify --binary, --emulator or --address"
        parser.exit()

    # default to storing logcat output for emulator runs
    if options.emulator and not options.logcat_dir:
        options.logcat_dir = 'logcat'

    if options.perf:
        import datazilla

    # check for valid resolution string, strip whitespaces
    try:
        if options.emulator_res:
            dims = options.emulator_res.split('x')
            assert len(dims) == 2
            width = str(int(dims[0]))
            height = str(int(dims[1]))
            options.emulator_res = 'x'.join([width, height])
    except:
        raise ValueError('Invalid emulator resolution format. '
                         'Should be like "480x800".')

    return (options, tests)