コード例 #1
0
ファイル: ipython.py プロジェクト: martinpmsmith/ptpython
def create_completer(
    get_globals,
    get_locals,
    magics_manager,
    alias_manager,
    get_enable_dictionary_completion,
):
    g = create_ipython_grammar()

    return GrammarCompleter(
        g,
        {
            "python":
            PythonCompleter(get_globals, get_locals,
                            get_enable_dictionary_completion),
            "magic":
            MagicsCompleter(magics_manager),
            "alias_name":
            AliasCompleter(alias_manager),
            "pdb_arg":
            WordCompleter(["on", "off"], ignore_case=True),
            "autocall_arg":
            WordCompleter(["0", "1", "2"], ignore_case=True),
            "py_filename":
            PathCompleter(only_directories=False,
                          file_filter=lambda name: name.endswith(".py")),
            "filename":
            PathCompleter(only_directories=False),
            "directory":
            PathCompleter(only_directories=True),
            "system":
            SystemCompleter(),
        },
    )
コード例 #2
0
def create_completer(get_globals, get_locals, magics_manager, alias_manager):
    g = create_ipython_grammar()

    return GrammarCompleter(
        g, {
            'python':
            PythonCompleter(get_globals, get_locals),
            'magic':
            MagicsCompleter(magics_manager),
            'alias_name':
            AliasCompleter(alias_manager),
            'pdb_arg':
            WordCompleter(['on', 'off'], ignore_case=True),
            'autocall_arg':
            WordCompleter(['0', '1', '2'], ignore_case=True),
            'py_filename':
            PathCompleter(only_directories=False,
                          file_filter=lambda name: name.endswith('.py')),
            'filename':
            PathCompleter(only_directories=False),
            'directory':
            PathCompleter(only_directories=True),
            'system':
            SystemCompleter(),
        })
コード例 #3
0
def prompt_bash(msg: str, allow_empty: bool) -> str:
    """
    Prompts for bash shell code.

    :param msg: shown message
    :param allow_empty: allow an empty string?
    :return: user input
    """
    from pygments.lexers.shell import BashLexer
    validator = None if allow_empty else NonEmptyValidator()
    return prompt(msg, lexer=PygmentsLexer(BashLexer), completer=SystemCompleter())
コード例 #4
0
ファイル: __init__.py プロジェクト: unix0000/chitin
def shell():
    c = Chitin()

    cmd_history = FileHistory(os.path.expanduser('~') + '/.chitin.history')
    print(WELCOME)
    message = VERSION

    def get_bottom_toolbar_tokens(cli):
        return [(Token.Toolbar, ' ' + message)]

    style = style_from_dict({
        Token.Toolbar: '#ffffff bg:#333333',
    })
    completer = SystemCompleter()
    del completer.completers["executable"]

    # Check whether files in and around the current directory have been changed...
    for failed in util.check_integrity_set(set(".")):
        print("[WARN] '%s' has been modified outside of lab book." % failed)
    try:
        while True:
            cmd_str = ""
            while len(cmd_str.strip()) == 0:
                cmd_str = prompt(
                    u'===> ',
                    history=cmd_history,
                    auto_suggest=AutoSuggestFromHistory(),
                    completer=completer,
                    lexer=PygmentsLexer(BashLexer),
                    get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
                    style=style,
                    on_abort=AbortAction.RETRY,
                )

            fields = cmd_str.split(" ")
            command_set = [" ".join(fields)]

            skip, special_command_set = c.attempt_special(cmd_str)
            if skip:
                continue
            if len(special_command_set) > 0:
                command_set = special_command_set

            #####################################
            handled = c.super_handle(command_set)
            if handled:
                if "message" in handled:
                    message = handled["message"]
                else:
                    message = VERSION
            #####################################

    except EOFError:
        print("Bye!")
コード例 #5
0
ファイル: completer.py プロジェクト: ywangd/peek
from peek.config import config_location
from peek.es_api_spec.spec import ApiSpec
from peek.lexers import PeekLexer, UrlPathLexer, PathPart, ParamName, Ampersand, QuestionMark, Slash, HttpMethod, \
    FuncName, ShellOut, DictKey, EOF
from peek.parser import PeekParser, ParserEvent, ParserEventType

_logger = logging.getLogger(__name__)

_HTTP_METHOD_COMPLETER = WordCompleter([m.upper() for m in HTTP_METHODS],
                                       ignore_case=True)

_ES_API_CALL_OPTION_NAME_COMPLETER = WordCompleter(
    [w + '=' for w in sorted(['conn', 'runas', 'headers', 'xoid', 'quiet'])])

_PATH_COMPLETER = PathCompleter(expanduser=True)
_SYSTEM_COMPLETER = SystemCompleter()

_DICT_EVENT_TYPES = (
    ParserEventType.DICT_KEY,
    ParserEventType.BEFORE_DICT_KEY_EXPR,
    ParserEventType.AFTER_DICT_KEY_EXPR,
    ParserEventType.BEFORE_DICT_VALUE,
    ParserEventType.AFTER_DICT_VALUE,
)


class ParserStateTracker:
    def __init__(self, text: str):
        self.text = text
        self._events: List[ParserEvent] = []
        self._tokens: List[PeekToken] = []
コード例 #6
0
def prompt_exec_driver_dict(choose_revision: bool, working_dir: str = None) -> dict:
    """
    Prompt for the contents of run config dict for suitable for the exec run driver.

    :param choose_revision: can the user choose a specific vcs revision?
    :param working_dir: default working dir for the exec driver
    """
    from pygments.lexers.shell import BashLexer
    old_cwd = os.path.realpath(".")
    working_dir = working_dir or prompt_dir("Working directory: ")
    run_dict = {}
    run_dict["cwd"] = working_dir
    os.chdir(working_dir)
    run_dict["run_cmd"] = prompt_bash("Command to execute the program: ", allow_empty=False)

    if prompt_yesno("Set some environment variables? ", default=False):
        env_dict = {}
        def set_env_var():
            name = prompt("Environment variable name: ", validator=NonEmptyValidator(),
                          completer=WordCompleter(sorted(list(env_dict.keys())), meta_dict=env_dict))
            default = env_dict[name] if name in env_dict else ""
            env_dict[name] = prompt("New value: ", default=default)
        try:
            set_env_var()
            while prompt_yesno("Set another environment variable? "):
                set_env_var()
        except KeyboardInterrupt:
            pass
        run_dict["env"] = env_dict

    if choose_revision:
        vcs = VCSDriver.get_suited_vcs()
        if vcs.number_of_revisions() + int(vcs.has_uncommitted()) > 1:
            run_dict["revision"] = default_prompt("Choose a revision in the current repository: ", default="HEAD",
                                    completer=create_revision_completer(vcs),
                                    validator=RevisionValidator(vcs),
                                    display_completions_in_columns=True)
            if is_builtin_type(int, run_dict["revision"]):
                run_dict["revision"] = int(run_dict["revision"])

    if prompt_yesno("Run some commands before that actually benchmarked command? ", default=False):
        print("The commands are entered via a multiline input. ")
        print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.")
        print("You can click with the mouse in order to select text.")
        run_dict["cmd_prefix"] = prompt('', multiline=True, mouse_support=True, lexer=PygmentsLexer(BashLexer),
                        completer=SystemCompleter())

    runners = {
        "perf_stat": {
            "func": prompt_perf_stat_exec_dict,
            "description": PerfStatExecRunner.__description__,
        },
        "rusage": {
            "func": prompt_rusage_exec_dict,
            "description": RusageExecRunner.__description__,
        },
        "spec": {
            "func": prompt_spec_exec_dict,
            "description": SpecExecRunner.__description__
        },
        "time": {
            "func": prompt_time_exec_dict,
            "description": TimeExecRunner.__description__
        }
    }

    valid = sorted(list(runners.keys()))
    meta_dict = {}
    for driver in runners:
        meta_dict[driver] = runners[driver]["description"]
    driver = prompt("Used runner: ", completer=WordCompleter(words=valid, ignore_case=True,
                                                                 meta_dict=meta_dict),
                    validator=WordValidator(ignore_case=False, valid_words=valid, error_msg="Invalid runner"),
                    display_completions_in_columns=True)
    run_dict["runner"] = driver
    run_dict[driver] = runners[driver]["func"](run_dict)
    os.chdir(old_cwd)
    return run_dict
コード例 #7
0
from __future__ import unicode_literals
from prompt_toolkit import prompt
# 导入历史模块类,实现查找历史的功能
from prompt_toolkit.history import FileHistory
# 实现用户输入时候自动提示
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
# tab自动补全提示命令,旧版的WordCompleter不可用了
from prompt_toolkit.contrib.completers import SystemCompleter


SQLCompleter = SystemCompleter()


while True:
    user_input = prompt('>', history=FileHistory('history.txt'),
                        auto_suggest=AutoSuggestFromHistory(),
                        completer=SQLCompleter, )
    print(user_input)