Python sys.args() Examples

The following are code examples for showing how to use sys.args(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: CPU   Author: MicBrain   File: autograder_base.py    Apache License 2.0 6 votes vote down vote up
def main(tests):
  if len(sys.argv) == 2:
    if sys.argv[1] == '-here':
      test_submission('here',sys.stdout,tests)
    else:
      print >> sys.stderr, "Incorrect usage!"
  elif len(sys.argv) == 3:
    if sys.argv[1] == '-login':
      extract_and_test(sys.args[2],sys.stdout,tests)
    else:
      print >> sys.stderr, "Incorrect usage!"
  elif len(sys.argv) == 1:
    run_tests(tests)
    sys.exit(0)
  else:
    print >> sys.stderr, "Incorrect usage!"
  sys.exit(1) 
Example 2
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 6 votes vote down vote up
def _load_options(self, args):
        '''Load config from options -E and -C from cli arguments.

        >>> c = Config()
        >>> c._load_options(['-E="data_file: data.txt"'])
        []
        >>> c.data_file
        'data.txt'
        '''
        if args is None:
            return
        for arg in findregex('^(-E|-C)=', args):
            config_string, option = _get_option(arg)
            if option == 'C':
                # Expand $ keys in file name
                config_string = self.render(config_string)
                config_string = self._load_config_file(config_string)
            if 'prog' not in self and 'clg' in config_string:
                self.prog = args[0]
            self._expand_keys(config_string)
        # Prevent clg seeing -E or -C options
        return delregex('^(-E|-C)=', args) 
Example 3
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 6 votes vote down vote up
def _load_config_cli(self, args, types=set()):
        '''Load config parsing cli arguments with clg.
        clg key config may come from config file, cli arg, or python config.

        >>> from os.path import basename
        >>> c = Config()
        >>> c.update("""
        ...     clg:
        ...         args:
        ...             filename:
        ...                 type: basename
        ...     """)
        >>> c._load_config_cli(args=['', '/data/data.txt'], types={basename})
        >>> c.filename
        'data.txt'
        '''
        if not args or 'clg' not in self:
            return
        clg_args = _clg_parse(self.clg, args, types)
        self._expand_keys(clg_args)  # Add config from cli args
        del self['clg']  # Remove clg key from Config 
Example 4
Project: ocrd_typegroups_classifier   Author: seuretm   File: simple.py    Apache License 2.0 5 votes vote down vote up
def cli():
    """
    Run on sys.args
    """
    if len(sys.argv) < 3 or len(sys.argv) > 4:
        print('Syntax: %s network-file image-file [stride]' % sys.argv[0])
        quit(1)
    network_file = sys.argv[1]
    image_file = Image.open(sys.argv[2])
    stride = int(sys.argv[3]) if len(sys.argv) > 3 else 96
    classifier = TypegroupsClassifier(network_file, stride)
    result = classifier.run(image_file)
    print(result) 
Example 5
Project: modl   Author: Tordek   File: modl_cli.py    MIT License 5 votes vote down vote up
def main(args):
    if len(args) > 2:
        print("Usage: {} [script]".format(sys.args[0]), file=sys.stderr)
        exit(-1)
    elif len(args) == 2:
        exit(run_file(args[1]))
    else:
        run_prompt() 
Example 6
Project: eden   Author: facebookexperimental   File: win32mbcs.py    GNU General Public License v2.0 5 votes vote down vote up
def basewrapper(func, argtype, enc, dec, args, kwds):
    # check check already converted, then call original
    for arg in args:
        if isinstance(arg, argtype):
            return func(*args, **kwds)

    try:
        # convert string arguments, call func, then convert back the
        # return value.
        return enc(func(*dec(args), **dec(kwds)))
    except UnicodeError:
        raise error.Abort(
            _("[win32mbcs] filename conversion failed with" " %s encoding\n")
            % (_encoding)
        ) 
Example 7
Project: eden   Author: facebookexperimental   File: win32mbcs.py    GNU General Public License v2.0 5 votes vote down vote up
def wrapper(func, args, kwds):
    return basewrapper(func, unicode, encode, decode, args, kwds)  # noqa 
Example 8
Project: eden   Author: facebookexperimental   File: win32mbcs.py    GNU General Public License v2.0 5 votes vote down vote up
def reversewrapper(func, args, kwds):
    return basewrapper(func, str, decode, encode, args, kwds) 
Example 9
Project: eden   Author: facebookexperimental   File: win32mbcs.py    GNU General Public License v2.0 5 votes vote down vote up
def wrapperforlistdir(func, args, kwds):
    # Ensure 'path' argument ends with os.sep to avoids
    # misinterpreting last 0x5c of MBCS 2nd byte as path separator.
    if args:
        args = list(args)
        args[0] = appendsep(args[0])
    if "path" in kwds:
        kwds["path"] = appendsep(kwds["path"])
    return func(*args, **kwds) 
Example 10
Project: eden   Author: facebookexperimental   File: win32mbcs.py    GNU General Public License v2.0 5 votes vote down vote up
def wrapname(name, wrapper):
    module, name = name.rsplit(".", 1)
    module = sys.modules[module]
    func = getattr(module, name)

    def f(*args, **kwds):
        return wrapper(func, args, kwds)

    f.__name__ = func.__name__
    setattr(module, name, f)


# List of functions to be wrapped.
# NOTE: os.path.dirname() and os.path.basename() are safe because
#       they use result of os.path.split() 
Example 11
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        '''Process first argument as yaml if it is a string'''
        args = self._process_args(*args, **kwargs)
        super(Odict, self).__init__(*args, **kwargs) 
Example 12
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 5 votes vote down vote up
def _process_args(self, *args, **kwargs):
        if len(args) == 1 and isinstance(args[0], str):
            try:
                pair_list = self.load(args[0])
            except ScannerError:
                # Yaml needs {} on multi-key single-line strings
                pair_list = self.load('{{{}}}'.format(args[0]))
            args = [pair_list] if pair_list else []
        return args 
Example 13
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 5 votes vote down vote up
def update(self, *args, **kwargs):
        '''Add yaml string as posible argument

        >>> d = Odict('hi: there')
        >>> d.hi
        'there'
        >>> d.update({'hi': 'Liss'})
        >>> d.hi
        'Liss'
        '''
        args = self._process_args(*args, **kwargs)
        super(Odict, self).update(*args, **kwargs)
        # Remove '_' key possible used by include
        if '_' in self:
            del self['_'] 
Example 14
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 5 votes vote down vote up
def dump(self, default_flow_style=True):
        '''Serialize odict into yaml string'''
        class Dumper(yaml.SafeDumper):
            def __init__(self, *args, **kwargs):
                super(Dumper, self).__init__(*args, **kwargs)
                self.ignore_aliases = lambda self: True
                self.add_representer(Odict, lambda self, data:
                    self.represent_dict(data.items()))

            def increase_indent(self, flow=False, indentless=False):
                return super(Dumper, self).increase_indent(flow, False)

        stream = cStringIO()
        yaml.dump(self, stream, Dumper, default_flow_style=default_flow_style)
        return stream.getvalue()[:-1] 
Example 15
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 5 votes vote down vote up
def run(self, namespace='__main__'):
        r'''Run selected subparser command from namespace.
        Namespace can be full qualified string (eg: package.module.class), a
        module or a class. Subparser command correspond with either a function
        or a method from the namespace.

        >>> conf = Config("""
        ...            prog: netapplet.py
        ...            clg:
        ...                subparsers:
        ...                    install:
        ...                        help: 'run as $prog install | bash'""")
        >>> def install(c):
        ...     print('echo "Installation shell script lines for {}."'.format(
        ...         c.prog))
        >>> # Ensure install function is reachable
        >>> __import__(__name__).install = install
        >>> c = Config(conf, args=['', 'install'])
        >>> c.run(__name__)
        echo "Installation shell script lines for netapplet.py."
        '''
        if isinstance(namespace, str):  # rename namespace with its last name
            lname = __import__(namespace.partition('.')[0])
            for name in namespace.split('.')[1:]:
                lname = getattr(lname, name)
            namespace = lname
        if isinstance(namespace, type):  # namespace is a class
            return getattr(namespace(self), str(self.command0))()
        return getattr(namespace, str(self.command0))(self) 
Example 16
Project: croutera   Author: cristianoliveira   File: test_runner.py    MIT License 5 votes vote down vote up
def test_it_runs_with_no_argument(self, show_help):
        sys.args = []

        runner.run()

        show_help.assert_called_with() 
Example 17
Project: git-grid   Author: RocketScienceAbteilung   File: __init__.py    MIT License 5 votes vote down vote up
def main(inargs=None):
    args = gitgrid.utils.utils.controller_args()

    sys.stdout = gitgrid.utils.utils.Unbuffered(sys.stdout)
    controller = gridcontroller.create(args.controller, args.input, args.output)
    manager = PageManager(controller)
    controller.loop() 
Example 18
Project: barman   Author: 2ndquadrant-it   File: walarchive.py    GNU General Public License v3.0 5 votes vote down vote up
def main(args=None):
    """
    The main script entry point

    :param list[str] args: the raw arguments list. When not provided
        it defaults to sys.args[1:]
    """
    config = parse_arguments(args)

    # Do connectivity test if requested
    if config.test:
        connectivity_test(config)
        return  # never reached

    # Check WAL destination is not a directory
    if os.path.isdir(config.wal_path):
        exit_with_error("WAL_PATH cannot be a directory: %s" %
                        config.wal_path)

    try:
        # Execute barman put-wal through the ssh connection
        ssh_process = RemotePutWal(config, config.wal_path)
    except EnvironmentError as exc:
        exit_with_error('Error executing ssh: %s' % exc)
        return  # never reached

    # Wait for termination of every subprocess. If CTRL+C is pressed,
    # terminate all of them
    RemotePutWal.wait_for_all()

    # If the command succeeded exit here
    if ssh_process.returncode == 0:
        return

    # Report the exit code, remapping ssh failure code (255) to 3
    if ssh_process.returncode == 255:
        exit_with_error("Connection problem with ssh", 3)
    else:
        exit_with_error("Remote 'barman put-wal' command has failed!",
                        ssh_process.returncode) 
Example 19
Project: barman   Author: 2ndquadrant-it   File: walarchive.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ChecksumTarInfo, self).__init__(*args, **kwargs)
        self.data_checksum = None 
Example 20
Project: transport_examples   Author: digidotcom   File: hi_poll.py    Mozilla Public License 2.0 5 votes vote down vote up
def display_help():
    print """
Usage: python {0}
Args (optional):
-[H|?] prints help, then exits
-A[voltage|current] # sets analog reading by voltage or current
-L<number of loops>
-W<wait milliseconds between loops>
--Ex. > python {0} -Avoltage -L100 -W250
""".format(sys.args[0]) 
Example 21
Project: printed-vs-handwritten   Author: seuretm   File: simple.py    Apache License 2.0 5 votes vote down vote up
def cli():
    """
    Run on sys.args
    """
    if len(sys.argv) < 3 or len(sys.argv) > 4:
        print('Syntax: %s network-file image-file [stride]' % sys.argv[0])
        quit(1)
    network_file = sys.argv[1]
    image_file = Image.open(sys.argv[2])
    stride = int(sys.argv[3]) if len(sys.argv) > 3 else 96
    classifier = TypegroupsClassifier(network_file, stride)
    result = classifier.run(image_file)
    print(result) 
Example 22
Project: loadconfig   Author: mzdaniel   File: __init__.py    MIT License 4 votes vote down vote up
def load(yaml_string):
        '''Return pair list from a yaml string'''
        class Loader(yaml.SafeLoader):
            yaml_mapping = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
            _data = ''

            def __init__(self, *args, **kwargs):
                super(Loader, self).__init__(*args, **kwargs)
                self.add_constructor(self.yaml_mapping, self.construct_mapping)
                self.add_constructor('!env', self.env)
                self.add_constructor('!read', self.read)
                self.add_constructor('!include', self.include)
                self.add_constructor('!expand', self.expand)

            def env(self, safeloader, node):
                node = self.construct_scalar(node)
                if node.upper() in environ:
                    return {node: environ[node.upper()]}
                return {node: ''}

            def read(self, safeloader, node):
                node = self.construct_scalar(node)
                return read_file(node)

            def include(self, safeloader, node):
                node = self.construct_scalar(node)
                filepath, sep, key = node.partition(':')
                self._data = yaml.load(read_file(filepath), Loader)
                return self.subkey(key)

            def expand(self, safeloader, node):
                key = self.construct_scalar(node)
                self._data = safeloader._data
                return self.subkey(key)

            def subkey(self, key):
                if not self._data:
                    return ''
                data = deepcopy(self._data)
                if key == '&':
                    return ''
                for k in key.split(':'):
                    if not k:
                        return data
                    data = data.get(k)
                    if data is None:
                        return ''
                return data

            def construct_mapping(self, safeloader, node):
                safeloader.flatten_mapping(node)
                return Odict(safeloader.construct_pairs(node))

        return yaml.load(yaml_string, Loader) 
Example 23
Project: paasta   Author: Yelp   File: status.py    Apache License 2.0 4 votes vote down vote up
def get_filters(args,) -> Sequence[Callable[[InstanceConfig], bool]]:
    """Figures out which filters to apply from an args object, and returns them

    :param args: args object
    :returns: list of functions that take an instance config and returns if the instance conf matches the filter
    """
    filters = []

    if args.service:
        filters.append(lambda conf: conf.get_service() in args.service.split(","))

    if args.clusters:
        filters.append(lambda conf: conf.get_cluster() in args.clusters.split(","))

    if args.instances:
        filters.append(lambda conf: conf.get_instance() in args.instances.split(","))

    if args.deploy_group:
        filters.append(
            lambda conf: conf.get_deploy_group() in args.deploy_group.split(",")
        )

    if args.registration:
        normalized_regs = normalize_registrations(
            service=args.service, registrations=args.registration.split(",")
        )
        filters.append(
            lambda conf: any(
                reg in normalized_regs
                for reg in (
                    conf.get_registrations()
                    if hasattr(conf, "get_registrations")
                    else []
                )
            )
        )

    if args.owner:
        owners = args.owner.split(",")

        filters.append(
            # If the instance owner is None, check the service owner, else check the instance owner
            lambda conf: get_team(
                overrides={}, service=conf.get_service(), soa_dir=args.soa_dir
            )
            in owners
            if conf.get_team() is None
            else conf.get_team() in owners
        )

    return filters 
Example 24
Project: paasta   Author: Yelp   File: status.py    Apache License 2.0 4 votes vote down vote up
def paasta_status(args) -> int:
    """Print the status of a Yelp service running on PaaSTA.
    :param args: argparse.Namespace obj created from sys.args by cli"""
    soa_dir = args.soa_dir
    system_paasta_config = load_system_paasta_config()

    return_codes = [0]
    tasks = []
    clusters_services_instances = apply_args_filters(args)
    for cluster, service_instances in clusters_services_instances.items():
        for service, instances in service_instances.items():
            all_flink = all(i == FlinkDeploymentConfig for i in instances.values())
            actual_deployments: Mapping[str, str]
            if all_flink:
                actual_deployments = {}
            else:
                actual_deployments = get_actual_deployments(service, soa_dir)
            if all_flink or actual_deployments:
                deploy_pipeline = list(get_planned_deployments(service, soa_dir))
                tasks.append(
                    (
                        report_status_for_cluster,
                        dict(
                            service=service,
                            cluster=cluster,
                            deploy_pipeline=deploy_pipeline,
                            actual_deployments=actual_deployments,
                            instance_whitelist=instances,
                            system_paasta_config=system_paasta_config,
                            verbose=args.verbose,
                        ),
                    )
                )
            else:
                paasta_print(missing_deployments_message(service))
                return_codes.append(1)

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
        tasks = [executor.submit(t[0], **t[1]) for t in tasks]  # type: ignore
        for future in concurrent.futures.as_completed(tasks):  # type: ignore
            return_code, output = future.result()
            paasta_print("\n".join(output))
            return_codes.append(return_code)

    return max(return_codes) 
Example 25
Project: paasta   Author: Yelp   File: logs.py    Apache License 2.0 4 votes vote down vote up
def validate_filtering_args(args, log_reader):
    if not log_reader.SUPPORTS_LINE_OFFSET and args.line_offset is not None:
        paasta_print(
            PaastaColors.red(
                log_reader.__class__.__name__ + " does not support line based offsets"
            ),
            file=sys.stderr,
        )
        return False
    if not log_reader.SUPPORTS_LINE_COUNT and args.line_count is not None:
        paasta_print(
            PaastaColors.red(
                log_reader.__class__.__name__
                + " does not support line count based log retrieval"
            ),
            file=sys.stderr,
        )
        return False
    if not log_reader.SUPPORTS_TAILING and args.tail:
        paasta_print(
            PaastaColors.red(
                log_reader.__class__.__name__ + " does not support tailing"
            ),
            file=sys.stderr,
        )
        return False
    if not log_reader.SUPPORTS_TIME and (
        args.time_from is not None or args.time_to is not None
    ):
        paasta_print(
            PaastaColors.red(
                log_reader.__class__.__name__ + " does not support time based offsets"
            ),
            file=sys.stderr,
        )
        return False

    if args.tail and (
        args.line_count is not None
        or args.time_from is not None
        or args.time_to is not None
        or args.line_offset is not None
    ):
        paasta_print(
            PaastaColors.red(
                "You cannot specify line/time based filtering parameters when tailing"
            ),
            file=sys.stderr,
        )
        return False

    # Can't have both
    if args.line_count is not None and args.time_from is not None:
        paasta_print(
            PaastaColors.red("You cannot filter based on both line counts and time"),
            file=sys.stderr,
        )
        return False

    return True 
Example 26
Project: paasta   Author: Yelp   File: logs.py    Apache License 2.0 4 votes vote down vote up
def pick_default_log_mode(
    args, log_reader, service, levels, components, clusters, instances
):
    if log_reader.SUPPORTS_LINE_COUNT:
        paasta_print(
            PaastaColors.cyan(
                "Fetching 100 lines and applying filters. Try -n 1000 for more lines..."
            ),
            file=sys.stderr,
        )
        log_reader.print_last_n_logs(
            service=service,
            line_count=100,
            levels=levels,
            components=components,
            clusters=clusters,
            instances=instances,
            raw_mode=args.raw_mode,
        )
        return 0
    elif log_reader.SUPPORTS_TIME:
        start_time, end_time = generate_start_end_time()
        paasta_print(
            PaastaColors.cyan(
                "Fetching a specific time period and applying filters..."
            ),
            file=sys.stderr,
        )
        log_reader.print_logs_by_time(
            service=service,
            start_time=start_time,
            end_time=end_time,
            levels=levels,
            components=components,
            clusters=clusters,
            instances=instances,
            raw_mode=args.raw_mode,
        )
        return 0
    elif log_reader.SUPPORTS_TAILING:
        paasta_print(
            PaastaColors.cyan("Tailing logs and applying filters..."), file=sys.stderr
        )
        log_reader.tail_logs(
            service=service,
            levels=levels,
            components=components,
            clusters=clusters,
            instances=instances,
            raw_mode=args.raw_mode,
        )
        return 0 
Example 27
Project: barman   Author: 2ndquadrant-it   File: walarchive.py    GNU General Public License v3.0 4 votes vote down vote up
def parse_arguments(args=None):
    """
    Parse the command line arguments

    :param list[str] args: the raw arguments list. When not provided
        it defaults to sys.args[1:]
    :rtype: argparse.Namespace
    """
    parser = argparse.ArgumentParser(
        description="This script will be used as an 'archive_command' "
                    "based on the put-wal feature of Barman. "
                    "A ssh connection will be opened to the Barman host.",
    )
    parser.add_argument(
        '-V', '--version',
        action='version', version='%%(prog)s %s' % barman.__version__)
    parser.add_argument(
        "-U", "--user", default=DEFAULT_USER,
        help="The user used for the ssh connection to the Barman server. "
             "Defaults to '%(default)s'.",
    )
    parser.add_argument(
        '-c', '--config',
        metavar="CONFIG",
        help='configuration file on the Barman server',
    )
    parser.add_argument(
        '-t', '--test',
        action='store_true',
        help="test both the connection and the configuration of the "
             "requested PostgreSQL server in Barman for WAL retrieval. "
             "With this option, the 'wal_name' mandatory argument is "
             "ignored.",
    )
    parser.add_argument(
        "barman_host",
        metavar="BARMAN_HOST",
        help="The host of the Barman server.",
    )
    parser.add_argument(
        "server_name",
        metavar="SERVER_NAME",
        help="The server name configured in Barman "
             "from which WALs are taken.",
    )
    parser.add_argument(
        "wal_path",
        metavar="WAL_PATH",
        help="The value of the '%%p' keyword "
             "(according to 'archive_command').",
    )
    return parser.parse_args(args=args) 
Example 28
Project: barman   Author: 2ndquadrant-it   File: walrestore.py    GNU General Public License v3.0 4 votes vote down vote up
def main(args=None):
    """
    The main script entry point
    """
    config = parse_arguments(args)

    # Do connectivity test if requested
    if config.test:
        connectivity_test(config)
        return  # never reached

    # Check WAL destination is not a directory
    if os.path.isdir(config.wal_dest):
        exit_with_error("WAL_DEST cannot be a directory: %s" %
                        config.wal_dest)

    # Open the destination file
    try:
        dest_file = open(config.wal_dest, 'wb')
    except EnvironmentError as e:
        exit_with_error("Cannot open '%s' (WAL_DEST) for writing: %s" %
                        (config.wal_dest, e))
        return  # never reached

    # If the file is present in SPOOL_DIR use it and terminate
    try_deliver_from_spool(config, dest_file)

    # If required load the list of files to download in parallel
    additional_files = peek_additional_files(config)

    try:
        # Execute barman get-wal through the ssh connection
        ssh_process = RemoteGetWal(config, config.wal_name, dest_file)
    except EnvironmentError as e:
        exit_with_error('Error executing "ssh": %s' % e, sleep=config.sleep)
        return  # never reached

    # Spawn a process for every additional file
    parallel_ssh_processes = spawn_additional_process(
        config, additional_files)

    # Wait for termination of every subprocess. If CTRL+C is pressed,
    # terminate all of them
    try:
        RemoteGetWal.wait_for_all()
    finally:
        # Cleanup failed spool files in case of errors
        for process in parallel_ssh_processes:
            if process.returncode != 0:
                os.unlink(process.dest_file)

    # If the command succeeded exit here
    if ssh_process.returncode == 0:
        sys.exit(0)

    # Report the exit code, remapping ssh failure code (255) to 3
    if ssh_process.returncode == 255:
        exit_with_error("Connection problem with ssh", 3, sleep=config.sleep)
    else:
        exit_with_error("Remote 'barman get-wal' command has failed!",
                        ssh_process.returncode, sleep=config.sleep) 
Example 29
Project: moderngl-window   Author: moderngl   File: __init__.py    MIT License 4 votes vote down vote up
def run_window_config(config_cls: WindowConfig, timer=None, args=None) -> None:
    """
    Run an WindowConfig entering a blocking main loop

    Args:
        config_cls: The WindowConfig class to render
        args: Override sys.args
    """
    setup_basic_logging(config_cls.log_level)
    values = parse_args(args)
    window_cls = get_local_window_cls(values.window)

    # Calculate window size
    size = values.size or config_cls.window_size
    size = int(size[0] * values.size_mult), int(size[1] * values.size_mult)

    # Resolve cursor
    show_cursor = values.cursor
    if show_cursor is None:
        show_cursor = config_cls.cursor

    window = window_cls(
        title=config_cls.title,
        size=size,
        fullscreen=values.fullscreen,
        resizable=values.resizable if values.resizable is not None else config_cls.resizable,
        gl_version=config_cls.gl_version,
        aspect_ratio=config_cls.aspect_ratio,
        vsync=values.vsync,
        samples=values.samples if values.samples is not None else config_cls.samples,
        cursor=show_cursor if show_cursor is not None else True,
    )
    window.print_context_info()
    activate_context(window=window)
    timer = Timer()
    window.config = config_cls(ctx=window.ctx, wnd=window, timer=timer)

    timer.start()

    while not window.is_closing:
        current_time, delta = timer.next_frame()

        window.clear()
        window.render(current_time, delta)
        window.swap_buffers()

    _, duration = timer.stop()
    window.destroy()
    if duration > 0:
        logger.info("Duration: {0:.2f}s @ {1:.2f} FPS".format(duration, window.frames / duration)) 
Example 30
Project: moderngl-window   Author: moderngl   File: __init__.py    MIT License 4 votes vote down vote up
def parse_args(args=None):
    """Parse arguments from sys.argv"""
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '-wnd', '--window',
        choices=find_window_classes(),
        help='Name for the window type to use',
    )
    parser.add_argument(
        '-fs', '--fullscreen',
        action="store_true",
        help='Open the window in fullscreen mode',
    )
    parser.add_argument(
        '-vs', '--vsync',
        type=valid_bool,
        default='1',
        help="Enable or disable vsync",
    )
    parser.add_argument(
        '-r', '--resizable',
        type=valid_bool,
        default=None,
        help="Enable/disable window resize",
    )
    parser.add_argument(
        '-s', '--samples',
        type=int,
        help="Specify the desired number of samples to use for multisampling",
    )
    parser.add_argument(
        '-c', '--cursor',
        type=valid_bool,
        help="Enable or disable displaying the mouse cursor",
    )
    parser.add_argument(
        '--size',
        type=valid_window_size,
        help="Window size",
    )
    parser.add_argument(
        '--size_mult',
        type=valid_window_size_multiplier,
        default=1.0,
        help="Multiplier for the window size making it easy scale the window",
    )

    return parser.parse_args(args or sys.argv[1:])


# --- Validators ---