• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sys.sys_exit函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: load_config

def load_config(config_db, args=None):
    args = argv[1:] if args is None else args
    set_debug_details(args.count('--debug') + args.count('-d'))

    default_config = config.DefaultValueLoader().load(config_db)
    _logger.debug('default config:\n\t%s', config.pretty(default_config, '\n\t'))

    # parse cli options at first because we need the config file path in it
    cli_config = config.CommandLineArgumentsLoader().load(config_db, argv[1:])
    _logger.debug('cli arg parsed:\n\t%s', config.pretty(cli_config, '\n\t'))
    run_config = config.merge_config(default_config, cli_config)

    if run_config.list_markets:
        list_markets()

    if run_config.generate_config:
        generate_config_file(config_db, run_config)

    config_file = run_config.config_file
    if not isfile(config_file):
        _logger.warning("can't find config file %s, use default settings and cli settings",
                        config_file)
    else:
        try:
            conf_config = config.from_file(config_db, run_config.config_file)
        except config.ConfigFileLoader.ConfigValueError as err:
            _logger.error(err)
            sys_exit(1)

        # noinspection PyUnboundLocalVariable
        _logger.debug('config file parsed:\n\t%s', config.pretty(conf_config, '\n\t'))
        run_config = config.merge_config(run_config, conf_config)

    # override saved settings again with cli options again, because we want
    # command line options to take higher priority
    run_config = config.merge_config(run_config, cli_config)
    if run_config.setter_args:
        run_config.setter_args = ','.join(run_config.setter_args).split(',')
    else:
        run_config.setter_args = list()

    # backward compatibility modifications
    if run_config.size_mode == 'collect':
        _logger.warning(
            'size_mode=collect is obsolete, considering use collect=accompany instead'
        )
        run_config.size_mode = 'highest'
        if 'accompany' not in run_config.collect:
            run_config.collect.append('accompany')

    _logger.info('running config is:\n\t%s', config.pretty(run_config, '\n\t'))
    return run_config
开发者ID:genzj,项目名称:pybingwallpaper,代码行数:52,代码来源:main.py


示例17: list_markets

def list_markets():
    # extracted from Bing Account settings page
    markets = (
        ("es-AR", "Argentina",),
        ("en-AU", "Australia",),
        ("de-AT", "Austria",),
        ("nl-BE", "Belgium - Dutch",),
        ("fr-BE", "Belgium - French",),
        ("pt-BR", "Brazil",),
        ("en-CA", "Canada - English",),
        ("fr-CA", "Canada - French",),
        ("es-CL", "Chile",),
        ("zh-CN", "China",),
        ("da-DK", "Denmark",),
        ("ar-EG", "Egypt",),
        ("fi-FI", "Finland",),
        ("fr-FR", "France",),
        ("de-DE", "Germany",),
        ("zh-HK", "Hong Kong SAR",),
        ("en-IN", "India",),
        ("en-ID", "Indonesia",),
        ("en-IE", "Ireland",),
        ("it-IT", "Italy",),
        ("ja-JP", "Japan",),
        ("ko-KR", "Korea",),
        ("en-MY", "Malaysia",),
        ("es-MX", "Mexico",),
        ("nl-NL", "Netherlands",),
        ("en-NZ", "New Zealand",),
        ("nb-NO", "Norway",),
        ("en-PH", "Philippines",),
        ("pl-PL", "Poland",),
        ("pt-PT", "Portugal",),
        ("ru-RU", "Russia",),
        ("ar-SA", "Saudi Arabia",),
        ("en-SG", "Singapore",),
        ("en-ZA", "South Africa",),
        ("es-ES", "Spain",),
        ("sv-SE", "Sweden",),
        ("fr-CH", "Switzerland - French",),
        ("de-CH", "Switzerland - German",),
        ("zh-TW", "Taiwan",),
        ("tr-TR", "Turkey",),
        ("ar-AE", "United Arab Emirates",),
        ("en-GB", "United Kingdom",),
        ("en-US", "United States - English",),
        ("es-US", "United States - Spanish",),
    )
    print('Available markets:')
    for k, v in markets:
        print(k, '    ', v)
    sys_exit(0)
开发者ID:genzj,项目名称:pybingwallpaper,代码行数:52,代码来源:main.py


示例18: shutdown

def shutdown(signum, frame):
    global pidfile, s
    try:
        s.close()
    except:
        print "Cannot shutdown the socket"
    try:
        unlink(pidfile)
    except:
        pass
    thistime = datetime.now()
    print thistime.strftime("%Y-%m-%d %H:%M:%S") + " Shutdown done"
    sys_exit(0)
开发者ID:passionengine,项目名称:ii,代码行数:13,代码来源:binlsrv2.py


示例19: run

def run():

    pygame.init()

    windowRect = pygame.Rect((0, 0), (1440, 900))

    screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)  # Main game surface

    clock = pygame.time.Clock()  # Clock to regulate FPS

    caption = "Blobular"  # Window caption

    pygame.display.set_caption(caption)  # Set the caption

    bob = moveblob.MoveBlob(windowRect)  # Test blob

    num_of_players = 1

    # Create and initialize joysticks
    joysticks = []  # List to hold joystick objects

    pygame.mouse.set_visible(False)

    for x in range(0, pygame.joystick.get_count()):
        joysticks.append(pygame.joystick.Joystick(x))  # Append new joystick object to joysticks with ID of x
        joysticks[x].init()  # Initialize newly created joystick object

    while True:
        clock.tick(60)  # Cap game to 60 fps
        screen.fill(WHITE)  # Fill screen with white

        events = pygame.event.get()  # Holds a list of pygame events
        keys = pygame.key.get_pressed()  # Holds a list of keys being held down

        # If there's a QUIT event, quit Pygame and exit program
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys_exit()
            if event.type == pygame.QUIT:
                pygame.quit()
                sys_exit()

        bob.update(keys, events, joysticks)

        bob.draw(screen)

        pygame.display.flip()
开发者ID:CodyKelly,项目名称:Blobular,代码行数:49,代码来源:game.py


示例20: clean

def clean():
    response = yes_no_quiz(
        question="Are you sure you want to clean up "
                 "the developers' environment?"
    )
    if not response:
        print('Exited at user\'s request with code 0.')
        sys_exit(0)

    from xml.etree.ElementTree import parse
    from xml.sax.saxutils import escape

    contents_xml = parse(XML_FILE_ABSOLUTE_PATH)
    root = contents_xml.getroot()

    for file in root:
        relative_path = [node.text for node in file.iterfind('path')]
        absolute_path = join_path(BASE_DIR, *relative_path)
        display_path = join_path('markdownx', *relative_path)

        if not exists(absolute_path):
            continue

        with open(absolute_path, mode='r') as data_file:
            file_content = data_file.read()

        if file.find('contents').text.strip() == escape(file_content.strip()):
            delete(absolute_path, display_path)
            continue

        if replace_contents_or_not(display_path):
            file.find('contents').text = escape(file_content)
            print('> UPDATED in default setting:', display_path)
            delete(absolute_path, display_path)
            continue

        delete(absolute_path, display_path)

    delete(join_path(BASE_DIR, 'db.sqlite3'), 'db.sqlite3')

    contents_xml.write(
        file_or_filename=XML_FILE_ABSOLUTE_PATH,
        xml_declaration=True,
        encoding='UTF-8',
        method='xml'
    )

    return True
开发者ID:adi-,项目名称:django-markdownx,代码行数:48,代码来源:dev.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sys.sysexit函数代码示例发布时间:2022-05-27
下一篇:
Python sys.stdout函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap