Python prompt_toolkit.prompt() Examples

The following are 30 code examples of prompt_toolkit.prompt(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit , or try the search function .
Example #1
Source File: repository.py    From margaritashotgun with MIT License 7 votes vote down vote up
def prompt_for_install(self):
        """
        Prompt user to install untrusted repo signing key
        """
        print(self.key_info)
        repo_key_url = "{0}/{1}".format(self.url, self.repo_signing_key)
        print(("warning: Repository key untrusted \n"
               "Importing GPG key 0x{0}:\n"
               "  Userid: \"{1}\"\n"
               "  From  : {2}".format(self.key_info['fingerprint'],
                                      self.key_info['uids'][0],
                                      repo_key_url)))
        response = prompt(u'Is this ok: [y/N] ')
        if response == 'y':
            self.install_key(self.raw_key)
            return True
        else:
            return False 
Example #2
Source File: __main__.py    From bibmanager with MIT License 7 votes vote down vote up
def cli_ads_search(args):
    """Command-line interface for ads-search call."""
    if args.next:
        query = None
    else:
        completer = u.KeyWordCompleter(u.ads_keywords, bm.load())
        session = prompt_toolkit.PromptSession(
            history=FileHistory(u.BM_HISTORY_ADS()))
        query = session.prompt(
            "(Press 'tab' for autocomplete)\n",
            auto_suggest=u.AutoSuggestCompleter(),
            completer=completer,
            complete_while_typing=False,
            ).strip()
        if query == "" and os.path.exists(u.BM_CACHE()):
            query = None
        elif query == "":
            return
    try:
        am.manager(query)
    except ValueError as e:
        print(f"\nError: {str(e)}") 
Example #3
Source File: job_controller.py    From rvt_model_services with MIT License 6 votes vote down vote up
def run_db_job_by_id(preset=None):
    """
    runs a job from database by id
    """
    if preset:
        job_id = preset
    else:
        print("  please enter job_id to run")
        job_id = prompt("> run_job_by_db_id> ", **sub_prompt_options)
    if job_id:
        job_id = int(job_id)
        job = rms_db.get(doc_id=job_id)
        if job:
            # print(job)
            cmd_tokens = serdes(job=job)
            # print(cmd_tokens)
            cmd_str = " ".join(cmd_tokens)
            if check_model_path(job_id):
                print("cmd_str:", cmd_str)
                subprocess.Popen(cmd_str)
    else:
        print("  no job with this id found") 
Example #4
Source File: job_controller.py    From rvt_model_services with MIT License 6 votes vote down vote up
def remove_db_job_by_id(preset=None):
    """
    removes rms job from db by id
    """
    if preset:
        job_id = preset
    else:
        print("  please enter job_id to run")
        job_id = prompt("> run_job_by_db_id> ", **sub_prompt_options)
    job_id = int(job_id)
    job = rms_db.get(doc_id=job_id)
    if job:
        list_jobs(by_id=job_id)
        cmd_str = serdes(job=job)
        print(colorful.cyan("  got removed from db"))
        job = rms_db.remove(doc_ids=[job_id])
    else:
        print("  no job with this id found") 
Example #5
Source File: gtd.py    From gtd.py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def review(ctx, tags, no_tags, match, listname, attachments, has_due, status):
    '''show a smart, command-line based menu for each card selected.
    This menu will prompt you to add tags to untagged cards, to attach the title
    of cards which have a link in the title, and gives you all the other functionality combined.
    '''
    cards = CardView.create(
        ctx,
        status=status,
        tags=tags,
        no_tags=no_tags,
        title_regex=match,
        list_regex=listname,
        has_attachments=attachments,
        has_due_date=has_due,
    )
    ctx.display.banner()
    card = cards.current()
    while card is not None:
        if ctx.card_repl(card):
            card = cards.next()
        else:
            card = cards.prev() 
Example #6
Source File: git_backdorizer.py    From GitBackdorizer with GNU General Public License v3.0 6 votes vote down vote up
def set_config(self):
        ip_listening = prompt('Set IP to listening: ')
        port_listening = prompt('Set PORT to listening: ')
        payload_choice = prompt('Choose into insert payload:\n1 - pre-commit\n2 - pre-push\n:> ')
        payload_hook = lambda choice: "pre-commit" if choice == "1" else "pre-push"
        payload = payload_hook(payload_choice)
        payload_content = pl.generate(ip_listening, port_listening, payload)
        filename = self.write_payload(payload_content)
        save_config = prompt('Save configuration? [y] [n]\n:> ')
        if 'y' == save_config.lower():
            output_config = open('conf/conf_payload.conf', 'w')
            output_config.write('{}|{}|{}'.format(ip_listening, port_listening, payload))
            output_config.close()
        elif 'n' == save_config.lower():
            pass
        print('\n[+] File in output/{}'.format(filename))
        listen_response = prompt('Listening backdoor? [y] [n]\n:> ')
        if 'y' == listen_response.lower():
            self.listening(ip_listening, port_listening)
            #pass
        else:
            self.start() 
Example #7
Source File: util.py    From coconut with Apache License 2.0 6 votes vote down vote up
def prompt(self, msg):
        """Get input using prompt_toolkit."""
        try:
            # prompt_toolkit v2
            prompt = prompt_toolkit.PromptSession(history=self.history).prompt
        except AttributeError:
            # prompt_toolkit v1
            prompt = partial(prompt_toolkit.prompt, history=self.history)
        return prompt(
            msg,
            multiline=self.multiline,
            vi_mode=self.vi_mode,
            wrap_lines=self.wrap_lines,
            enable_history_search=self.history_search,
            lexer=PygmentsLexer(CoconutLexer),
            style=style_from_pygments_cls(
                pygments.styles.get_style_by_name(self.style),
            ),
        ) 
Example #8
Source File: git_backdorizer.py    From GitBackdorizer with GNU General Public License v3.0 6 votes vote down vote up
def gen_backdoor(self):
        os.system('clear')
        print(self.gen_menu)
        while 1:
            user_input = prompt(':> ')
            
            if '1' == user_input:
                self.set_config()
                
            elif '2' == user_input:
                self.get_config()
                
            elif 'back' == user_input:
                self.start()
            else:
                os.system('clear')
                print('Chose one option')
                print(self.gen_menu) 
Example #9
Source File: card.py    From gtd.py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def rename(self, default: Optional[str] = None, variables: dict = {}):
        if variables:
            print('You can use the following variables in your new card title:')
            for k, v in variables.items():
                print(f'  ${k}: {v}')
        suggestion = variables.get('title0', None) or self.card_json['name']
        newname = prompt(f'Input new name for this card (blank for "{default or suggestion}"): ').strip()
        if newname:
            for k, v in variables.items():
                expansion = f'${k}'
                if expansion in newname:
                    newname = newname.replace(expansion, v)
            self.set_name(newname)
        else:
            # If there wasn't a default set for the card name, leave the card name unchanged
            result = default or suggestion
            if result != self.card_json['name']:
                self.set_name(result) 
Example #10
Source File: util.py    From coconut with Apache License 2.0 6 votes vote down vote up
def input(self, more=False):
        """Prompt for code input."""
        sys.stdout.flush()
        if more:
            msg = more_prompt
        else:
            msg = main_prompt
        if self.style is not None:
            internal_assert(prompt_toolkit is not None, "without prompt_toolkit cannot highlight style", self.style)
            try:
                return self.prompt(msg)
            except EOFError:
                raise  # issubclass(EOFError, Exception), so we have to do this
            except (Exception, AssertionError):
                logger.display_exc()
                logger.show_sig("Syntax highlighting failed; switching to --style none.")
                self.style = None
        return input(msg) 
Example #11
Source File: interface.py    From hermit with Apache License 2.0 6 votes vote down vote up
def enter_shard_words(self, name: str) -> str:
        print(("\nEnter SLIP39 phrase for shard {} below (CTRL-D to submit):".format(name)))
        lines: List = []
        while True:
            try:
                line = prompt("", completer=self.ShardWordCompleter,
                              **self.options).strip()
            except EOFError:
                break
            # Test against wordlist
            words = line.lower().split()
            if set(words).issubset(ShardWords):
                lines += words
            else:
                for word in words:
                    if word not in ShardWords:
                        print(("{} is not a valid shard word, "
                               + "ignoring last line").format(word))
        shortcuts.clear()
        return ' '.join(lines) 
Example #12
Source File: card.py    From gtd.py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_due_date(self):
        def validate_date(text):
            return re.match(r'\d{2}\/\d{2}\/\d{4}', text) or re.match(r'[A-Z][a-z]{2} \d{2} \d{4}', text)

        validator = Validator.from_callable(
            validate_date,
            error_message='Enter a date in format "Jun 15 2018", "06/15/2018" or "15/06/2018". Ctrl+D to go back',
            move_cursor_to_end=True,
        )
        while True:
            user_input = prompt('gtd.py > duedate > ', validator=validator, validate_while_typing=True)
            result = parse_user_date_input(user_input)
            if result is None:
                print('Invalid date format!')
            else:
                break
        # Set the due daet
        self.connection.trello.fetch_json(
            '/cards/' + self.id + '/due', http_method='PUT', post_args={'value': result.isoformat()}
        )
        # Pick it up
        self.fetch()
        print('Due date set')
        return result 
Example #13
Source File: job_controller.py    From rvt_model_services with MIT License 6 votes vote down vote up
def run_db_job():
    """
    runs a job from database
    """
    print(" please enter: '<project_code>'")
    project_code = prompt("> run_job> ", **sub_prompt_options)
    print(" please enter: '<command>'")
    command = prompt("> run_job> ", **sub_prompt_options)
    print(f"to be run: 'python process_model.py {project_code} {command}'")
    job_id = rms_db.get((Query()["<project_code>"] == project_code) & (Query()["<command>"] == command)).doc_id
    job = rms_db.get(doc_id=job_id)
    if job_id:
        cmd_tokens = serdes(job=job[0])
        cmd_str = " ".join(cmd_tokens)
        if check_model_path(job_id):
            print(cmd_str)
            subprocess.Popen(cmd_str)
    else:
        print("  no job with this id found") 
Example #14
Source File: rprompt.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    # Option 1: pass a string to 'rprompt':
    answer = prompt("> ", rprompt=" <rprompt> ", style=example_style)
    print("You said: %s" % answer)

    # Option 2: pass HTML:
    answer = prompt("> ", rprompt=HTML(" <u>&lt;rprompt&gt;</u> "), style=example_style)
    print("You said: %s" % answer)

    # Option 3: pass ANSI:
    answer = prompt(
        "> ", rprompt=ANSI(" \x1b[4m<rprompt>\x1b[0m "), style=example_style
    )
    print("You said: %s" % answer)

    # Option 4: Pass a callable. (This callable can either return plain text,
    #           an HTML object, an ANSI object or a list of (style, text)
    #           tuples.
    answer = prompt("> ", rprompt=get_rprompt_text, style=example_style)
    print("You said: %s" % answer) 
Example #15
Source File: job_controller.py    From rvt_model_services with MIT License 6 votes vote down vote up
def show_db_job_by_id(preset=None):
    """
    show config details of rms job from db by id
    """
    if not preset:
        print("  please enter job_id to show details")
        job_id = prompt("> show_job_by_db_id> ", **sub_prompt_options)
        job_id = int(job_id)
    else:
        job_id = int(preset)
    job = rms_db.get(doc_id=job_id)
    if job:
        list_jobs(by_id=job_id)
        cmd_str = serdes(job=job)
        print(colorful.cyan("\n  command:"))
        print(cmd_str)
        return
    else:
        print("  no job with this id found") 
Example #16
Source File: interface.py    From hermit with Apache License 2.0 6 votes vote down vote up
def choose_shard(self,
                     shards) -> Optional[str]:

        if len(shards) == 0:
            raise HermitError("Not enough shards to reconstruct secret.")

        shardnames = [shard.name for shard in shards]
        shardnames.sort()

        shardCompleter = WordCompleter(shardnames, sentence=True)

        while True:
            prompt_string = "Choose shard\n(options: {} or <enter> to quit)\n> "
            prompt_msg = prompt_string.format(", ".join(shardnames))
            shard_name = prompt(prompt_msg,
                                completer=shardCompleter,
                                **self.options).strip()

            if shard_name in shardnames:
                return shard_name

            if shard_name == '':
                return None

            print("Shard not found.") 
Example #17
Source File: Genkuki.py    From s-mbf with MIT License 6 votes vote down vote up
def login(self):
	global s
	print("\n[!] checking cookies")
	time.sleep(1)
	s = self.req
	s.cookies = kuki('toket/kue.txt')
	try:
		fil=open('toket/kue.txt')
		fil.close()
	except FileNotFoundError:
		print("[!] cookies not found\n\n[!] please login in your facebook once again")
		email=input('[?] email/username: ')
		pw=prompt('[?] password: ', is_password=True)
		data = {'email':email,'pass':pw}
		res = s.post('https://mbasic.facebook.com/login',data=data).text
		if 'logout.php' in str(res) or 'mbasic_logout_button' in str(res):
			s.cookies.save()
		else:
			exit('[!] fail login into your account')
	if 'True' in cek():
		pass
	else:
		exit() 
Example #18
Source File: Cspam.py    From s-mbf with MIT License 6 votes vote down vote up
def login():
		print("\n[!] checking cookies")
		time.sleep(1)
		s = ses()
		s.cookies = kuki('toket/kue.txt')
		try:
			fil=open('toket/kue.txt')
			fil.close()
		except FileNotFoundError:
			print("[!] cookies not found\n\n[!] please login in your facebook once again")
			email=input('[?] email/username: ')
			pw=prompt('[?] password: ',is_password=True)
			data = {'email':email,'pass':pw}
			url='https://mbasic.facebook.com/login'

			res = s.post(url,data=data).text
			if 'logout.php' in str(res) or 'mbasic_logout_button' in str(res):
				s.cookies.save()
			else:
				exit('[!] fail login into your account') 
Example #19
Source File: interface.py    From hermit with Apache License 2.0 6 votes vote down vote up
def get_change_password(self, name: str) -> Tuple[bytes, bytes]:
        # promt_toolkit's 'is_password' option
        # replaces input with '*' characters
        # while getpass echos nothing.

        print_formatted_text("\nChange password for shard {}".format(name))
        old_password: bytes = prompt(
            "old password> ", is_password=True).strip().encode('ascii')
        new_password = self.confirm_password()

        # Empty string means do not encrypt    
        if len(old_password) == 0:
            old_password = None

        if len(new_password) == 0:
            new_password = None

        return (old_password, new_password) 
Example #20
Source File: ptk.py    From pyq with Apache License 2.0 6 votes vote down vote up
def cmdloop(self, intro=None):
    """A Cmd.cmdloop implementation"""
    style = style_from_pygments(BasicStyle, style_dict)
    self.preloop()
    stop = None
    while not stop:
        line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,
                      get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
                      history=history, style=style, true_color=True,
                      on_exit='return-none', on_abort='return-none',
                      completer=QCompleter())
        if line is None or line.strip() == r'\\':
            raise SystemExit
        else:
            line = self.precmd(line)
            stop = self.onecmd(line)
        stop = self.postcmd(stop, line)
    self.postloop() 
Example #21
Source File: autocorrection.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    # We start with a `KeyBindings` for our extra key bindings.
    bindings = KeyBindings()

    # We add a custom key binding to space.
    @bindings.add(" ")
    def _(event):
        """
        When space is pressed, we check the word before the cursor, and
        autocorrect that.
        """
        b = event.app.current_buffer
        w = b.document.get_word_before_cursor()

        if w is not None:
            if w in corrections:
                b.delete_before_cursor(count=len(w))
                b.insert_text(corrections[w])

        b.insert_text(" ")

    # Read input.
    text = prompt("Say something: ", key_bindings=bindings)
    print("You said: %s" % text) 
Example #22
Source File: patch-stdout.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    # Print a counter every second in another thread.
    running = True

    def thread():
        i = 0
        while running:
            i += 1
            print("i=%i" % i)
            time.sleep(1)

    t = threading.Thread(target=thread)
    t.daemon = True
    t.start()

    # Now read the input. The print statements of the other thread
    # should not disturb anything.
    with patch_stdout():
        result = prompt("Say something: ")
    print("You said: %s" % result)

    # Stop thread.
    running = False 
Example #23
Source File: tasks.py    From DistributedDeepLearning with MIT License 6 votes vote down vote up
def _prompt_sub_id_selection(c):
    # Importing here to avoid overhead to the rest of the application
    from tabulate import tabulate
    from toolz import pipe
    import json
    from prompt_toolkit import prompt

    results = c.run(f"az account list", pty=True, hide="out")
    parsestr = "["+results.stdout[1:-7]+"]" #TODO: Figure why this is necessary
    sub_dict = json.loads(parsestr)
    sub_list = [
        {"Index": i, "Name": sub["name"], "id": sub["id"]}
        for i, sub in enumerate(sub_dict)
    ]
    pipe(sub_list, tabulate, print)
    prompt_result = prompt("Please type in index of subscription you want to use: ")
    sub_id = sub_list[int(prompt_result)]["id"]
    print(f"You selected index {prompt_result} sub id {sub_id}")
    return sub_id 
Example #24
Source File: key_bindings.py    From azure-cli-shell with MIT License 6 votes vote down vote up
def config_settings(event):
    """ opens the configuration """
    global PROMPTING
    telemetry.track_key('F1')

    PROMPTING = True
    config = azclishell.configuration.CONFIGURATION
    answer = ""
    questions = {
        "Do you want command descriptions" : "command_description",
        "Do you want parameter descriptions" : "param_description",
        "Do you want examples" : "examples"
    }
    for question in questions:
        while answer.lower() != 'y' and answer.lower() != 'n':
            answer = prompt(u'\n%s (y/n): ' % question)
        config.set_val('Layout', questions[question], format_response(answer))
        answer = ""

    PROMPTING = False
    print("\nPlease restart shell for changes to take effect.\n\n")
    event.cli.set_return_value(event.cli.current_buffer) 
Example #25
Source File: get-multiline-input.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def prompt_continuation(width, line_number, wrap_count):
    """
    The continuation: display line numbers and '->' before soft wraps.

    Notice that we can return any kind of formatted text from here.

    The prompt continuation doesn't have to be the same width as the prompt
    which is displayed before the first line, but in this example we choose to
    align them. The `width` input that we receive here represents the width of
    the prompt.
    """
    if wrap_count > 0:
        return " " * (width - 3) + "-> "
    else:
        text = ("- %i - " % (line_number + 1)).rjust(width)
        return HTML("<strong>%s</strong>") % text 
Example #26
Source File: colored-prompt.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def example_1():
    """
    Style and list of (style, text) tuples.
    """
    # Not that we can combine class names and inline styles.
    prompt_fragments = [
        ("class:username", "john"),
        ("class:at", "@"),
        ("class:host", "localhost"),
        ("class:colon", ":"),
        ("class:path", "/user/john"),
        ("bg:#00aa00 #ffffff", "#"),
        ("", " "),
    ]

    answer = prompt(prompt_fragments, style=style)
    print("You said: %s" % answer) 
Example #27
Source File: get-password-with-toggle-display-shortcut.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    hidden = [True]  # Nonlocal
    bindings = KeyBindings()

    @bindings.add("c-t")
    def _(event):
        " When ControlT has been pressed, toggle visibility. "
        hidden[0] = not hidden[0]

    print("Type Control-T to toggle password visible.")
    password = prompt(
        "Password: ", is_password=Condition(lambda: hidden[0]), key_bindings=bindings
    )
    print("You said: %s" % password) 
Example #28
Source File: interactive.py    From st2 with Apache License 2.0 5 votes vote down vote up
def read(self):
        message = self.template.format(self.prefix + self.name, **self.spec)
        response = prompt(message, **self.options)

        result = self.spec.get('default', None)

        if response:
            result = self._transform_response(response)

        return result 
Example #29
Source File: fancy-zsh-prompt.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main() -> None:
    while True:
        answer = prompt(get_prompt, style=style, refresh_interval=1)
        print("You said: %s" % answer) 
Example #30
Source File: autocomplete-with-control-space.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    text = prompt(
        "Give some animals: ",
        completer=animal_completer,
        complete_while_typing=False,
        key_bindings=kb,
    )
    print("You said: %s" % text)