Beispiel #1
0
def parseArguments(argv, print_help=True):
    ENABLE_DEFAULT_HELP_MESSAGE = False
    command = None

    if len(argv) >= 2:
        arg1 = argv[1]
        for cursor in CMD_MAP.keys():
            if cursor == arg1:
                command = cursor
                argv.pop(1)
                break

    parser = OptionParser(add_help_option=ENABLE_DEFAULT_HELP_MESSAGE)
    parser.set_usage('Usage: opm {COMMAND} {OPTIONS}')
    parser.add_option('-c', '--config-path',
                      dest='config_path',
                      metavar='PATH',
                      default=CONFIG_XML_PATH,
                      help='Set the configure file path.')
    options, args = parser.parse_args(argv)

    if print_help is True and (command is None or command == CMD_HELP):
        parser.print_help()
        printCommandHelp()

    return command, options
Beispiel #2
0
def parse():
    p = OptionParser()
    p.set_usage("command [options] privatekey")
    p.add_option('-p', '--publickey', dest = 'publickey', default = './p.pub')
    #p.add_option('-v', '--private', dest = 'vf')
    p.add_option('-t', '--type', dest = 'type', default = 'ssh-rsa')
    return p
Beispiel #3
0
class Attach():
	def __init__(self):
		self.git = Git()
		self.parser = OptionParser()
		self.parser.set_usage("mgit attach <subproject name>")

	def print_usage(self):
		self.parser.print_usage()

	def run(self, args):
		options, args = self.parser.parse_args(args[1:])
		if len(args) <= 0:
			self.parser.print_usage()
			return
	
		if len(args) > 1:
			module = args[1]
		else:
			module = self.git.module_name(args[0])
		if module == None or len(module) <= 0:
			return

		if not os.path.exists(module):
			print("module %s not exists." % module)
			return

		project = Project()
		project.append(module)
def parse_commandline():
    """Parse the comandline and return parsed options."""

    parser = OptionParser()
    parser.description = __doc__

    parser.set_usage("usage: %prog [options] (list|add|remove) [collaborator]." "\nTry %prog --help for details.")
    parser.add_option("-d", "--debug", action="store_true", help="Enables debugging mode")
    parser.add_option("-c", "--cache", default=None, help="Location for network cache [default: None]")
    parser.add_option("-l", "--login", help="Username to login with")
    parser.add_option(
        "-a", "--account", help="User owning the repositories to be changed " "[default: same as --login]"
    )
    parser.add_option(
        "-t", "--apitoken", help="API Token - can be found on the lower right of " "https://github.com/account"
    )

    options, args = parser.parse_args()
    if len(args) not in [1, 2]:
        parser.error("wrong number of arguments")
    if len(args) == 1 and args[0] in ["add", "remove"]:
        parser.error("%r needs a collaborator name as second parameter\n" % args[0])
    elif len(args) == 1 and args[0] != "list":
        parser.error('unknown command %r. Try "list", "add" or "remove"\n' % args[0])
    if len(args) == 2 and args[0] not in ["add", "remove"]:
        parser.error('unknown command %r. Try "list", "add" or "remove"\n' % args[0])
    if not options.login:
        parser.error("you must provide --login information\n")

    return options, args
def cmd_line():
    parser = OptionParser()
    parser.set_usage("yum-debug-restore [options]")
    parser.add_option("-C", "--cache", action="store_true",
                      help="run from cache only")
    parser.add_option("-c", dest="conffile", help="config file location")
    parser.add_option("--enablerepo", action="append", dest="enablerepos",
                      help="specify additional repoids to query, can be specified multiple times")
    parser.add_option("--disablerepo", action="append", dest="disablerepos",
                      help="specify repoids to disable, can be specified multiple times")                      
    parser.add_option("-y", dest="assumeyes", action="store_true",
                      help="answer yes for all questions")
    parser.add_option("--skip-broken", action="store_true",
                      help="skip packages with depsolving problems")

    parser.add_option("--output", action="store_true",
                      help="output the yum shell commands")
    parser.add_option("--shell", 
                      help="output the yum shell commands to a file")

    parser.add_option("--install-latest", action="store_true",
                      help="install the latest instead of specific versions")
    parser.add_option("--ignore-arch", action="store_true",
                      help="ignore arch of packages, so you can dump on .i386 and restore on .x86_64")

    parser.add_option("--filter-types", 
                      help="Limit to: install, remove, update, downgrade")

    (opts, args) = parser.parse_args()
    if not args:
        parser.print_usage()
        sys.exit(1)
    return (opts, args)
Beispiel #6
0
def optParse():
    """
    Parses commandline options.
    """
    parser = OptionParser(
        prog=__applicationName__, version="%prog " + __version__)

    parser.set_usage("%prog [options] filename")
    parser.add_option("--autobrief",
                      action="store_true", dest="autobrief",
                      help="use the docstring summary line as @brief description"
                      )
    parser.add_option("--debug",
                      action="store_true", dest="debug",
                      help="enable debug output on stderr"
                      )

    # parse options
    global options
    (options, filename) = parser.parse_args()

    if not filename:
        sys.stderr.write("No filename given.")
        sys.exit(-1)

    return filename[0]
def main():
	parser = OptionParser(conflict_handler="resolve")
	parser.set_usage("mail-instance-creator.py <from-email-address> <to-email-address> <languagecode> <wikiaddress>\n\n\texample: mail-instance-creator.py 'test@example.com' 'es' 'http://example.com/w/'")

	(options, args) = parser.parse_args()

	if len(args) != 4:
		parser.error("mail-instance-creator.py expects exactly four arguments.")

	fromaddress = args[0]
	toaddress = args[1]
	lang = args[2]
	wikiaddress = args[3]
	subjecturl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-subject/' + lang + '}}&format=xml'
	bodyurl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-body/' + lang + '}}&format=xml'
	dom = minidom.parse(urllib.urlopen(subjecturl))
	subject = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	dom = minidom.parse(urllib.urlopen(bodyurl))
	p = subprocess.Popen("ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub", shell=True, stdout=subprocess.PIPE)
	fingerprint = p.communicate()[0]
	fingerprint = fingerprint.split(' ')[1]
	body = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	body = body + ' ' + gethostname() + ' (' + fingerprint + ')'
	message = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (fromaddress, toaddress, subject, body)
	p = subprocess.Popen("/usr/sbin/sendmail -t", shell=True, stdin=subprocess.PIPE)
	p.communicate(message)
	if p.wait() != 0:
		return 1
Beispiel #8
0
def call_fun(args):
    '''
Listing funtions available in Astir
Liste les fonctions disponible dans Astir
    '''
    usage = 'fun'
    prog  = 'fun'
    desc  = call_fun.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-c', action='store', type='int', default='4', help='Number of columns. Nombre de colonnes')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) > 0:
        p.print_help()
        return 0
    listfun.sort()
    sfun = len(listfun)
    nc   = opt.c
    if sfun % nc == 0: nl = sfun // nc
    else:              nl = (sfun // nc) + 1
    smax = 0
    for i in xrange(sfun):
        val = len(listfun[i])
        if val > smax: smax = val
    for i in xrange(nl):
        txt = ''
        for j in xrange(nc):
            ind = j * nl + i
            if ind < sfun: txt += '%s  ' % listfun[ind].ljust(smax)
            else:          txt += ''
        print txt

    return 1
Beispiel #9
0
def call_save_world(args):
    '''
Save the whole work space to a file.
Sauvegarde entierement l espace de travail dans un fichier
    '''
    usage = 'save_world <file_name>\nsave_world backup.pck'
    prog  = 'save_world'
    desc  = call_save_world.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 1:
        p.print_help()
        return 0
    kname = WORLD.keys()
    if len(kname) == 0:
        outbox_bang('Nothing to save')
        return 0
    fname = args[0]
    if not check_overwrite_file(fname): return -1
    f = open(fname, 'w')
    local = ['world_astir', WORLD]
    cPickle.dump(local, f, 1)
    f.close()
    
    return 1
Beispiel #10
0
def call_div(args):
    '''
Divide two mat variables (L or RGB).
Divise deux variables mat (L ou RGB)
mat_c = mat_a / mat_b
    '''
    usage = 'div <mat_a> <mat_b> <mat_c>\n\
             div im1 im2 res\n'
    prog  = 'div'
    desc  = call_div.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 3:
        p.print_help()
        return 0
    src1, src2, trg = args
    if not check_name([src1, src2]): return -1
    if not check_mat([src1, src2]):  return -1
    if not check_overwrite(trg):     return 0
    mat1 = WORLD[src1][1]
    mat2 = WORLD[src2][1]
    res  = mat1 / mat2
    WORLD[trg] = ['mat', res]

    return 1
Beispiel #11
0
def call_mem(args):
    '''
Memories used in work space by the variables
Mémoire utilisee dans les espaces de travails par les variables
    '''
    usage = 'mem'
    prog  = 'mem'
    desc  = call_mem.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) > 0:
        p.print_help()
        return 0
    space = 10
    txt = ['', 'k', 'M', 'G', 'T']
    nbb = {'float8':1, 'float16':2, 'float32':4, 'float64':8,
            'uint8':1,  'uint16':2,  'uint32':4,  'uint64':8}
    lname = WORLD.keys()
    for name in lname:
        size   = WORLD[name][1].size
        dtype  = WORLD[name][1].dtype
        size  *= nbb[dtype]
        ie     = int(log(size) // log(1e3))
        size  /= (1e3 ** ie)
        size   = '%5.2f %sB' % (size, txt[ie])
        print '%s %s%s %s%s%s' % (name.ljust(space), 
              G, kind.ljust(space), 
              R, size.ljust(space), N)
        
    return 1
Beispiel #12
0
def call_colormap(args):
    '''
Apply false-colors to a luminance mat.
Applique des fausses couleurs sur une mat en luminance
colormap <mat_name> <kind_of_map> <new_mat_name>
different color of map: jet, hsv, hot

colormap im1 hot im_map    
    '''
    usage = 'colormap <mat_name> <new_name> [options]\n\
             colormap im1 im1color -c jet'
    prog  = 'colormap'
    desc  = call_colormap.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-c', action='store', type='string', default='jet', help='Kind of colormap jet, hsv and hot (default is jet)')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 2:
        p.print_help()
        return 0
    src, trg = args
    kind     = opt.c
    if not check_name(src):      return -1
    if not check_mat(src):       return -1
    if not check_overwrite(trg): return  0
    if not check_L(src):         return -1
    if kind not in ['jet', 'hsv', 'hot']:
        outbox_error('Kind of map color unknown')
        return -1
    res = color_colormap(WORLD[src][1], kind)
    WORLD[trg] = ['mat', res]

    return 1
Beispiel #13
0
def call_anaglyph(args):
    '''
Create an anaglyph image from two RGB matrix (right and left).
Creer une image anaglyphe depuis deux mat RGB (droite et gauche).
    '''
    usage = 'anaglyph <mat_right> <mat_left> [options]\n\
             anaglyph imr img -o newim\n'
    prog  = 'anaglyph'
    desc  = call_anaglyph.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-o', action='store', type='string', default='res_anag', help='Output name (default res_anag)')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 2:
        p.print_help()
        return 0
    src1, src2 = args
    trg        = opt.o
    if not check_name([src1, src2]): return -1
    if not check_mat([src1, src2]):  return -1
    if not check_overwrite(trg):     return 0
    im1, im2 = WORLD[src1][1], WORLD[src2][1]
    if not check_RGB(im1): return -1
    if not check_RGB(im2): return -1
    res = image_anaglyph(im1, im2)
    WORLD[trg] = ['mat', res]
    
    return 1
Beispiel #14
0
def call_cut_seq(args):
    '''
Cut a part of sequence to a new one, start and stop
specifies the part you want keep. Coupe une partie d une 
sequence dans une nouvelle, start et stop specifis la partie
que vous voulez garder.
    '''
    usage = 'cut_seq <seq_name> <new_seq_name> [option]\n\
             cut_seq vid1 newvid -s 10 -e 34\n'
    prog  = 'cut_seq'
    desc  = call_cut_seq.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    p.add_option('-s', action='store', type='int', default='-1', help='Start number (default 0)')
    p.add_option('-e', action='store', type='int', default='-1', help='Stop number (default until the end)')
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 2:
        p.print_help()
        return 0
    src, trg = args
    if not check_name(src):      return -1
    if not check_seq(src):       return -1
    if not check_overwrite(trg): return  0
    if opt.s == -1: opt.s = 0
    if opt.e == -1: opt.e = WORLD[src][1].shape[0]
    seq = []
    for n in xrange(opt.s, opt.e + 1):
        seq.append(WORLD[src][1][n])
    seq = array(seq)
    WORLD[trg] = ['seq', seq]
    del seq

    return 1
Beispiel #15
0
class Clone():
	def __init__(self):
		self.git = Git()
		self.parser = OptionParser()
		self.parser.add_option("-b", "--branch", dest="branch", help="with checkout branch")
		self.parser.add_option("-C", "--repo-dir", dest="repodir", help="repo directory")
		self.parser.add_option("-R", "--recursive", dest="recursive", help="clone project and subproject recursively")
		self.parser.set_usage("mgit clone <url> [-b <branch>]")

	def print_usage(self):
		self.parser.print_usage()
	
	def run(self, orig_args):
		options,args = self.parser.parse_args(orig_args)
		args = args[1:]
		if len(args) <= 0:
			self.print_usage()
			return
		project_dir = self.git.module_name(args[0])
		if project_dir == None or len(project_dir) <= 0:
			print("Unknow project name.Please use git clone, then use mgit sync in the project dir.")
			return
		cmd = ['git', 'clone'] + args
		if options.branch != None:
			cmd += ["-b", options.branch]
		if 0 != os.system(" ".join(cmd)):
			return
		cwd = os.getcwd()
		os.chdir("/".join([cwd, project_dir]))
		sync = Sync()
		sync.run(['sync'] + orig_args[1:])
		os.chdir(cwd)
Beispiel #16
0
def call_load_world(args):
    '''
Load a work space from a file.
Charge un espace de travial depuis un fichier.
    '''
    usage = 'load_world <file_name>\nload_world mydata.pck'
    prog  = 'load_world'
    desc  = call_load_world.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 1:
        p.print_help()
        return 0
    fname = args[0]
    if not check_name_file(fname): return -1
    f = open(fname, 'r')
    try: local = cPickle.load(f)
    except:
        outbox_error('Can not open the file')
        f.close()
        return -1
    f.close()
    if local[0] != 'world_astir':
        outbox_error('Not Astir format')
        return -1
    answer = inbox_question('All variables will be deleted, are you agree')
    if answer == 'n': return 0
    del WORLD
    WORLD = local[1]

    return 1
Beispiel #17
0
def main():
    parser = OptionParser()
    parser.set_usage(_("Usage:  billreminder [OPTIONS...]"))
    parser.add_option('--version', action='store_true', dest='app_version', default=False, help=_('Displays the version number for this application.'))
    parser.add_option('--verbose', action='store_true', dest='app_verbose', default=False, help=_('Print output messages.'))
    parser.add_option('--no-daemon', action='store_true', dest='app_nodaemon', default=False, help=_("Don't run as a daemon."))
    parser.add_option('--open-gui', action='store_true', dest='app_opengui', default=False, help=_('Start daemon and launch GUI.'))
    parser.add_option('--stop', action='store_true', dest='app_stop', default=False, help=_('Stop daemon.'))

    # Verify arguments
    options, args = parser.parse_args()
    if options.app_stop:
        import dbus
        import dbus.service
        if verify_service(common.DBUS_INTERFACE):
            session_bus = dbus.SessionBus()
            obj = session_bus.get_object(common.DBUS_INTERFACE,
                                         common.DBUS_PATH)
            dbus_interface = dbus.Interface(obj, common.DBUS_INTERFACE)
            dbus_interface.quit()
    elif options.app_version:
        print _('This is %(appname)s - Version: %(version)s') % \
                         {'appname': _("BillReminder Notifier"),
                          'version': common.APPVERSION}
    else:
        BillReminderd.main(options)
Beispiel #18
0
def call_show_mat(args):
    '''
Display a mat variable as an image.
Affiche une variable de type mat comme une image.
    '''
    usage = 'show_mat <mat_name>\nshow_mat <mat_name1> <mat_name2>'
    prog  = 'show_mat'
    desc  = call_show_mat.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) == 0 or len(args) > 2:
        p.print_help()
        return 0
 
    list_im = []
    if not check_name(args): return -1
    if not check_mat(args):  return -1    
    for name in args:
        im = WORLD[name][1]
        list_im.append(im)

    image_show(list_im)
    del list_im, args, im

    return 1
def parse_args():
    parser = OptionParser()
    parser.add_option("--snapshot-file", default=None,
                      help="Path to the test-warehouse archive")
    parser.add_option("--cm-user", default="admin", help="Cloudera Manager admin user")
    parser.add_option("--cm-pass", default="admin",
                      help="Cloudera Manager admin user password")
    parser.add_option("--gateway", default=None,
                      help=("Gateway host to upload the data from. If not set, uses the "
                            "CM host as gateway."))
    parser.add_option("--ssh-user", default="jenkins",
                      help=("System user on the remote machine with passwordless "
                            "SSH configured."))
    parser.add_option("--no-load", action="store_false", default=True, dest="load",
                      help="Do not try to load the snapshot")
    parser.add_option("--exploration-strategy", default="core")
    parser.add_option("--test", action="store_true", default=False,
                      help="Run end-to-end tests against cluster")
    parser.set_usage("remote_data_load.py [options] cm_host")

    options, args = parser.parse_args()

    try:
        return options, args[0]  # args[0] is the cm_host
    except IndexError:
        logger.error("You must supply the cm_host.")
        parser.print_usage()
        raise
Beispiel #20
0
def call_wiener(args):
    '''
Image restoration by Wiener filter.
Restauration d image par filtre de Wiener
wiener <mat_source_name> <mat_res_name>
    '''
    usage = 'wiener <mat_source_name> <mat_res_name>'
    prog  = 'wiener'
    desc  = call_wiener.__doc__
    p = OptionParser(description = desc, prog = prog, version = version)
    p.set_usage(usage)
    try: opt, args = p.parse_args(args)
    except: return 0
    if len(args) != 1:
        p.print_help()
        return 0
    src   = args[0]
    trg   = args[1]
    if not check_name(src):      return -1
    if not check_mat(src):       return -1
    if not check_overwrite(trg): return -1
    res = resto_wiener(WORLD[src][1])
    WORLD[trg] = ['mat', res]

    return 1
Beispiel #21
0
def main():

    #args = sys.argv
    parser = OptionParser()
    parser.set_usage(_("Usage:  billreminder [OPTIONS...]"))
    parser.add_option('-v','--version', action='store_true', dest='app_version', default=False, help=_('Displays the version number for this application.'))
    parser.add_option('--about', action='store_true', dest='app_about', default=False, help=_('About this application.'))
    parser.add_option('--add', action='store_true', dest='app_add', default=False, help=_('Adds a new bill to the database.'))
    parser.add_option('--standalone', action='store_true', dest='app_standalone', default=False, help=_('Access database directly, without daemon.'))

    # Verify arguments
    options, args = parser.parse_args()
    if options.app_about:
        dialogs.about_dialog()
    elif options.app_add:
        print dialogs.add_dialog()
    elif options.app_standalone:
        print _("This option is not implemented yet.")
    elif options.app_version:
        print _("This is %(appname)s - Version: %(version)s") % \
                         {'appname': common.APPNAME,
                          'version': common.APPVERSION}
    else:
        gtk.gdk.threads_init()
        app = BillReminder()
        gtk.main()
Beispiel #22
0
  def __init__(self):
    usage = "--user <user-name> [--database <database-name>] [--host <host-name>] [--port <port>]"
    parser = OptionParser()
    parser.set_usage(usage)
    parser.add_option("-u", "--user", dest="user", help="DataHub username")
    parser.add_option("-H", "--host", dest="host", help="DataHub server hostname", default="datahub-experimental.csail.mit.edu")
    parser.add_option("-p", "--port", dest="port", help="DataHub server port", type="int", default=9000)
    parser.add_option("-d", "--database", dest="database", help="DataHub database")
    (self.options, self.arg_values) = parser.parse_args()

    if not self.options.user:
      parser.print_usage()
      sys.exit(1)

    parser.destroy()
    self.password = getpass.getpass('DataHub password for %s: ' %(self.options.user))
    cmd2.Cmd.__init__(self, completekey='tab')
    self.client = DataHubClient(host=self.options.host, port=self.options.port)
    try:
      database = None
      if self.options.database:
        database=DHDatabase(name=self.options.database)
      con_params = DHConnectionParams(
          user=self.options.user,
          password=self.password,
          database=database)
      self.con = self.client.connect(con_params)
      self.prompt = "datahub> "
    except Exception, e:
      self.print_line('error: %s' % (e.message))
      sys.exit(1)
Beispiel #23
0
    def optParse():
        """
        Parses command line options.

        Generally we're supporting all the command line options that doxypy.py
        supports in an analogous way to make it easy to switch back and forth.
        We additionally support a top-level namespace argument that is used
        to trim away excess path information.
        """

        parser = OptionParser(prog=basename(argv[0]))

        parser.set_usage("%prog [options] filename")
        parser.add_option(
            "-a", "--autobrief",
            action="store_true", dest="autobrief",
            help="parse the docstring for @brief description and other information"
        )
        parser.add_option(
            "-c", "--autocode",
            action="store_true", dest="autocode",
            help="parse the docstring for code samples"
        )
        parser.add_option(
            "-n", "--ns",
            action="store", type="string", dest="topLevelNamespace",
            help="specify a top-level namespace that will be used to trim paths"
        )
        parser.add_option(
            "-t", "--tablength",
            action="store", type="int", dest="tablength", default=4,
            help="specify a tab length in spaces; only needed if tabs are used"
        )
        group = OptionGroup(parser, "Debug Options")
        group.add_option(
            "-d", "--debug",
            action="store_true", dest="debug",
            help="enable debug output on stderr"
        )
        parser.add_option_group(group)

        ## Parse options based on our definition.
        (options, filename) = parser.parse_args()

        # Just abort immediately if we are don't have an input file.
        if not filename:
            stderr.write("No filename given." + linesep)
            sysExit(-1)

        # Turn the full path filename into a full path module location.
        fullPathNamespace = filename[0].replace(sep, '.')[:-3]
        # Use any provided top-level namespace argument to trim off excess.
        realNamespace = fullPathNamespace
        if options.topLevelNamespace:
            namespaceStart = fullPathNamespace.find(options.topLevelNamespace)
            if namespaceStart >= 0:
                realNamespace = fullPathNamespace[namespaceStart:]
        options.fullPathNamespace = realNamespace

        return options, filename[0]
Beispiel #24
0
def get_optparser():
    parser = OptionParser(epilog='version %s, http://github.com/shadowprince/ddcp/' % VERSION)
    parser.set_usage('ddcp SOURCE... DESTINATION')
    parser.add_option('-b', '--block-size', 
            default=DEFAULT_BS, 
            help='block size for dd\'s bs, default = %s' % DEFAULT_BS
            )

    parser.add_option('-q', '--quiet', 
            action='store_true', 
            help='dont print progress to stdout default = false'
            )
    parser.add_option('-d', '--detailed', 
            action='store_true', 
            help='detailed output (with bar), default = false'
            )
    parser.add_option('-v', '--verbose', 
            action='store_true', 
            help='print system messages instead of progress bar, default = false'
            )

    parser.add_option('-t', '--time-delay', 
            help='time delay between dd sessions, default = %s' % DEFAULT_TIME_DELAY, 
            default=DEFAULT_TIME_DELAY
            )

    parser.add_option('', '--test', 
            help='dont run dd command, default = false', action='store_true'
            )
    parser.add_option('', '--dd', 
            help='various dd arguments added to execution string, default = blank', 
            default=''
            )

    return parser
def main():
	parser = OptionParser(conflict_handler="resolve")
	parser.set_usage("mail-instance-creator.py <from-email-address> <to-email-address> <languagecode> <wikiaddress>\n\n\texample: mail-instance-creator.py 'test@example.com' 'es' 'http://example.com/w/'")

	(options, args) = parser.parse_args()

	if len(args) != 4:
		parser.error("mail-instance-creator.py expects exactly four arguments.")

	fromaddress = args[0]
	toaddress = args[1]
	lang = args[2]
	wikiaddress = args[3]
	subjecturl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-subject/' + lang + '}}&format=xml'
	bodyurl = wikiaddress + 'api.php?action=expandtemplates&text={{msgnw:mediawiki:openstackmanager-email-body/' + lang + '}}&format=xml'
	dom = minidom.parse(urllib.urlopen(subjecturl))
	subject = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	dom = minidom.parse(urllib.urlopen(bodyurl))
	body = dom.getElementsByTagName('expandtemplates')[0].firstChild.data
	body = body + ' ' + gethostname()
	sendmail_location = "/usr/sbin/sendmail" # sendmail location
	p = os.popen("%s -t" % sendmail_location, "w")
	p.write("From: %s\n" % fromaddress)
	p.write("To: %s\n" % toaddress)
	p.write("Subject: %s\n" % subject)
	p.write("\n") # blank line separating headers from body
	p.write(body)
	status = p.close()
	return status
Beispiel #26
0
def parse_commandline():
    """Parse the comandline and return parsed options."""

    parser = OptionParser()
    parser.description = __doc__

    parser.set_usage('usage: %prog [options] (add|delete) [package].\n'
                     'Try %prog --help for details.')
    parser.add_option('-d', '--debug', action='store_true',
                      help='Enables debugging mode')
    parser.add_option('-l', '--login',
                      help='Username to login with')
    parser.add_option('-a', '--account',
                      help='User owning the repositories to be changed ' \
                           '[default: same as --login]')
    parser.add_option('-t', '--apitoken',
                      help='API Token - can be found on the lower right of ' \
                           'https://github.com/account')

    options, args = parser.parse_args()
    if len(args) != 2:
        parser.error('wrong number of arguments')
    if (len(args) == 1 and args[0] in ['add', 'delete']):
        parser.error('%r needs a package name as second parameter\n' % args[0])
    if (len(args) == 2 and args[0] not in ['add', 'delete']):
        parser.error('unknown command %r. Try "add" or "delete"\n' % args[0])

    return options, args
def CreateCommandLineParser():
    parser = OptionParser()
    usage = sys.argv[0] + " command [args] [options]"
    usage += "\n\nCommands:"
    usage += "\n  init [projects ...]       Initialize local copies of projects"
    usage += "\n  list                      List contents of INI file"
    usage += "\n  status [projects ...]     Get current project status"
    usage += "\n  history [projects ...]    Get time and outcome of previous syncs"
    usage += "\n  sync [projects ...]       Perform synchronisation"
    parser.set_usage(usage)
    parser.add_option('-i', '--ini', type='string', dest='ini_filename',
                      help='INI file name')
    parser.add_option('-d', '--direction', dest='direction',
                      choices=['push', 'pull', 'both'],
                      help='Direction(s) of the synchronisation operation (push|pull|both)')
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
                      default=False, help='Verbose output')
    parser.add_option('-q', '--quiet', dest='quiet', action='store_true',
                      default=False, help='No output')
    parser.add_option('-n', '--dry-run', dest='dry_run', action='count',
                      default=0, help='Do not actually execute any actions')
    parser.add_option('-a', '--all', dest='all', action='store_true',
              default=False, help='Sync all projects, including those with auto=false')
    parser.add_option('-r', '--remote', dest='remote',
                      help="Name of remote")
    parser.add_option('-p', '--prefer', dest='prefer',
                      help="Which copy to prefer in case of conflict (local|remote)")

    return parser
Beispiel #28
0
    def create_parser(self, prog_name, subcommand):
        parser = OptionParser(prog=prog_name, add_help_option=False,
                              formatter=SynnefoCommandFormatter())

        parser.set_usage(self.usage(subcommand))
        parser.version = self.get_version()

        # Handle Django's and common options
        common_options = OptionGroup(parser, "Common Options")
        common_options.add_option("-h", "--help", action="help",
                                  help="show this help message and exit")

        common_options.add_option("--version", action="version",
                                  help="show program's version number and"
                                       "  exit")
        [common_options.add_option(o) for o in self.option_list]
        if common_options.option_list:
            parser.add_option_group(common_options)

        # Handle command specific options
        command_options = OptionGroup(parser, "Command Specific Options")
        [command_options.add_option(o)
         for o in getattr(self, "command_option_list", ())]
        if command_options.option_list:
            parser.add_option_group(command_options)

        return parser
Beispiel #29
0
def parse_args():
    parser = OptionParser()
    parser.set_usage("rhn-custom-info [options] key1 value1 key2 value2 ...")
    parser.add_option("-u", "--username",
                      action="store", type="string", dest="username",
                      help="your RHN username", metavar="RHN_LOGIN")

    parser.add_option("-p", "--password",
                      action="store", type="string", dest="password",
                      help="your RHN password", metavar="RHN_PASSWD")

    parser.add_option("-s", "--server-url",
                      action="store", type="string", dest="url",
                      help="use the rhn api at URL", metavar="URL")

    parser.add_option("-d", "--delete-values",
                      action="store_true", dest="delete_values", default=0,
                      help="delete one or multiple custom keys from the system")

    parser.add_option("-l", "--list-values",
                      action="store_true", dest="list_values", default=0,
                      help="list the custom keys and values for the system",
                      )


    return parser.parse_args()
Beispiel #30
0
def parseArgs(argv):
   '''
   Parses command line arguments
   '''

   opt_args= ['start', 'stop', 'restart']

   optParser= OptionParser()

   [ optParser.add_option(opt) for opt in [
      make_option('-f', '--foreground', action='store_true', dest= 'foreground', default= False, help= 'run in foreground'),
      make_option('-q', '--queue', default= 'localhost:50001:impetus', help= 'queue ip:port:key'),
      make_option('-d', '--dfs', default= 'localhost:50002:impetus', help= 'dfs ip:port:key'),
      make_option('-s', '--s3', default= None, help= '<accessKey>:<secretKey>:<bucket> for s3 transport'),
      make_option('-p', '--pidDir', default= path.join(getcwd(), '../pid'), help= 'path to pid directory'),
      make_option('-o', '--logDir', default= path.join(getcwd(), '../log'), help= 'path to log directory'),
      make_option('-t', '--taskDir', default= path.join(getcwd(), '../tasks'), help= 'path to task directory'),
      make_option('-m', '--maxProcesses', default= 25, type= int, help= 'path to pid directory'),
      make_option('-n', '--sleep', default= 0.01, type= float, help= 'sleep time for waits')
   ]]

   optParser.set_usage('%%prog %s' % ('|'.join(opt_args)))

   opts, args= optParser.parse_args()
   if not opts.foreground and len(args) < 1:
      optParser.print_usage()
      exit(-1)

   setattr(opts, 'PIDFile', path.join(opts.pidDir, argv[0].replace('.py', '.pid')))

   if opts.dfs == 'None':
      opts.dfs = None

   return args, opts, optParser.print_usage, optParser.print_help