Пример #1
0
def run(session, text, *, log=True, downgrade_errors=False):
    """execute a textual command

    Parameters
    ----------
    text : string
        The text of the command to execute.
    log : bool
        Print the command text to the reply log.
    downgrade_errors : bool
        True if errors in the command should be logged as informational.
    """

    from chimerax.core.commands import Command
    from chimerax.core.errors import UserError
    command = Command(session)
    try:
        results = command.run(text, log=log)
    except UserError as err:
        if downgrade_errors:
            session.logger.info(str(err))
        else:
            raise
        results = []
    return results[0] if len(results) == 1 else results
Пример #2
0
 def process_command(self, command_text):
     if self._command_runner is None:
         from chimerax.core.commands import Command
         from chimerax.core.commands.cli import RegisteredCommandInfo
         command_registry = RegisteredCommandInfo()
         self._register_commands(command_registry)
         self._command_runner = Command(self.alignment.session, registry=command_registry)
     self._command_runner.run(command_text, log=False)
Пример #3
0
def run(session, sv, text):
    from chimerax.core.commands import Command
    cmd = Command(session, registry=registry)
    global _sv
    _sv = sv
    try:
        cmd.run(text, log=False)
    finally:
        _sv = None
Пример #4
0
    def execute(self):
        from contextlib import contextmanager

        @contextmanager
        def processing_command(line_edit, cmd_text, command_worked,
                               select_failed):
            line_edit.blockSignals(True)
            self._processing_command = True
            # as per the docs for contextmanager, the yield needs
            # to be in a try/except if the exit code is to execute
            # after errors
            try:
                yield
            finally:
                line_edit.blockSignals(False)
                line_edit.setText(cmd_text)
                if command_worked[0] or select_failed:
                    line_edit.selectAll()
                self._processing_command = False

        session = self.session
        logger = session.logger
        text = self.text.lineEdit().text()
        logger.status("")
        from chimerax.core import errors
        from chimerax.core.commands import Command
        from html import escape
        for cmd_text in text.split("\n"):
            if not cmd_text:
                continue
            # don't select the text if the command failed, so that
            # an accidental keypress won't erase the command, which
            # probably needs to be edited to work
            command_worked = [False]
            with processing_command(self.text.lineEdit(), cmd_text,
                                    command_worked,
                                    self.settings.select_failed):
                try:
                    self._just_typed_command = cmd_text
                    cmd = Command(session)
                    cmd.run(cmd_text)
                    command_worked[0] = True
                except SystemExit:
                    # TODO: somehow quit application
                    raise
                except errors.UserError as err:
                    logger.status(str(err), color="crimson")
                    from chimerax.core.logger import error_text_format
                    logger.info(error_text_format % escape(str(err)),
                                is_html=True)
                except BaseException:
                    raise
        self.set_focus()
Пример #5
0
def log_equivalent_command(session, command_text):
    """
    Log a command.  This is typically used to show the equivalent
    command for some action (button press, mouse drag, ...) done
    with the grahical user interface.
    """
    from chimerax.core.commands import Command
    from chimerax.core.errors import UserError
    command = Command(session)
    try:
        command.run(command_text, log_only=True)
    except UserError as err:
        session.logger.info(str(err))
Пример #6
0
def cmd_save(session, file_name, rest_of_line, *, log=True):
    tokens = []
    remainder = rest_of_line
    while remainder:
        token, token_log, remainder = next_token(remainder)
        remainder = remainder.lstrip()
        tokens.append(token)
    format_name = None
    for i in range(len(tokens)-2, -1, -2):
        test_token = tokens[i].lower()
        if "format".startswith(test_token):
            format_name = tokens[i+1]
    provider_cmd_text = "save " + " ".join([FileNameArg.unparse(file_name)]
        + [StringArg.unparse(token) for token in tokens])

    try:
        from .manager import NoSaverError
        mgr = session.save_command
        data_format= file_format(session, file_name, format_name)
        try:
            provider_args = mgr.save_args(data_format)
        except NoSaverError as e:
            raise LimitationError(str(e))

        # register a private 'save' command that handles the provider's keywords
        registry = RegisteredCommandInfo()
        keywords = {
            'format': DynamicEnum(lambda ses=session: format_names(ses)),
        }
        for keyword, annotation in provider_args.items():
            if keyword in keywords:
                raise ValueError("Save-provider keyword '%s' conflicts with builtin arg"
                    " of same name" % keyword)
            keywords[keyword] = annotation
        # for convenience, allow 'models' to be a second positional argument instead of a keyword
        if 'models' in keywords:
            optional = [('models', keywords['models'])]
            del keywords['models']
        else:
            optional = []
        desc = CmdDesc(required=[('file_name', SaveFileNameArg)], optional=optional,
            keyword=keywords.items(), hidden=mgr.hidden_args(data_format), synopsis="unnecessary")
        register("save", desc, provider_save, registry=registry)
    except BaseException as e:
        # want to log command even for keyboard interrupts
        log_command(session, "save", provider_cmd_text, url=_main_save_CmdDesc.url)
        raise
    Command(session, registry=registry).run(provider_cmd_text, log=log)
Пример #7
0
def run_expectfail(session, command):
    from chimerax.core.errors import NotABug, UserError
    from chimerax.core.commands import run, Command

    # first confirm that command is an actual command
    cmd = Command(session)
    cmd.current_text = command
    cmd._find_command_name(no_aliases=True)
    if not cmd._ci:
        raise UserError("Unknown commmand")
    try:
        cmd.run(command)
    except NotABug:
        session.logger.info("Failed as expected")
    else:
        raise UserError("Command failed to fail")
Пример #8
0
def process_command(session, name, structure, substring):
    # all the commands use the trick that the structure arg is temporarily made available in the
    # global namespace as '_structure'
    global _structure, command_registry
    _structure = structure
    try:
        if command_registry is None:
            # register commands to private registry
            from chimerax.core.commands.cli import RegisteredCommandInfo
            command_registry = RegisteredCommandInfo()

            from chimerax.core.commands import Float3Arg, StringArg, BoolArg, \
                Float2Arg, DynamicEnum

            # atom
            register("atom",
                CmdDesc(
                    keyword=[("position", Float3Arg), ("res_name", StringArg),
                        ("select", BoolArg)],
                    synopsis="place helium atom"
                ), shim_place_atom, registry=command_registry)

            # peptide
            from chimerax.core.commands import Annotation
            class RepeatableFloat2Arg(Annotation):
                allow_repeat = True
                parse = Float2Arg.parse
                unparse = Float2Arg.unparse

            register("peptide",
                CmdDesc(
                    required=[("sequence", StringArg), ("phi_psis", RepeatableFloat2Arg)],
                    keyword=[("position", Float3Arg), ("chain_id", StringArg),
                        ("rot_lib", DynamicEnum(session.rotamers.library_names))],
                    synopsis="construct peptide from sequence"
                ), shim_place_peptide, registry=command_registry)

        cmd = Command(session, registry=command_registry)
        return cmd.run(name + ' ' + substring, log=False)[0]
    finally:
        _structure = None
Пример #9
0
def run(session, cmd_text):
    from chimerax.core.commands import Command
    cmd = Command(session)
    cmd.run(cmd_text)
Пример #10
0
def cmd_open(session, file_names, rest_of_line, *, log=True):
    tokens = []
    remainder = rest_of_line
    while remainder:
        token, token_log, remainder = next_token(remainder)
        remainder = remainder.lstrip()
        tokens.append(token)
    provider_cmd_text = "open " + " ".join([FileNameArg.unparse(fn)
        for fn in file_names] + [StringArg.unparse(token) for token in tokens])
    try:
        database_name = format_name = None
        for i in range(len(tokens)-2, -1, -2):
            test_token = tokens[i].lower()
            if "format".startswith(test_token):
                format_name = tokens[i+1]
            elif "fromdatabase".startswith(test_token):
                database_name = tokens[i+1]

        from .manager import NoOpenerError
        mgr = session.open_command
        fetches, files = fetches_vs_files(mgr, file_names, format_name, database_name)
        if fetches:
            try:
                provider_args = mgr.fetch_args(fetches[0][1], format_name=fetches[0][2])
            except NoOpenerError as e:
                raise LimitationError(str(e))
        else:
            data_format = file_format(session, files[0], format_name)
            if data_format is None:
                # let provider_open raise the error, which will show the command
                provider_args = {}
            else:
                try:
                    provider_args = mgr.open_args(data_format)
                except NoOpenerError as e:
                    raise LimitationError(str(e))

        # register a private 'open' command that handles the provider's keywords
        registry = RegisteredCommandInfo()

        def database_names(mgr=mgr):
            return mgr.database_names

        keywords = {
            'format': DynamicEnum(lambda ses=session:format_names(ses)),
            'from_database': DynamicEnum(database_names),
            'ignore_cache': BoolArg,
            'name': StringArg
        }
        for keyword, annotation in provider_args.items():
            if keyword in keywords:
                raise ValueError("Open-provider keyword '%s' conflicts with builtin arg of"
                    " same name" % keyword)
            keywords[keyword] = annotation
        desc = CmdDesc(required=[('names', OpenFileNamesArg)], keyword=keywords.items(),
            synopsis="read and display data")
        register("open", desc, provider_open, registry=registry)
    except BaseException as e:
        # want to log command even for keyboard interrupts
        log_command(session, "open", provider_cmd_text, url=_main_open_CmdDesc.url)
        raise
    return Command(session, registry=registry).run(provider_cmd_text, log=log)