Esempio n. 1
0
def main():
    args = sys.argv[1:]
    if "-h" in args or "--help" in args:
        print(USAGE, end="")
        return

    if "--version" in args:
        print(__version__)
        return

    debug = True
    try:
        args.pop(args.index("--debug"))
    except ValueError:
        debug = False

    if args:
        print(USAGE, file=sys.stderr, end="")
        sys.exit(1)

    cli = DiscordCli(debug=debug)
    readline.set_auto_history(True)
    history_path = os.path.join(os.path.expanduser("~"), ".harmony_history")

    try:
        readline.read_history_file(history_path)
    except FileNotFoundError:
        pass

    try:
        cli.command_loop()
    finally:
        readline.write_history_file(history_path)
        get_config().save()
Esempio n. 2
0
    def __init__(self, list_files):
        self.start = time.time()
        self.list = []
        self.passes = 0
        self.fails = 0
        self.list_files = list_files

        # We obviously do not want history in this program
        readline.set_auto_history(False)

        for list_file in list_files:
            try:
                with open(list_file) as word_list_file:
                    for line in word_list_file:
                        if not line.strip():  # Do not add emtpy lines
                            pass
                        # Lines starting with a '#' are comments
                        elif line[0] == "#":
                            pass
                        else:
                            self.list.append(Item(line))
            except FileNotFoundError:
                print(f"Error: {list_file}, no such file or directory")
                sys.exit()
            except IsADirectoryError:
                print(f"Error: {list_file}, is a directory")
                sys.exit()
            random.shuffle(self.list)

        self.orig_len = len(self.list)
Esempio n. 3
0
def readline_disabled():
  """Context manager to temporarily disable readline features.
  """
  readline.set_auto_history(False)
  try:
    yield
  finally:
    readline.set_auto_history(True)
Esempio n. 4
0
    def preloop(self):
        enable_mac_auto_complete()

        try:
            readline.read_history_file(self.history_file)
        except IOError:
            pass
        readline.set_auto_history(False)
Esempio n. 5
0
def set_readline(
):  # a set of functions from the readline to complete command line text
    import readline
    readline.set_auto_history(True)
    readline.set_completer(completion)

    if "libedit" in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")
Esempio n. 6
0
def set_readline():
    import readline

    readline.set_auto_history(True)
    readline.set_completer(completion)

    if 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")
Esempio n. 7
0
def interactive_prompt(
		token: str,
		*,
		verbose: bool = False,
		colour: ColourTrilean = True,
		org: bool = True,
		) -> None:
	"""
	Start an interactive session.

	:param token: The token to authenticate with the GitHub API.
	:param verbose: Whether to show information on the GitHub API rate limit.
	:param colour: Whether to use coloured output.
	:param org: Indicates the repository belongs to the organisation configured as
		'username' in repo_helper.yml.
	"""

	click.echo("repo_helper_github interactive prompt.")
	click.echo(f"Version {repo_helper_github.__version__}")
	click.echo(f"Type 'help' for help or 'quit' to exit.")

	readline.set_history_length(-1)
	readline.set_auto_history(True)

	parser = InteractiveParser()
	manager = GitHubManager(token, PathPlus.cwd(), verbose=verbose, colour=colour)

	# This will catch a missing --org option error earlier
	manager.get_org_or_user(org)

	readline.parse_and_bind("tab: complete")
	readline.set_completer(parser.complete)
	HISTORY_FILE.read()

	HISTORY_FILE.get_history_items()

	try:
		while True:
			for command in prompt('>', prompt_suffix=' ').split("&&"):
				command = command.lower().strip()

				command, args = parse_command(command)
				if command is not None:
					try:
						getattr(manager, command)(*args, org=org)
					except Exception:
						click.echo(traceback.format_exc())

	except (KeyboardInterrupt, EOFError, click.Abort):
		click.echo("\nExiting...")
		sys.exit(0)
	finally:
		HISTORY_FILE.write()
Esempio n. 8
0
    def launch_history(self):
        readline.set_auto_history(False)

        using_history = self.local_storage.get("history")
        if using_history:
            readline.set_auto_history(True)
            self.enable_history_file()

        readline.set_completer(self.completer.completer)
        readline.set_completer_delims(" \t\n;")

        readline.parse_and_bind("tab: complete")
Esempio n. 9
0
def main():
    readline.set_auto_history(True)
    readline.set_completer(completion)
    wiz_help()

    try:
        while True:
            task = input("> ")
            task = task.strip().lower()
            request(task)
    except (KeyboardInterrupt, EOFError):
        bye()
Esempio n. 10
0
    def _init_rline(self):
        log.d("Init GNU readline")

        # [GNU] readline config
        rl_load()

        # TAB: autocomplete
        readline.parse_and_bind("tab: complete")
        # readline.parse_and_bind("set show-all-if-ambiguous on")
        # readline.parse_and_bind("set show-all-if-unmodified on")
        # readline.parse_and_bind("set menu-complete-display-prefix on")
        # readline.parse_and_bind("tab: complete")

        # Show 'show all possibilities' if there are too many items
        readline.parse_and_bind("set completion-query-items 50")
        readline.parse_and_bind("set completion-ignore-case on")
        readline.parse_and_bind("set echo-control-characters off")

        # Remove '-' from the delimiters for handle suggestions
        # starting with '-' properly and '/' for handle paths
        # `~!@#$%^&*()-=+[{]}\|;:'",<>/?
        # readline.set_completer_delims(multireplace(readline.get_completer_delims(),
        #                                      [("-", ""), ("/", "")]))

        # Completion function
        readline.set_completer(self._next_suggestion)

        # Use only a space as word breaker
        readline.set_completer_delims(" ")

        # Use a custom render function; this has been necessary for print
        # colors while using rline for the suggestions engine
        if has_gnureadline():
            readline.set_completion_display_matches_hook(
                self._display_suggestions_gnureadline)
        elif has_pyreadline():
            readline.rl.mode._display_completions = self._display_suggestions_pyreadline

        # Set quote characters for quoting strings with spaces
        rl_set_completer_quote_characters('"')

        rl_set_char_is_quoted_p(self._quote_detector)

        # History
        try:
            readline.set_auto_history(False)
            self._load_history()
        except:
            log.w("History not supported")
            pass
Esempio n. 11
0
 def wrap_history(self):
     '''Loads history at startup and saves history on exit.'''
     readline.set_auto_history(False)
     try:
         if self.history_file:
             readline.read_history_file(self.history_file)
         h_len = readline.get_current_history_length()
     except FileNotFoundError:
         h_len = 0
     try:
         yield
     finally:
         new_items = readline.get_current_history_length() - h_len
         if new_items > 0 and self.history_file:
             open(self.history_file, 'a').close()
             readline.append_history_file(new_items, self.history_file)
Esempio n. 12
0
def main():
    readline.set_auto_history(True)
    readline.set_completer(completion)
    readline.parse_and_bind("tab: complete")

    while True:
        try:
            request = input("> ")
            if request == "quit":
                print("Goodbye!")
                break
        except (EOFError, KeyboardInterrupt):
            print("\nGoodbye!")
            break

        task(request)
Esempio n. 13
0
    def __init__(self, prompt: str = '> ') -> None:
        """
		Creates a new Terminal. If prompt is given the given prompt
		will be used.
		"""
        self.prompt = prompt
        self.running = False
        try:
            self._format_help()
        except KeyError:
            pass

        readline.parse_and_bind('tab: complete')
        readline.set_completer(_make_completer(self._get_commands_name()))
        readline.set_auto_history(True)
        _read_history()
Esempio n. 14
0
def run_prompt(prompt, headerless=False):
    # Our KSL is global like the _Interpreter instance
    autoCmp = assemble_acmp(KSL)

    if not headerless:
        print(header, end="\n")

    _readline.set_completer(autoCmp.completer)
    _readline.parse_and_bind("tab: complete")

    # Load repl history file
    try:
        _readline.read_history_file('.rocket_repl_history')

    except FileNotFoundError:
        # Just leave it till user finishes session to create the file
        pass

    _readline.set_auto_history('enabled')

    while True:

        try:
            chunk = input(prompt)
        except EOFError:
            save_and_quit()

        except KeyboardInterrupt:
            silent_quit()

        if chunk == "exit":
            _readline.write_history_file('.rocket_repl_history')
            _sys.exit(0)

        elif chunk == "":
            pass

        else:
            # Allow user to SIGINT (^C) a running chunk of code and still be in the REPL
            try:
                run(chunk,
                    "REPL")  # replace with actual shell interpreter (REPL)

            except KeyboardInterrupt:
                pass

        UpdateAuto(autoCmp)
Esempio n. 15
0
def ask_user_input(prompt=''):
    """
    Ask user input (without being put into readline history).

    Parameters
    ----------
    prompt : str
        Prompt passed to input() function.
    """

    if config.system == 'windows':
        user_input = input(prompt)
    else:
        try:
            readline.set_auto_history(False)
            user_input = input(prompt)
        finally:
            readline.set_auto_history(True)
    return user_input
Esempio n. 16
0
 def start(self):
     self.load_history()
     while True:
         try:
             remote = self._peer.connections[self.connected()[1]]
             self.cmdloop(
                 f'Peer: {self._peer.name} '
                 f'({hashlib.sha1(self._peer.key.publickey().export_key("DER")).hexdigest().upper()})\n'
                 f'Remote peer: {remote.name} '
                 f'({hashlib.sha1(remote.key.export_key("DER")).hexdigest().upper()})'
             )
             break
         except KeyboardInterrupt:
             readline.set_auto_history(False)
             prompt = input(f'\nYou really want to exit? (y/n): ').lower()
             if prompt == 'y':
                 break
             else:
                 readline.set_auto_history(True)
Esempio n. 17
0
def main():
    if len(sys.argv) != 2:
        print("USAGE: {} <url>".format(sys.argv[0]))
        sys.exit(1)

    url = sys.argv[1]
    if url[:8].lower() != "mysql://":
        url = "mysql://" + url

    readline.set_auto_history(False)

    mysql_task = wf.create_mysql_task(url, retry_max, mysql_callback)

    first_sql = "show databases;"
    req = mysql_task.get_req()
    req.set_query(first_sql)
    readline.add_history(first_sql)

    series = wf.create_series_work(mysql_task, None)
    series.set_context(url)
    series.start()
    wf.wait_finish()
Esempio n. 18
0
def main():
    """Main executing function.

    Args:   none

    Modifies:
        adv:    through the called functions

    Returns:    nothing
    """
    # adventure-elements in a named tuple, access like adv.rooms or adv.player
    # this adventure namedtuple will be passed around by functions allowing access to all game data
    adv = setup(*get_jsons())
    if not all(adv):
        sys.exit("Something went wrong, unable to start the game.")

    # create references to handler functions
    adv.player["commands"] = {
        command: eval(command)
        for command in adv.commands
    }

    # setup readline history
    readline.set_history_length(HISTORY_BUFFER)
    readline.clear_history()
    readline.set_auto_history(True)

    # main game loop
    while check(adv.player["status"],
                "playing",
                "alive",
                "nowinner",
                logic=all):
        room_description(adv)
        items_listing(adv)
        adv.rooms[adv.player["location"]]["status"].add("visited")
        player_input(adv)
        predefined_events(adv)
Esempio n. 19
0
start_time = time.clock()

file_messages = []

for file in options["files"]:
    print("Loading file %s" % file)
    for msg in lib.messages.parse_message_file("src/pi/msgs/" + file + ".txt"):
        file_messages.append(msg)

if len(file_messages) > 0:
    conn.send_batched(file_messages)

if options["read"] == "true":
    print("Enter 'q' to quit")

    readline.set_auto_history(True)

    def complete(options, begin, text, state):
        values = []

        for s in options:
            if (s.startswith(text)):
                values.append(s)

        if state < len(values):
            return begin + values[state]

    def completer(text, state):
        if text.find(" ") == -1:
            return complete(lib.messages.opcodes.keys(), "", text, state)
Esempio n. 20
0
import os

import sentence_mixing.sentence_mixer as sm
from sentence_mixing.logic.display import combo_displayer
from sentence_mixing.model.exceptions import PhonemError, TokenAmbiguityError
from sentence_mixing.serialize import load, save
from sentence_mixing.video_creator.audio import concat_wav

# Allows command history
try:
    READLINE_IMPORTED = True
    import readline
    readline.set_auto_history(False)
except:
    # If python have been compiled without readline
    READLINE_IMPORTED = False

AUDIO_FILE_PATH = "out.wav"


def clear_screen():
    os.system("cls" if os.name == "nt" else "clear")


def get_sentence(text):
    if text is not None:
        print("Previous sentences:\n", text)
    sentence = input("Enter a sentence: ")

    if READLINE_IMPORTED:
        readline.add_history(sentence)
Esempio n. 21
0
def __input_history(input_history):
    if input_history and os.name != "nt":
            readline.set_auto_history(True)
Esempio n. 22
0
def __input_history(input_history):
    if input_history:
        readline.set_auto_history(True)
Esempio n. 23
0
 def postcmd(self, line):
     readline.set_auto_history(False)
     return self.should_exit