示例#1
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        :param argv: split command-line like ``sys.argv``.
        :type argv: list[str]
        :returns: the Run object corresponding to the finished run
        :rtype: sacred.run.Run
        """
        if argv is None:
            argv = sys.argv
        all_commands = self.gather_commands()

        args = parse_args(argv,
                          description=self.doc,
                          commands=OrderedDict(all_commands))
        config_updates, named_configs = get_config_updates(args['UPDATE'])
        cmd_name = args.get('COMMAND') or self.default_command

        try:
            return self.run_command(cmd_name, config_updates, named_configs,
                                    args)
        except Exception:
            if not self.current_run or self.current_run.debug:
                raise
            elif self.current_run.pdb:
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                print_filtered_stacktrace()
示例#2
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        Parameters
        ----------
        argv : list[str] or str, optional
            Command-line as string or list of strings like ``sys.argv``.

        Returns
        -------
        sacred.run.Run
            The Run object corresponding to the finished run.

        """
        if argv is None:
            argv = sys.argv
        elif isinstance(argv, basestring):
            argv = shlex.split(argv)
        else:
            if not isinstance(argv, (list, tuple)):
                raise ValueError("argv must be str or list, but was {}".format(
                    type(argv)))
            if not all([isinstance(a, basestring) for a in argv]):
                problems = [a for a in argv if not isinstance(a, basestring)]
                raise ValueError("argv must be list of str but contained the "
                                 "following elements: {}".format(problems))

        all_commands = self.gather_commands()

        args = parse_args(argv,
                          description=self.doc,
                          commands=OrderedDict(all_commands))
        config_updates, named_configs = get_config_updates(args['UPDATE'])
        cmd_name = args.get('COMMAND') or self.default_command

        try:
            return self.run(cmd_name, config_updates, named_configs, {}, args)
        except Exception:
            if not self.current_run or self.current_run.debug:
                raise
            elif self.current_run.pdb:
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                print_filtered_stacktrace()
                exit(1)
示例#3
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        Parameters
        ----------
        argv : list[str] or str, optional
            Command-line as string or list of strings like ``sys.argv``.

        Returns
        -------
        sacred.run.Run
            The Run object corresponding to the finished run.

        """
        argv = ensure_wellformed_argv(argv)
        short_usage, usage, internal_usage = self.get_usage()
        args = docopt(internal_usage, [str(a) for a in argv[1:]], help=False)

        cmd_name = args.get('COMMAND') or self.default_command
        config_updates, named_configs = get_config_updates(args['UPDATE'])

        err = self._check_command(cmd_name)
        if not args['help'] and err:
            print(short_usage)
            print(err)
            exit(1)

        if self._handle_help(args, usage):
            exit()

        try:
            return self.run(cmd_name, config_updates, named_configs, {}, args)
        except Exception:
            if not self.current_run or self.current_run.debug:
                raise
            elif self.current_run.pdb:
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                print_filtered_stacktrace()
                exit(1)
示例#4
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        Parameters
        ----------
        argv : list[str] or str, optional
            Command-line as string or list of strings like ``sys.argv``.

        Returns
        -------
        sacred.run.Run
            The Run object corresponding to the finished run.

        """
        argv = ensure_wellformed_argv(argv)
        short_usage, usage = self.get_usage()
        args = docopt(usage, [str(a) for a in argv[1:]], help=False)

        cmd_name = args.get('COMMAND') or self.default_command
        config_updates, named_configs = get_config_updates(args['UPDATE'])

        err = self._check_command(cmd_name)
        if not args['help'] and err:
            print(short_usage)
            print(err)
            exit(1)

        if self._handle_help(args, usage):
            exit()

        try:
            return self.run(cmd_name, config_updates, named_configs, {}, args)
        except Exception:
            if not self.current_run or self.current_run.debug:
                raise
            elif self.current_run.pdb:
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                print_filtered_stacktrace()
                exit(1)
示例#5
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        :param argv: split command-line like ``sys.argv``.
        :type argv: list[str]
        :returns: the Run object corresponding to the finished run
        :rtype: sacred.run.Run
        """
        if argv is None:
            argv = sys.argv
        all_commands = self._gather_commands()

        args = parse_args(argv,
                          description=self.doc,
                          commands=OrderedDict(all_commands))
        config_updates, named_configs = get_config_updates(args['UPDATE'])
        loglevel = args.get('--logging')
        for obs in get_observers(args):
            if obs not in self.observers:
                self.observers.append(obs)

        if args['COMMAND']:
            cmd_name = args['COMMAND']
        else:
            cmd_name = self.default_command

        try:
            return self.run_command(cmd_name,
                                    config_updates=config_updates,
                                    named_configs_to_use=named_configs,
                                    log_level=loglevel)
        except Exception:
            if args['--debug']:
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                print_filtered_stacktrace()
示例#6
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        :param argv: split command-line like ``sys.argv``.
        :type argv: list[str]
        :return: The result of the command that was run.
        """
        if argv is None:
            argv = sys.argv
        all_commands = self._gather_commands()

        args = parse_args(argv,
                          description=self.doc,
                          commands=OrderedDict(all_commands))
        config_updates, named_configs = get_config_updates(args['UPDATE'])
        loglevel = args.get('--logging')
        for obs in get_observers(args):
            if obs not in self.observers:
                self.observers.append(obs)

        if args['COMMAND']:
            cmd_name = args['COMMAND']
        else:
            cmd_name = self.default_command

        try:
            return self.run_command(cmd_name,
                                    config_updates=config_updates,
                                    named_configs_to_use=named_configs,
                                    loglevel=loglevel)
        except:
            if args['--debug']:
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                print_filtered_stacktrace()
示例#7
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        Parameters
        ----------
        argv : list[str] or str, optional
            Command-line as string or list of strings like ``sys.argv``.

        Returns
        -------
        sacred.run.Run
            The Run object corresponding to the finished run.

        """
        argv = ensure_wellformed_argv(argv)
        short_usage, usage, internal_usage = self.get_usage()
        args = docopt(internal_usage, [str(a) for a in argv[1:]], help=False)

        cmd_name = args.get('COMMAND') or self.default_command
        config_updates, named_configs = get_config_updates(args['UPDATE'])

        err = self._check_command(cmd_name)
        if not args['help'] and err:
            print(short_usage)
            print(err)
            exit(1)

        if self._handle_help(args, usage):
            exit()

        try:
            return self.run(cmd_name, config_updates, named_configs, {}, args)
        except Exception as e:
            if self.current_run:
                debug = self.current_run.debug
            else:
                # The usual command line options are applied after the run
                # object is built completely. Some exceptions (e.g.
                # ConfigAddedError) are raised before this. In these cases,
                # the debug flag must be checked manually.
                debug = args.get('--debug', False)

            if debug:
                # Debug: Don't change behaviour, just re-raise exception
                raise
            elif self.current_run and self.current_run.pdb:
                # Print exception and attach pdb debugger
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                # Handle pretty printing of exceptions. This includes
                # filtering the stacktrace and printing the usage, as
                # specified by the exceptions attributes
                if isinstance(e, SacredError):
                    print(format_sacred_error(e, short_usage), file=sys.stderr)
                else:
                    print_filtered_stacktrace()
                exit(1)
示例#8
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        Parameters
        ----------
        argv : list[str] or str, optional
            Command-line as string or list of strings like ``sys.argv``.

        Returns
        -------
        sacred.run.Run
            The Run object corresponding to the finished run.

        """
        argv = ensure_wellformed_argv(argv)
        short_usage, usage, internal_usage = self.get_usage()
        args = docopt(internal_usage, [str(a) for a in argv[1:]], help=False)

        cmd_name = args.get('COMMAND') or self.default_command
        config_updates, named_configs = get_config_updates(args['UPDATE'])

        err = self._check_command(cmd_name)
        if not args['help'] and err:
            print(short_usage)
            print(err)
            exit(1)

        if self._handle_help(args, usage):
            exit()

        try:
            return self.run(cmd_name, config_updates, named_configs, {}, args)
        except Exception as e:
            if self.current_run:
                debug = self.current_run.debug
            else:
                # The usual command line options are applied after the run
                # object is built completely. Some exceptions (e.g.
                # ConfigAddedError) are raised before this. In these cases,
                # the debug flag must be checked manually.
                debug = args.get('--debug', False)

            if debug:
                # Debug: Don't change behaviour, just re-raise exception
                raise
            elif self.current_run and self.current_run.pdb:
                # Print exception and attach pdb debugger
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                # Handle pretty printing of exceptions. This includes
                # filtering the stacktrace and printing the usage, as
                # specified by the exceptions attributes
                if isinstance(e, SacredError):
                    print(format_sacred_error(e, short_usage), file=sys.stderr)
                else:
                    print_filtered_stacktrace()
                exit(1)
示例#9
0
    def run_commandline(self, argv=None):
        """
        Run the command-line interface of this experiment.

        If ``argv`` is omitted it defaults to ``sys.argv``.

        Parameters
        ----------
        argv : list[str] or str, optional
            Command-line as string or list of strings like ``sys.argv``.

        Returns
        -------
        sacred.run.Run
            The Run object corresponding to the finished run.

        """
        if argv is None:
            argv = sys.argv
        elif isinstance(argv, basestring):
            argv = shlex.split(argv)
        else:
            if not isinstance(argv, (list, tuple)):
                raise ValueError("argv must be str or list, but was {}"
                                 .format(type(argv)))
            if not all([isinstance(a, basestring) for a in argv]):
                problems = [a for a in argv if not isinstance(a, basestring)]
                raise ValueError("argv must be list of str but contained the "
                                 "following elements: {}".format(problems))

        short_usage, usage = self.get_usage()
        args = docopt(usage, [str(a) for a in argv[1:]], help=False)
        commands = OrderedDict(self.gather_commands())
        cmd_name = args.get('COMMAND') or self.default_command
        config_updates, named_configs = get_config_updates(args['UPDATE'])

        if cmd_name is not None and cmd_name not in commands:
            print(short_usage)
            print('Error: Command "{}" not found. Available commands are: '
                  '{}'.format(cmd_name, ", ".join(commands.keys())))
            exit(1)

        if args['help'] or args['--help']:
            if args['COMMAND'] is None:
                print(usage)
            else:
                print(help_for_command(commands[args['COMMAND']]))
            exit()

        if cmd_name is None:
            print(short_usage)
            print('Error: No command found to be run. Specify a command'
                  ' or define main function. Available commands'
                  ' are: {}'.format(", ".join(commands.keys())))
            exit(1)

        try:
            return self.run(cmd_name, config_updates, named_configs, {}, args)
        except Exception:
            if not self.current_run or self.current_run.debug:
                raise
            elif self.current_run.pdb:
                import traceback
                import pdb
                traceback.print_exception(*sys.exc_info())
                pdb.post_mortem()
            else:
                print_filtered_stacktrace()
                exit(1)