Exemple #1
0
def enableAutoComplete(matchList):
    """ Enables tab-autocomplete functionality in user input.

        Parameters:
            matchList(list<str>): List of strings that can be matched to.
    """
    readline.parse_and_bind("tab: complete")
    readline.set_completer_delims("")

    def complete(text, state):
        """ Credit Chris Siebenmann: https://bit.ly/2E0pNDB"""
        # generate candidate completion list
        if text == "":
            matches = matchList
        else:
            matches = [
                x for x in matchList if x.lower().startswith(text.lower())
            ]

        # return current completion match
        if state > len(matches):
            return None
        else:
            return matches[state]

    readline.set_completer(complete)
Exemple #2
0
    def init_completer(self):
        try:
            import rlcompleter
            readline.parse_and_bind("tab: complete")

            readline.set_completer_delims("")

            readline.write_history_file(os.path.join(dxpy.config.get_user_conf_dir(), '.dx_history'))
            readline.clear_history()
            readline.set_completer()
        except:
            pass
Exemple #3
0
    def preloop(self):
        delims = set(readline.get_completer_delims())
        for d in "%*-/":
            try:
                delims.remove(d)
            except KeyError:
                pass
        readline.set_completer_delims(''.join(delims))

        try:
            readline.read_history_file(self.HISTORY_FILE)
        except (OSError, IOError) as e:
            warn("Can't read history file")
Exemple #4
0
 def cmdloop(self, line=None):
     """Handle interactive and non-interactive input"""
     if line:
         # non-interactive (file or command)
         self.use_rawinput = False
         line = self.precmd(line)
         stop = self.onecmd(line)
         stop = self.postcmd(stop, line)
     else:
         # interactive
         self.interactive = True
         try:
             readline.set_completer_delims(self.DELIMS)
         except (AttributeError, NameError):
             # platforms that do not support readline (Windows)
             pass
         self.set_prompt()
         cmd.Cmd.cmdloop(self)
Exemple #5
0
    def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
Exemple #6
0
    def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
Exemple #7
0
    ret.append(None)
    last_clist = ret
    return last_clist[state]


# some python distributions don't have readline, so handle that case
# with a try/except
try:
    if platform.system() == 'Darwin':
        import gnureadline as readline
    else:
        try:
            import readline
        except ImportError:
            import pyreadline as readline
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
    redisplay = readline.redisplay
except Exception:
    pass

if __name__ == "__main__":
    from mp_settings import MPSettings, MPSetting

    class mystate(object):
        def __init__(self):
            self.settings = MPSettings([
                MPSetting('foo',
                          int,
                          1,
Exemple #8
0
 def init_readline(self):
     readline.parse_and_bind('tab: complete')
     readline.set_completer(complete)
     readline.set_completer_delims(' \t')
     self.init_history_file()
     readline.read_history_file(self.history)
Exemple #9
0
    "Python": python,
    "bash": bash
}

completer_state = {
    "available": False
}

try:
    try:
        import gnureadline as readline
    except ImportError:
        import readline
    import rlcompleter
    readline.parse_and_bind("tab: complete")
    readline.set_completer_delims("")
    completer_state['available'] = True
except ImportError:
    print('NOTE: readline module not available.  Install for tab-completion.')

class Completer():
    def __init__(self, choices):
        self.matches = None
        self.choices = choices

    def complete(self, text, state):
        if state == 0:
            self.matches = filter(lambda choice: choice.startswith(text),
                                  self.choices)

        if self.matches is not None and state < len(self.matches):
Exemple #10
0
def input_with_prefill(prompt, text):
    def hook():
        readline.insert_text(text)
        readline.redisplay()

    readline.set_pre_input_hook(hook)
    try:
        result = input(prompt)
    except:
        result = ''
    readline.set_pre_input_hook()
    return result


readline.set_completer_delims('')

if 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")

os.chdir(DMSdirectory + 'Documents')

for (dirpath, dirnames, filenames) in os.walk(DMSdirectory + 'inbox'):
    for name in filenames:
        filename_old = os.path.join(dirpath, name)
        if name.endswith(".pdf"):
            print('Processing: ' + filename_old)

            subprocess.call([
Exemple #11
0
    last_clist = ret
    return last_clist[state]



# some python distributions don't have readline, so handle that case
# with a try/except
try:
    if platform.system() == 'Darwin':
        import gnureadline as readline
    else:
        try:
            import readline
        except ImportError:
            import pyreadline as readline
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
    redisplay = readline.redisplay
except Exception:
    pass


if __name__ == "__main__":
    from mp_settings import MPSettings, MPSetting

    class mystate(object):
        def __init__(self):
            self.settings = MPSettings(
            [ MPSetting('foo', int, 1, 'foo int', tab='Link', range=(0,4), increment=1),
              MPSetting('bar', float, 4, 'bar float', range=(-1,20), increment=1)])
    def __init__(
        self, command: str, rebuild: bool, config_path: str, nix: bool = False, settings_path: str = SETTINGS_PATH
    ):
        self._command = command
        self._rebuild: bool = rebuild
        self._nix: bool = nix  # Not currently supported
        self._config_path: str = config_path
        self._settings_path: str = settings_path

        assert command in RUNNER_COMMANDS

        # Some state flags/vars used by eg the UI/event loop
        self._primary_attached_app: Optional[Dict] = None
        self._shutdown: threading.Event = threading.Event()
        self._awaiting_input: bool = False
        self._suppress_log_printing: bool = False
        self._filter_logs: Sequence[str] = []
        self._use_docker_services: bool = False
        self._processes: dict = {}
        self._dmservices = None
        self._main_log_name = "manager"
        self.config: Dict = {}

        # Temporarily ignore SIGINT while setting up multiprocessing components.
        # START
        curr_signal = signal.getsignal(signal.SIGINT)
        signal.signal(signal.SIGINT, signal.SIG_IGN)

        self._manager = multiprocessing.Manager()
        self._apps: Dict[str, Dict[str, Any]] = self._manager.dict()

        signal.signal(signal.SIGINT, curr_signal)  # Probably a race condition?
        # END

        with open(self._settings_path) as settings_file:
            self.settings: dict = yaml.safe_load(settings_file.read())

        # load environment variables from settings file,
        # taking care not to override existing envvars
        if self.settings.get("environment"):
            for key, value in self.settings["environment"].items():
                if key not in os.environ:
                    self.logger(f"setting environment variable {key}")
                    os.environ[key] = str(value)

        self._main_log_name = "setup"
        # Handles initialization of external state required to run this correctly (repos, docker images, config, etc).
        exitcode, self._use_docker_services, self.config = setup_and_check_requirements(
            logger=self.logger,
            config=self.config,
            config_path=self._config_path,
            settings=self.settings,
            command=self._command,
        )

        if exitcode or self._command != RUNNER_COMMAND_RUN:
            self.shutdown()
            sys.exit(exitcode)

        self._inject_credentials()

        self._main_log_name = "manager"

        self._populate_multiprocessing_components()

        # Setup tab completion for app names.
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self._app_name_completer)
        readline.set_completer_delims(" ")
Exemple #13
0
from collections import defaultdict
from termcolor import colored as term_colored
from xclib.conductor import Conductor
from xclib.conductor.models import Datacenter, Project, Host, Group
import sys, fcntl, termios, struct, os, cmd, re
reload(sys)
sys.setdefaultencoding("utf8")

try:
    import gnureadline as readline
except ImportError:
    import readline

sys.modules["readline"] = readline
readline.parse_and_bind("tab: complete")
readline.set_completer_delims(readline.get_completer_delims().replace(":", ""))


def terminal_size():
    h, w, hp, wp = struct.unpack(
        'HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0)))
    return w, h


def colored(*args, **kwargs):
    if "sym_ignore" in kwargs:
        sym_ignore = kwargs["sym_ignore"]
        del (kwargs["sym_ignore"])
    else:
        sym_ignore = False
Exemple #14
0
def console():
    # Configuring the commpleter
    comp = Completer(['load', 'set', 'show', 'run', 'back', 'warriors', 'quit', 'help'])
    gnureadline.set_completer_delims(' \t\n;')
    gnureadline.parse_and_bind("tab: complete")
    gnureadline.set_completer(comp.complete)

    print (banners.get_banner())
    cprint(' [+]', 'yellow', end='')
    print (' Starting the console...')
    cprint(' [*]', 'green', end='')
    print (' Console ready!\n')

    session = None

    while True:
        if session is None:
            # With termcolor not work colors
            # user_input = input(
            #     colored('iBombShell> ', 'green', attrs=['bold'])).split()

            # /* Definitions available for use by readline clients. */
            # define RL_PROMPT_START_IGNORE  '\001'
            # define RL_PROMPT_END_IGNORE    '\002'
            user_input = input('\001\033[1;32m\002iBombShell> \001\033[0m\002').split()
        else:
            # user_input = input(
            #     "iBombShell["
            #     + colored(session.header(), 'green', attrs=['bold'])
            #     + "]> ").split()

            user_input = input('iBombShell[' +
                               '\001\033[1;32m\002' +
                               session.header() +
                               '\001\033[0m\002' +
                               ']> ').split()

        if user_input == []:
            continue

        elif user_input[0] in CLEAR_COMMANDS:
            os.system('cls' if os.name=='nt' else 'clear')

        elif user_input[0] == 'back':
            session = None

        elif user_input[0] == 'warriors':
            i = 0
            for p in Path("/tmp/").glob("ibs-*"):
                i += 1
                cprint(str(p)[9:], 'yellow')
            
            if i == 0:
                cprint('[!] Warriors haven\'t been found...', 'red')

        elif user_input[0] in END_COMMANDS:
            cprint('[+] Killing warriors...', 'green')
            for p in Path("/tmp/").glob("ibs-*"):
                p.unlink()
            cprint('[+] Exit...', 'green')
            os._exit(-1)

        elif user_input[0] == 'load':
            if (len(user_input) == 1):
                cprint('[!] Please, load a module', 'red')
                continue
            session = Session(user_input[1])

            # The module is incorrect
            if not(session.correct_module()):
                cprint('[!] Invalid module', 'red')
                session = None

        elif user_input[0] == 'show':
            if session is None:
                cprint('[!] Please, load a module', 'red')
                continue
            session.show()

        elif user_input[0] == 'set':
            if session is None:
                cprint('[!] Please, load a module', 'red')
                continue
            else:
                value = ' '.join([str(x) for x in user_input[2:]])
                session.set(user_input[1], value)

        elif user_input[0] == 'run':
            if session is None:
                cprint('[!] Please, load a module', 'red')
                continue
            session.run()

        else:
            cprint('[!] Command not found', 'red')