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


Python sys.sys_exit函数代码示例

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


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

示例1: grep_for

    def grep_for(self, exp):
        """
        Execute a grep command to search for the given expression.
        Results are returned as a list.
        """
        cmd = self._grep_cmd(exp, self.file_patterns)

        if self.debug:
            print "=== Grep command ==="
            print " $ %s\n" % cmd

        try:
            response = subprocess.check_output(
                    [cmd],
                    shell=True
                    )
            results = response.splitlines()

            if self.debug:
                print "=== Grep results ==="
                print response, "Total results: %d\n" % len(results)
        except subprocess.CalledProcessError, err:
            if err.returncode == 1:
                print "Couldn't find anything matching '%s'" % exp
            else:
                print "Whoops, grep returned errorcode %d" % err.returncode
            sys_exit()
开发者ID:nicr9,项目名称:greptools,代码行数:27,代码来源:searcher.py

示例2: parse_commandline

def parse_commandline():
   """ Return the parsed commandline arguments

   :return: (obj) argparse.Namespace
   """
   main_parser = argparse.ArgumentParser(
      description='Validate `LCONF files`',
      formatter_class=RawDescriptionHelpFormatter,
      epilog='''EXAMPLES:
   lconf-validate path-to-first.lconf path-to-second.lconf
   '''
   )

   main_parser.add_argument(
      'in_files',
      nargs='*',
      default=[],
      help='List of files to be validates',
   )

   args = main_parser.parse_args()
   if not args.in_files:
      main_parser.print_help()
      sys_exit()

   return args
开发者ID:peter1000,项目名称:LCONF,代码行数:26,代码来源:validator.py

示例3: main

def main(args=None):
    parser = ArgumentParser(usage="Usage: %(prog)s taskName xmlFile [options]", description="create new job in DB")
    parser.add_argument("-d", "--dry", dest="dry", action='store_true', default=False,
                        help='if dry, do not try interacting with batch farm')
    parser.add_argument("-l", "--local", dest="local", action='store_true', default=False, help='run locally')
    parser.add_argument("-p", "--pythonbin", dest="python", default=None, type=str,
                        help='the python executable if non standard is chosen')
    parser.add_argument("-c", "--chunk", dest="chunk", default=100, type=int,
                        help='number of jobs to process per cycle')
    parser.add_argument("-m", "--maxJobs", dest="maxJobs", default=None, type=int,
                        help='number of jobs that can be in the system')
    parser.add_argument("-u", "--user", dest="user", default=None, type=str, help='name of user that submits jobs')
    parser.add_argument("-s", "--skipDBcheck", dest="skipDBcheck", action='store_true', default=False,
                        help='skip DB check for jobs')
    send_heartbeat("JobFetcher") # encapsulates the heartbeat update!
    opts = parser.parse_args(args)
    log = logging.getLogger("script")
    batchsite = BATCH_DEFAULTS['name']
    BEngine = HPC.BatchEngine()
    if opts.user is not None: BEngine.setUser(opts.user)
    if opts.maxJobs is not None:
        try:
            val = BEngine.checkJobsFast(pending=True)
        except Exception as err:
            print 'EXCEPTION during getRunningJobs, falling back to DB check, reason follows: %s' % str(err)
            val = 0
            if opts.skipDBcheck:
                print 'skipping DB check, assume no jobs to be in the system'
            else:
                for stat in ['Running', 'Submitted', 'Suspended']:
                    res = get("%s/newjobs/" % DAMPE_WORKFLOW_URL,
                              data={"site": str(batchsite), "limit": opts.chunk, "status": stat})
                    res.raise_for_status()
                    res = res.json()
                    if not res.get("result", "nok") == "ok":
                        log.error(res.get("error"))
                    val += len(res.get("jobs"))
        log.info('found %i jobs running or pending', val)
        if val >= opts.maxJobs:
            log.warning(
                "reached maximum number of jobs per site, not submitting anything, change this value by setting it to higher value")
            sys_exit();
    res = get("%s/newjobs/" % DAMPE_WORKFLOW_URL, data={"site": str(batchsite), "limit": opts.chunk})
    res.raise_for_status()
    res = res.json()
    if not res.get("result", "nok") == "ok":
        log.error(res.get("error"))
    jobs = res.get("jobs")
    log.info('found %i new job instances to deploy this cycle', len(jobs))
    njobs = 0
    for job in jobs:
        j = DmpJob.fromJSON(job)
        # j.__updateEnv__()
        j.write_script(pythonbin=opts.python, debug=opts.dry)
        try:
            ret = j.submit(dry=opts.dry, local=opts.local)
            j.updateStatus("Submitted", "WaitingForExecution", batchId=ret, cpu=0., memory=0.)
            njobs += 1
        except Exception, e:
            log.exception(e)
开发者ID:zimmerst,项目名称:DmpWorkflow,代码行数:60,代码来源:dampe_cli_fetch_new_jobs.py

示例4: add_node

def add_node(logger, args):
    logger.debug("action: add_node")
    p = argparse.ArgumentParser(usage="%(prog)s add_node IP PLUGIN [-u USERNAME] [-p PASSWORD]")
    p.add_argument("ip")
    p.add_argument("plugin")
    p.add_argument("-u", "--username")
    p.add_argument("-p", "--password")
    o, a = p.parse_known_args(args)

    logger.debug("action opts: %s", o)
    logger.debug("action args: %s", a)

    if o.ip and o.plugin:
        try:
            load_plugin(o.plugin)
        except ImportError:
            logger.error("%s is not a valid plugin", o.plugin)
            sys_exit(1)

        node = Node(o.ip, o.plugin)
        try:
            session.add(node)
            node.username = o.username
            node.password = o.password
            session.commit()
            logger.info("Node added")
        except IntegrityError:
            logger.error("Node already exists")
            sys_exit(1)
开发者ID:jrha,项目名称:artemis,代码行数:29,代码来源:artemis_cli.py

示例5: send_blueprint_script

def send_blueprint_script(src_path,target_path):
    with settings(show('warnings', 'running',
                        'stdout', 'stderr'), 
                        warn_only=False,
                        shell='/bin/bash -lc',
                        user='labadm',
                        ):
        ## try/except wrapped check to validate existance of local file
        try:
            with open(src_path, 'rt') as f:
               f.readline()
        except IOError as e:
            print "I/O error [{0}] {1}: {2}".format(e.errno, e.strerror, e.filename)
            sys_exit(1)


        test_exist = fab_run('ls -l %s' % (target_path))
        if test_exist.succeeded:
            replace_yesno = fab_prompt(
            'File <{0}> already Exists. OK to Replace? [yes/no]'.format(target_path),
            default='no')

        if debug == True:
            print 'You said [{0}], exiting.'.format(replace_yesno)
            if 'yes' in replace_yesno.lower():
                replace_yesno = True
            else:
                replace_yesno = False
                
                #ch = lambda x: 'yes' if x == True else 'no'
            sys_exit(0)

            test = fab_put(src_path,target_path,use_sudo=False, mirror_local_mode=False, mode=None)
        else:
            test = fab_run('[ -f %s ]' % (lsbdata))
开发者ID:GunioRobot,项目名称:Rigel-Major,代码行数:35,代码来源:fabric_deploy_blueprint.py

示例6: main

def main(argv):
    # NOTE:  If parsing arguments fails or if the program is run with `-h`
    #   switch to just get the help message, the rest of the function will
    #   not be executed.  Parsing arguments before importing and defining
    #   everything thus saves time if the user runs the program with `-h`
    #   flag or if the user makes a mistake in command line arguments.
    parsed_args = parse_argv(argv)

    # NOTE:  Putting imports here seems to be against Style Guide for
    #   Python Code (PEP 8).  However, having imports in the body of
    #   `main` function looks more justifiable than in the bodies of
    #   other functions.
    from .runner import go

    go( parsed_args.input_file_name,
        parsed_args.sampling_number,
        parsed_args.zero_threshold,
        parsed_args.signature_parameter,
        parsed_args.periodicity_parameter,
        parsed_args.caution )

    # NOTE:  Apparently according to current practices, `main` function
    #   is expected to return the exit status (with `return`, instead of
    #   calling `sys.exit` itself).  However, since `parse_args` is called
    #   inside this function, in some cases this function will be exiting
    #   through `sys.exit` anyway (for example, if the program is called
    #   with `-h` flag to get the help message).  Thus it seems unreasonable
    #   to try to return normally from this function in other situations.
    # TODO: make sure to return the correct exit status in all situations,
    #   based on the outcome of `go` execution
    sys_exit(0)
开发者ID:alexeymuranov,项目名称:sig,代码行数:31,代码来源:cli.py

示例7: main

def main(args=None):
    parser = ArgumentParser(usage="Usage: %(prog)s [options]", description="query datacatalog")
    parser.add_argument("-H","--host",dest='host',help="hostname of influxdb instance")
    parser.add_argument("-u","--user",dest="user",help="username")
    parser.add_argument("-p","--password",dest="pw",help="password")
    parser.add_argument("-P","--port",dest="port",type=int,default=8086,help="influxdb ingest port")
    parser.add_argument("-n","--dbname", dest="dbname",help="name of DB to store data in.")
    parser.add_argument("-d", "--dry", dest="dry", action="store_true", default=False, help="do not report results to grafana")
    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", default=False, help="verbose mode")
    opts = parser.parse_args(args)
    json_bdy = []
    for site in batchSites:
        status_dict = {key: 0 for key in statii}
        stats = JobInstance.objects.filter(site=site).item_frequencies("status")
        status_dict.update(stats)
        for stat, freq in status_dict.iteritems():
            json_bdy.append(__makeEntry__(stat, site, freq))
    print 'found %i measurements to add'%len(json_bdy)
    pp = PrettyPrinter(indent=2)
    if opts.verbose: pp.pprint(json_bdy)
    if opts.dry:
        return
    if influxdb:
        client = InfluxDBClient(opts.host,opts.port,opts.user,opts.pw,opts.dbname)
        client.create_database(opts.dbname)
        ret = client.write_points(json_bdy)
        if not ret: 
            try:
                raise Exception("Could not write points to DB")
            except Exception:
                print_exc()
                sys_exit(int(ret))
开发者ID:zimmerst,项目名称:DmpWorkflow,代码行数:32,代码来源:jobs_summary_influxdb.py

示例8: scan_file

def scan_file(file_path):
    cur_token = ''
    token_idx = 0
    args = []

    fd = open(file_path, 'r')
    for line in fd:
        line = line.strip()
        if line.startswith('static const chunk_tag_t'):
            idx = line.find('[')
            if idx > 0:
                cur_token = line[25:idx].strip()
                token_idx = 0
        else:
            if len(cur_token) > 0:
                idx1 = line.find('{')
                idx2 = line.find('CT_')
                if idx1 >= 0 and idx2 > idx1:
                    tok = line[idx1 + 1:idx2].strip()
                    if tok.startswith('R"'):
                        pos_paren_open = tok.find('(')
                        pos_paren_close = tok.rfind(')')

                        if pos_paren_open == -1 or pos_paren_close == -1:
                            print("raw string parenthesis not found", file=stderr)
                            sys_exit(-1)

                        tok = tok[pos_paren_open+1:pos_paren_close]
                    else:
                        tok = tok[1:-2]  # strip off open quotes and commas
                    args.append([tok, '%s[%d]' % (cur_token, token_idx)])
                    token_idx += 1
    return args
开发者ID:Unity-Technologies,项目名称:uncrustify,代码行数:33,代码来源:punc.py

示例9: generate_config_file

def generate_config_file(configdb, config_content):
    filename = config_content.config_file
    _logger.info(
        'save following config to file %s:\n\t%s',
        filename,
        config.pretty(config_content, '\n\t')
    )
    save_config(configdb, config_content, filename)
    sys_exit(0)
开发者ID:genzj,项目名称:pybingwallpaper,代码行数:9,代码来源:main.py

示例10: run

    def run(self):  # suppress(unused-function)
        """Run linters."""
        import parmap
        from prospector.formatters.pylint import PylintFormatter

        cwd = os.getcwd()
        files = self._get_files_to_lint([os.path.join(cwd, "test")])

        if len(files) == 0:
            sys_exit(0)
            return

        use_multiprocessing = (
            not os.getenv("DISABLE_MULTIPROCESSING", None)
            and multiprocessing.cpu_count() < len(files)
            and multiprocessing.cpu_count() > 2
        )

        if use_multiprocessing:
            mapper = parmap.map
        else:
            # suppress(E731)
            mapper = lambda f, i, *a: [f(*((x,) + a)) for x in i]

        with _patched_pep257():
            keyed_messages = dict()

            # Certain checks, such as vulture and pyroma cannot be
            # meaningfully run in parallel (vulture requires all
            # files to be passed to the linter, pyroma can only be run
            # on /setup.py, etc).
            non_test_files = [f for f in files if not _file_is_test(f)]
            mapped = (
                mapper(_run_prospector, files, self.stamp_directory)
                + mapper(_run_flake8, files, self.stamp_directory)
                + [_stamped_deps(self.stamp_directory, _run_prospector_on, non_test_files, ["vulture"])]
                + [_stamped_deps(self.stamp_directory, _run_pyroma, "setup.py")]
            )

            # This will ensure that we don't repeat messages, because
            # new keys overwrite old ones.
            for keyed_messages_subset in mapped:
                keyed_messages.update(keyed_messages_subset)

        messages = []
        for _, message in keyed_messages.items():
            if not self._suppressed(message.location.path, message.location.line, message.code):
                message.to_relative_path(cwd)
                messages.append(message)

        sys.stdout.write(
            PylintFormatter(dict(), messages, None).render(messages=True, summary=False, profile=False) + "\n"
        )

        if len(messages):
            sys_exit(1)
开发者ID:pombredanne,项目名称:polysquare-setuptools-lint,代码行数:56,代码来源:__init__.py

示例11: __init__

 def __init__(self, msg): # Object constructor initialized with a custom user message
     """
     Catch an IsisConfException, print a description of the error and exit without python
     error printing traceback
     @param msg spefific error message
     """
     err_msg = "IsisConfException : An error occured while parsing Isis options!\n"
     err_msg += "\t{}.\n\tPlease ajust your settings\n".format(msg)
     print (err_msg)
     sys_exit ()
开发者ID:a-slide,项目名称:Isis,代码行数:10,代码来源:IsisConf.py

示例12: update_probe

def update_probe(logger, args):
    logger.debug("action: update_probe")
    p = argparse.ArgumentParser(usage="%(prog)s update_probe [options]")
    p.add_argument("id", help="probe id")
    p.add_argument("-n", help="name")
    p.add_argument("-x", help="x position")
    p.add_argument("-y", help="y position")
    p.add_argument("-z", help="z position")
    p.add_argument("-w", help="width")
    p.add_argument("-d", help="depth")
    p.add_argument("-t", help="height")
    o, a = p.parse_known_args(args)

    logger.debug("action opts: %s", o)
    logger.debug("action args: %s", a)

    if o.n is o.x is o.y is o.z is o.w is o.d is o.t is None:
        p.print_help()

    else:
        probe = session.query(Probe).filter(Probe.id == o.id).first()

        # Try name if id doesn't match any probes
        if not probe:
            logger.info("No probe found with id '%s', trying to match by name", o.id)
            probe = session.query(Probe).filter(Probe.name == o.id).all()

            if len(probe) > 1:
                logger.error("%d probes found with the name '%s', use ID to update each in turn", len(probe), o.id)
                for p in probe:
                    print p
                sys_exit(1)

            probe = probe[0]

        if probe:
            if o.n:
                probe.name = o.n
            if o.x:
                probe.x = o.x
            if o.y:
                probe.y = o.y
            if o.z:
                probe.z = o.z
            if o.w:
                probe.w = o.w
            if o.t:
                probe.h = o.t
            if o.d:
                probe.d = o.d

            session.commit()
            logger.info("Probe updated")
        else:
            logger.error("No probe found with id or name '%s'", o.id)
开发者ID:jrha,项目名称:artemis,代码行数:55,代码来源:artemis_cli.py

示例13: selectlayers

def selectlayers(args, layers):
    layer_specs = args.layers

    if layer_specs is None:
        selected_indexes = list(range(len(layers[':layers'])))

        if args.reverse:
            selected_indexes.reverse()
    else:
        selected_indexes = []
        last_num_selected_indexes = num_selected_indexes = len(selected_indexes)

        for l, r, v in layer_specs:
            last_num_selected_indexes = num_selected_indexes
            li = layerspec2index(args, layers, l)
            ri = layerspec2index(args, layers, r)

            if li is None:
                continue

            if r is None:
                selected_indexes.append(li)
            elif ri is None:
                continue
            elif ri < li:
                selected_indexes.extend(reversed(range(ri, li + 1))) # upper bounds are inclusive
            else:
                selected_indexes.extend(range(li, ri + 1)) # upper bounds are inclusive

            num_selected_indexes = len(selected_indexes)

            if num_selected_indexes == last_num_selected_indexes:
                empty_layer_range_msg = '"%s" resolves to an empty range'

                if args.strict:
                    _LOGGER.error(empty_layer_range_msg, v)
                    sys_exit(_EXIT_LAYER_SPEC)
                else:
                    _LOGGER.warning(empty_layer_range_msg, v)

        if not args.reverse:
            selected_indexes.reverse()

    # Take the last of each index specified (so we don't have to look at
    # each distinct layer more than once)
    seen = OrderedDict()

    for i in selected_indexes:
        if i not in seen:
            seen[i] = None # use OrderedDict as an ordered set

    top_most_layer_id = None if not seen else layers[':layers'][min(seen)][':id']
    selected_layers = [ layers[':layers'][i] for i in seen ]

    return top_most_layer_id, selected_layers
开发者ID:pombredanne,项目名称:py-dimgx,代码行数:55,代码来源:cmd.py

示例14: salir

	def salir(self):
		"""Finaliza los objetos y pygame, y cierra la aplicaión."""
		# Eliminar las referencias de la escena
		self.escena.destruir()
		# Al no tener referencias, son eliminados al ser olvidados por el núcleo
		self.escena = None
		self.mapa_eve = None
		self.reloj = None
		# Finalizar Pygame y cerrar la aplicaión
		pygame.quit()
		sys_exit()
开发者ID:Lizard-13,项目名称:LizardEngine,代码行数:11,代码来源:nucleo.py

示例15: shutdown

def shutdown(signum, frame):
    global pidfile, s
    try:
        s.close()
    except:
        print 'Cannot shutdown the socket'
    try:
        unlink(pidfile)
    except:
        pass
    print 'Shutdown done'
    sys_exit(0)
开发者ID:blueardour,项目名称:pxe-server,代码行数:12,代码来源:binlsrv.py


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