当前位置: 首页>>代码示例>>Python>>正文


Python argv.index函数代码示例

本文整理汇总了Python中sys.argv.index函数的典型用法代码示例。如果您正苦于以下问题:Python index函数的具体用法?Python index怎么用?Python index使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了index函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __load_cmd_line_args

    def __load_cmd_line_args(self):
        """

        :return:
        """
        required_fields = self.my_config['config'][self.default_conf]['required_fields']
        resp = {}
        for f in required_fields:
            resp[f]=''
        if len(cmd_args) > len(required_fields)*2:
            for field in required_fields:
                arg = '--{arg_type}'.format(arg_type=field)
                if arg in cmd_args:
                    if path.exists(cmd_args[cmd_args.index(arg)+1]):
                        resp[field] = cmd_args[cmd_args.index(arg)+1]
                    else:
                        print self.error_codes.errors_list[4]['msg']
                        exit(self.error_codes.errors_list[4]['exit_code'])
                else:
                    print self.error_codes.errors_list[3]['msg']
                    exit(self.error_codes.errors_list[3]['exit_code'])
            return resp['input'], resp['output']
        else:
            print self.error_codes.errors_list[2]['msg']
            exit(self.error_codes.errors_list[2]['exit_code'])
开发者ID:ganipa93,项目名称:data_refine_scheduler_module,代码行数:25,代码来源:task_module.py

示例2: main

def main():
    user,recAmt,library,libraryFile = configParse()
    if library == None:
        if user == None:
            user = input('Enter discogs username:')
    if recAmt == None:
        recAmt = 1

    """
    main-ish
    interprates arguments and decides what to do depending on what arguments are provided
    too messy, I'd like to clean this up
    """
    validArgs = ['-r','-h','-update']
    if len(argv) > 1:
        if '-r' in argv:
            if argv.index('-r') + 1 < len(argv):
                try:
                    int(argv[argv.index('-r') + 1])
                    recAmt = int(argv[argv.index('-r') + 1])

                except (TypeError,ValueError):
                    print('Incorrect formatting for "-r" argument. We need an integer after it. Defaulting to 1')
                    help()
                    recAmt = 1
            else:
                print("Incorrect formatting for "-r" argument. We need a number after it.")
                recAmt = 1
                help()

        if '-h' in argv:
            help()

        if '-update' in argv:
            print('Updating...')
            library = popLibrary(user)
            libraryDump(library,libraryFile)
            print('Done.')

        if '-r' not in argv and '-update' not in argv and '-gtk' not in argv: # some argument was given but not valid
            help()


    if '-update' not in argv and '-h' not in argv:
        if library == None:
            library = popLibrary(user)
            libraryDump(library,libraryFile)
            listenList = genSuggest(recAmt,library,list(library))
            if '-gtk' in argv:
                mainGtk(user,library)
            else:
                mainCli(listenList)

        else:
            listenList = genSuggest(recAmt,library,list(library))
            if '-gtk' in argv:
                mainGtk(user,library)
            else:
                mainCli(listenList)
开发者ID:CharlesSchimmel,项目名称:silt,代码行数:59,代码来源:silt.py

示例3: create_processes

def create_processes(n=20):
    try:
        x = int(.8 * n)
        y = n - x
        argv.index("-PART2")
        starts = exp_rand(x)
        p = [Process(pid, 0, randrange(500, 4001), randrange(0, 5)) for pid in range(y)]
        p.extend([Process(pid+y, starts[pid], randrange(500,4001), randrange(0,5)) for pid in range(x)])
    except:
        p = [Process(pid, 0, randrange(500, 4001), randrange(0, 5)) for pid in range(n)]
    return p
开发者ID:c00w,项目名称:OPSYS-2013-Project,代码行数:11,代码来源:main.py

示例4: main

def main():
	'''Main method. Put in method so can be exported.'''
	i = Interpreter()

	#TODO cleaner argument parsing
	if "-c" in argv and len(argv) > argv.index("-c") + 1:
		exprs = argv[argv.index("-c") + 1]
		for expr in exprs.split(";"):
			interpret(i, expr)
	else:
		# just a bit of main loop stuff
		cli = CalcInterpreterCLI(i)
		cli.cmdloop()
开发者ID:boompig,项目名称:CalcInterpreter,代码行数:13,代码来源:main.py

示例5: testCmd

def testCmd(argv) :
    global HELP
    try:                            # ---------- do you need some help ?
        argv.index("-h")
        HELP = 1
        printUsage(argv[0], 0)
    except:
        try:
            argv.index("--help")
            HELP= 1
            printUsage(argv[0], 0)
        except:
            HELP = 0
	return
开发者ID:rmarabini,项目名称:LAdV23,代码行数:14,代码来源:editPDB.py

示例6: run

    def run(self):

        """
        Metodo run del thread, viene richiamato tramite start().
        Viene eseguito un loop che cerca a intervalli di 30 secondi
        nuovi hosts sulla rete e per ogni host che trova inizializza
        un thread che ne raccoglie le informazioni.
        I vari thread vengono raccolti all'interno di una lista.

        L'indirizzo della rete viene preso dalla linea di comando o se 
        non fornito si cerca di indovinarlo a partire dall'ip della 
        macchina (assumendo che la netmask sia 255.255.255.0 
        come spesso si verifica). 
        """

        self.known_hosts = []

        if '-n' in argv: 
            network_address = argv[argv.index('-n') + 1]

        elif '--network' in argv: 
            network_address = argv[argv.index('--network') + 1]

        else: 
            network_address = get_network_address()
        if not network_address:
            print("Cannot find network address... program will continue without network scanning!\n" +
                  "If this trouble persist, try providing the network address in the launch command!\n" +
                  "Press CTRL-C to terminate!")
            exit()

        while(True):

            hosts = host_discovery(network_address) 

            for host in hosts:
                if not (host in self.known_hosts):
                    self.known_hosts.append(host) 
                    print("Starting thread for host %s" % host) 
                    thread = Host(host)
                    self.threads.append(thread)
                    thread.start()

            for thread in self.threads:
                if not thread.is_alive:
                    self.known_hosts.remove(thread.info['ip'])

            sleep(30)
开发者ID:michelesr,项目名称:network-monitor-server,代码行数:48,代码来源:netmapping.py

示例7: main

def main():
    if '-o' in argv[1:]:
        ver = get_closest_version(argv[argv.index('-o') + 1])
    else:
        ver = get_latest_version()

    if '-g' in argv[1:]:
        gui()
        return
    elif '-h' in argv[1:]:
        usage()
        return
    elif '-r' in argv[1:]:
        revert()
        return
    elif '-b' in argv[1:]:
        backup(ver)
        return

    print('Latest Version: ', ver)

    if '-v' in argv[1:]:
        return

    del_current(False)
    download_chromium(ver)
    unzip()
开发者ID:howardjohn,项目名称:Chromium-Downloader,代码行数:27,代码来源:chromium.py

示例8: main

def main():
  if '-h' in args or '--h' in args or '--help' in args:
    print 'Usage is as follows: ./makefile -if infile -of outfile -s stepsize -t runtime_in_seconds -org organism_name'
    print 'Good default values are -s 500 and -t 120 -org scenedesmus_dimorphus'
    sys.exit()

  vals = [args[args.index(flag) + 1] for flag in ['-if', '-of', '-s', '-t', '-org']]
  infile = vals[0]
  outfile = vals[1]
  step = int(vals[2])
  runtime = int(vals[3])
  organism = vals[4].replace('_', ' ')
  
  if infile[-5:] == 'fasta':
    seq_dict = parse_fasta(infile)
    pickle.dump(seq_dict, open(infile[:-5]+'seq_dict', 'w'))
  else:
    seq_dict = pickle.load(open(infile, 'r'))

  #offset for chunks of sequences to blast
  o = 0
  start = time.time()
  seq_dict_keys = seq_dict.keys(); n = len(seq_dict_keys)
  descs = []

  #logic that queries as many queries possible in time given, and if we run out of queries before allotted time, end querying
  while time.time()-start < runtime and o+step < n:
    sample_seqs = [(k, seq_dict[k]) for k in seq_dict_keys[o:o+step]]
    descs += get_descriptions(sample_seqs, organism)
    o += step
    print 'Time Elapsed:', int(time.time()-start), 'seconds'
  pickle.dump(descs, open(outfile, 'w'))
开发者ID:Sudoka,项目名称:tupac,代码行数:32,代码来源:make_descs.py

示例9: main

def main(argv=None):
    """Print to stdout the project home path found with find_project_dir.find_project_dir(`project_homes`, `verbose`)
    """
    from sys import stdout, stderr

    # stderr.write(repr(argv) + '\n')
    project_homes = None  # ['~/src', '~/flint-projects', '~/bin', '~/projects', '~/sublime-projects', '~']
    proj_subdirs = None

    # TODO: Use getopt to process project_homes, verbose, and project_name keyword options/args
    verbose = False
    for verbosity in ('verbose', '-v'):
        if verbosity in argv:
            del(argv[argv.index(verbosity)])
            verbose = True
    if argv and len(argv) >= 2:
        project_name = argv[1]

    found_path = find_project_dir(project_name=project_name, project_homes=project_homes, proj_subdirs=proj_subdirs, verbose=verbose)
    # stderr.write(found_path + '\n')
    if found_path:
        stdout.write(found_path)
        # Don't attempt to os.chdir here, because subprocesses aren't allowed to affect the parent env
    else:
        stderr.write('Unable to find a valid virtualenvwrapper path in $VENVWRAP_PROJECT_HOMES=%s\n that contains the project name %s\n and also contains a subdir among $VIRTUALENVWRAPPER_PROJECT_HOMES_CONTAIN=%s.\n' % (repr(project_homes), repr(environ.get('VIRTUAL_ENV', '')), repr(proj_subdirs)))
开发者ID:hobson,项目名称:skel,代码行数:25,代码来源:find_project_dir.py

示例10: hfst_specific_option

def hfst_specific_option(option):
    if option in argv:
        index = argv.index(option)
        argv.pop(index)
        return True
    else:
        return False
开发者ID:hfst,项目名称:hfst,代码行数:7,代码来源:setup.py

示例11: getCalcArgs

def getCalcArgs():
    from sys import argv                   # get cmdline args in a dict
    config = {}                            # ex: -bg black -fg red
    for arg in argv[1:]:                   # font not yet supported
        if arg in ['-bg', '-fg']:          # -bg red' -> {'bg':'red'}
            try:
                config[arg[1:]] = argv[argv.index(arg) + 1]
            except:
                pass
    return config
开发者ID:chuzui,项目名称:algorithm,代码行数:10,代码来源:calculator.py

示例12: get_short_param

    def get_short_param(self, short_param=None, single_param=True, is_mark=False):
        """Get the target according to the short require
            :param short_param (string)
                    well, actually this most functions like the `get_full_param`, but I prefer to make a difference
                this param is more likely to be `-b` or `-l`, in this case, this method support a kind match like
                when give `-nutpl` and `-l` is a mark (is_mark=True)
                    `-l` will be regard as True
            :param single_param (bool)
                    whether or not continues to see the following as the param
                example will be seen at `get_full_param` but in short term
            :param is_mark  (bool)
                    whether the param head used ad a mark only
                example will be seen at `get_full_param` but in short term
        """
        if is_mark:
            if short_param in self.args:
                return True
            if short_param.startswith(self.prefix_short) and self.args:
                from re import compile
                regs = compile('(?<={})\w'.format(self.prefix_short))
                target = regs.findall(short_param)[0]
                for param in self.args:
                    if param.startswith(self.prefix_short) and \
                            not param.startswith(self.prefix) and \
                            target in param:
                        return True

        if short_param not in argv:
            return False

        last = argv[argv.index(short_param):]
        if len(last) > 1:
            if single_param:
                return argv[argv.index(short_param) + 1]
            result = ''
            for single in argv[argv.index(short_param) + 1:]:
                if not single.startswith(self.prefix) and not single.startswith(self.prefix_short):
                    result += single + ' '
                else:
                    break
            return result.strip()
        return False
开发者ID:hellflame,项目名称:paramSeeker,代码行数:42,代码来源:seeker.py

示例13: main

def main():
    # excluding this programs name (argv[0]) and all arguments up to and
    # and excluding the first "--" are c files to include
    try:
        c_code_files = argv[1:argv.index("--")]
    except ValueError: # there might be no "--"
        c_code_files = argv[1:]

    if len(c_code_files) == 0:
        raise Exception("You must provide at least one C source file")

    state = State()
    state.autoSetupSystemMacros()
    state.autoSetupGlobalIncludeWrappers()
    interpreter = Interpreter()
    interpreter.register(state)

    for cfile in c_code_files:
        state = parse(cfile, state)

    main_func = interpreter.getFunc("main")
    if len(main_func.C_argTypes) == 0:
        return_code = interpreter.runFunc("main", return_as_ctype=False)
    else:
        # if the main() function doesn't have zero arguments, it
        # should have the standard two, (int argc0, char **argv0)
        assert(len(main_func.C_argTypes) == 2)

        # first c file is program name and first argument
        arguments_to_c_prog = [c_code_files[0]]
        try: # append everything after the "--" as c program arguments
            arguments_to_c_prog += argv[argv.index("--")+1:]
        except: ValueError

        # return_as_ctype=False as we're expecting a simple int or None for void
        return_code = interpreter.runFunc(
            "main",
            len(arguments_to_c_prog), arguments_to_c_prog,
            return_as_ctype=False)

    if isinstance(return_code, int):
        exit(return_code)
开发者ID:albertz,项目名称:PyCParser,代码行数:42,代码来源:runcprog.py

示例14: main

def main():
    compout = subprocess.PIPE if "--run" not in argv else subprocess.STDERR
    retcode = subprocess.call(" ".join(CXX, FLAGS, OPTIM).split(), stdout=compout)

    if retcode == 0:
        print("### DONE COMPILING\n")

        if "--run" in argv:
            retcode = subprocess.call(["./bin/main"] + argv[argv.index("--run"):], stdout=subprocess.PIPE)
            print("### DONE RUNNING\n")
            return retcode
    else:
        print("### FAILED COMPILING\n")
        return retcode
开发者ID:gtarciso,项目名称:trafficsim,代码行数:14,代码来源:build.py

示例15: get_data

def get_data(key,data_type,default=None):
    if key not in argv:
        if default == None:
            return data_type()
        else:
            return default

    key_in = argv.index(key)
    if data_type==str:
        output = argv[key_in+1]
    elif data_type==list:
        output = []
        for i in range(key_in+1,len(argv)):
            if argv[i][0]=='-':
                break
            else:
                output.append(argv[i])
    return output
开发者ID:jeffhsu3,项目名称:Structural_Variant_Comparison,代码行数:18,代码来源:merge_data.py


注:本文中的sys.argv.index函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。