def interact(workspace=None, banner=None, exitmsg=None, completer='standard'): if workspace is None: frame = sys._getframe(1) globs = frame.f_globals locs = frame.f_locals workspace = globs workspace.update(locs) try: import readline if completer == 'standard': from rlcompleter import Completer readline.set_completer(Completer(workspace).complete) elif completer == 'key': from .completer import Completer readline.set_completer_delims(' \t\n\\`@$><=;|&{(') readline.set_completer(Completer(workspace).complete) else: raise AttributeError(f'Invalid completer {completer}') readline.parse_and_bind('tab:complete') except: print('Could not start auto complete!') shell = code.InteractiveConsole(workspace) shell.interact(banner=banner, exitmsg=exitmsg)
def handle_TAB(self): necessarypart = "".join(self.lineBuffer).split(' ')[-1] completer = Completer(globals()) if completer.complete(necessarypart, 0): matches = list(set(completer.matches)) # has multiples if len(matches) == 1: length = len(necessarypart) self.lineBuffer = self.lineBuffer[:-length] self.lineBuffer.extend(matches[0]) self.lineBufferIndex = len(self.lineBuffer) else: matches.sort() commons = self.find_common(matches) if commons: length = len(necessarypart) self.lineBuffer = self.lineBuffer[:-length] self.lineBuffer.extend(commons) self.lineBufferIndex = len(self.lineBuffer) self.terminal.nextLine() while matches: matches, part = matches[4:], matches[:4] for item in part: self.terminal.write('%s' % item.ljust(30)) self.terminal.write('\n') self.terminal.nextLine() self.terminal.eraseLine() self.terminal.cursorBackward(self.lineBufferIndex + 5) self.terminal.write("%s %s" % (self.ps[self.pn], "".join(self.lineBuffer)))
def loop(editor): try: editor.stop_async_io() global name_space if name_space is None: print('\tuse :eval in a python source file to use its name_space.') name_space = {} else: print() print('\tBuffer correctly evaluated.') print() console = Console(locals=name_space) #, editor=editor) try: with local_completer: readline.set_completer(Completer(name_space).complete) console.interact() except SystemExit: pass name_space = None #console.save_history() return 'normal' finally: editor.start_async_io()
def __init__(self, tabcomplete=True, spaces=True, tabwidth=2, font=defaultFont(), bgcolor=Qt.black, textcolor=Qt.white, startup="", silentStartup=False, parent=None, *, catchstd=False, closeAction): super(QPlainTextEdit, self).__init__(parent) self.setLineWrapMode(QPlainTextEdit.NoWrap) self.setWindowTitle(self._tr("pyTSon Console")) self.tabcomplete = tabcomplete self.spaces = spaces self.tabwidth = tabwidth self.setFont(font) self.setContextMenuPolicy(Qt.PreventContextMenu) p = self.palette p.setColor(QPalette.Base, bgcolor) p.setColor(QPalette.Text, textcolor) self.palette = p self.history = [] self.curhistory = -1 self.lastinp = "" self.locked = False self.globals = {} self.inmulti = False self.multi = "" self.incmd = False self.comp = Completer(self.globals) self.selformat = self.currentCharFormat() self.selformat.setBackground(Qt.white) self.selformat.setForeground(Qt.black) self.norformat = self.currentCharFormat() self.closeAction = closeAction # we have to make sure, that this runs in the same context as # commands run from the console self.clearlocals = list(eval("dir()", self.globals)) self.connect("destroyed()", self._resetdir) if catchstd: self.redirector = StdRedirector(self.appendLine) self.stdout = sys.stdout sys.stdout = self.redirector self.connect("destroyed()", self._resetStdout) else: self.redirector = None if os.path.isfile(startup): with open(startup, "r") as f: self.runCommand(f.read(), silentStartup) self.writePrompt(self.plainText != "")
def keyPressEvent(self, event): qt = QtCore.Qt if event.key() == qt.Key_Tab: line = str(self.document().lastBlock().text())[4:] completer = Completer(self.interpreter.locals) suggestion = completer.complete(line, 0) if suggestion is not None: self.insertPlainText(suggestion[len(line):]) return None if event.key() == qt.Key_Down: if self.historyIndex == len(self.history): self.historyIndex -= 1 try: if self.historyIndex > -1: self.historyIndex -= 1 self.recallHistory() else: self.clearCurrentBlock() except Exception: pass return None if event.key() == qt.Key_Up: try: if len(self.history) - 1 > self.historyIndex: self.historyIndex += 1 self.recallHistory() else: self.historyIndex = len(self.history) except Exception: pass return None if event.key() == qt.Key_Home: # set cursor to position 4 in current block. 4 because that's where # the marker stops blockLength = len(self.document().lastBlock().text()[4:]) lineLength = len(self.document().toPlainText()) position = lineLength - blockLength textCursor = self.textCursor() textCursor.setPosition(position) self.setTextCursor(textCursor) return None if event.key() in [qt.Key_Left, qt.Key_Backspace]: # don't allow deletion of marker if self.textCursor().positionInBlock() == 4: return None if event.key() in [qt.Key_Return, qt.Key_Enter]: self.doEnter(event) return None # allow all other key events super(PyInterp, self).keyPressEvent(event)
def initialize_completer(): global ip_completer, p_completer try: __IPYTHON__ from IPython.core.completer import IPCompleter ip = get_ipython() ip_completer = IPCompleter(ip, global_namespace=global_dict) except NameError: try: from rlcompleter import Completer p_completer = Completer(namespace=global_dict) except: pass
def shell(): """ Run an interactive Python shell in the context of a given navycut application. The application will populate the default namespace of this shell according to its configuration. This is useful for executing small snippets of management code without having to manually configure the application. """ import code from flask.globals import _app_ctx_stack _app: t.Type["Navycut"] = _app_ctx_stack.top.app banner = (f"Python {sys.version} on {sys.platform}\n" f"Project: {_app.config.get('PROJECT_NAME')} \n" f"Debug mode: {'on' if _app.debug else 'off'}\n" f"Instance: {_app.instance_path}\n" "(InteractiveConsole)") ctx: dict = dict() # Support the regular Python interpreter startup script if someone # is using it. startup = environ.get("PYTHONSTARTUP") if startup and path.isfile(startup): with open(startup) as f: eval(compile(f.read(), startup, "exec"), ctx) ctx.update(app.make_shell_context()) # Site, customize, or startup script can set a hook to call when # entering interactive mode. The default one sets up readline with # tab and history completion. interactive_hook = getattr(sys, "__interactivehook__", None) if interactive_hook is not None: try: import readline from rlcompleter import Completer except ImportError: pass else: # rlcompleter uses __main__.__dict__ by default, which is # flask.__main__. Use the shell context instead. readline.set_completer(Completer(ctx).complete) interactive_hook() code.interact(banner=banner, local=ctx)
def handle_TAB(self): text = "".join(self.lineBuffer).split(' ')[-1] if len(text) == 0: # Bell character self.terminal.write("\a") return completer = Completer(self.namespace) if completer.complete(text, 0): allMatches = list(set(completer.matches)) # Get rid of a bunch of cruft builtins = __builtin__.keys() matches = [ x for x in allMatches if x.strip('(') not in builtins and "__" not in x ] matches.sort() # If there are no matches, ring the terminal bell # If there's only one match, autocomplete it # If there's more than one match, print a list of matches if len(matches) == 0: self.terminal.write("\a") return elif len(matches) == 1: length = len(text) self.lineBuffer = self.lineBuffer[:-length] self.lineBuffer.extend(matches[0]) self.lineBufferIndex = len(self.lineBuffer) else: # Remove text before the last dot, for brevity if "." in matches[0]: matches = [x[x.rfind(".") + 1:] for x in matches] self.terminal.nextLine() self.terminal.write(repr(matches)) self.terminal.nextLine() self.terminal.write("%s%s" % (self.ps[self.pn], "")) self.terminal.eraseLine() self.terminal.cursorBackward(self.lineBufferIndex + 5) self.terminal.write("%s%s" % (self.ps[self.pn], "".join(self.lineBuffer))) else: self.terminal.write("\a")
def tab_complete(self): try: from rlcompleter import Completer c = Completer(self.namespace) cmd = self.getCommand() if "." in cmd: matches = c.attr_matches(cmd) else: matches = c.global_matches(cmd) if len(matches) == 1: cmd = matches[0] else: self.appendPlainText("\t".join(matches)) self.newPrompt() self.setCommand(cmd) except ImportError, e: log(e)
def __init__(self, workspace=None): self.wsdict = dict() if workspace is None else workspace self.ws = DictStruct(self.wsdict) Shell.instance = self self.wsdict['shell'] = self self.wsdict['gui'] = gui self.wsdict['use'] = use self.wsdict['__name__'] = '__main__' self.redirect_stdout() self.redirect_input() self.comp = Completer(self.wsdict) self.interpreters = dict() self.logdir = LogDir(config['path_log']) self.bootpath = Path('.').resolve()
def dbshell(args): from app.models import User # noqa if args.ipython: try: from IPython import embed embed() except ImportError: print("You need to install IPython") sys.exit(1) else: import readline from rlcompleter import Completer readline.parse_and_bind("tab: complete") import code variables = globals().copy() variables.update(locals()) readline.set_completer(Completer(variables).complete) shell = code.InteractiveConsole(variables) shell.interact()
def main(args): if args.filter: pkt_filter = ' '.join(args.filter) else: pkt_filter = None pkts = sniff(iface=args.iface, filter=pkt_filter, count=args.count, prn=pkt_callback) if args.interact: vars = globals() vars.update(locals()) set_completer(Completer(vars).complete) parse_and_bind("tab: complete") InteractiveConsole(vars).interact()
def getSuggestions(self, line): from rlcompleter import Completer def _inRange(i): if MAX_COMPLETIONS <= 0: # No limit return True else: return i <= MAX_COMPLETIONS result = [] completer = Completer(self.globals) i = 0 suggestion = True while suggestion and _inRange(i): suggestion = completer.complete(line, i) if suggestion: if i == MAX_COMPLETIONS and MAX_COMPLETIONS != 0: result.append('...') else: if suggestion not in result: result.append(suggestion) i += 1 return result
def keyboard_on_key_down(self, window, keycode, text, modifiers): '''Override of _keyboard_on_key_down. ''' if keycode[0] == 9 and Completer: # tab, add autocomplete suggestion txt = self.text[self._cursor_pos:] if txt.strip(): suggestion = Completer(self.sh.locals).complete(txt, 0) if suggestion: self.select_text(self._cursor_pos, self._cursor_pos + len(txt)) self.delete_selection() Clock.schedule_once(partial(self.insert_text, suggestion)) return False elif keycode[0] == 13: # For enter self.last_line = self.text[self._cursor_pos:] self.dispatch('on_ready_to_input') return super(InteractiveShellInput, self).keyboard_on_key_down(window, keycode, text, modifiers)
def init_completer(selfi, locals): completer = Completer(locals) readline.set_completer(completer.complete) readline.parse_and_bind("tab: complete")
sys.path.insert(0, '/home/vsharma/temp/audio/build/lib.linux-x86_64-3.5') #Python2 #sys.path.insert(0,'/home/vsharma/temp/audio/build/lib.linux-x86_64-2.7') # For audio preprocessing import numpy as np from scipy.io import wavfile from scipy.signal import resample import librosa import torchaudio import readline from rlcompleter import Completer readline.parse_and_bind("tab: complete") readline.set_completer(Completer(locals()).complete) ############## # # Example : CUDA_VISIBLE_DEVICES=2 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=0 --end_movie_num=1 # krenew -b -- screen -Dm -fn # screen -r # cd /home/vsharma/Documents/Audio_Visual_Text # source ~/.bashrc # CUDA_VISIBLE_DEVICES=0 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=0 --end_movie_num=25 # CUDA_VISIBLE_DEVICES=0 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=25 --end_movie_num=50 # CUDA_VISIBLE_DEVICES=1 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=50 --end_movie_num=75 # CUDA_VISIBLE_DEVICES=1 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=75 --end_movie_num=100 # CUDA_VISIBLE_DEVICES=2 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=100 --end_movie_num=125 # CUDA_VISIBLE_DEVICES=2 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=125 --end_movie_num=150 # CUDA_VISIBLE_DEVICES=3 python3.5 Audio_Visual_Place_Temporal.py --start_movie_num=150 --end_movie_num=175
def __init__(self, local_ctx): self.completer = Completer(local_ctx)
def load_and_run_shell() -> None: """Launch a shell for a thrift service.""" sys.path.append(os.getcwd()) parser = argparse.ArgumentParser( description="Open a shell for a Thrift service with app configuration loaded.", formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "--debug", action="store_true", default=False, help="enable extra-verbose debug logging" ) parser.add_argument( "--app-name", default="main", metavar="NAME", help="name of app to load from config_file (default: main)", ) parser.add_argument( "config_file", type=argparse.FileType("r"), help="path to a configuration file" ) args = parser.parse_args(sys.argv[1:]) with args.config_file: config = read_config(args.config_file, server_name=None, app_name=args.app_name) logging.basicConfig(level=logging.INFO) env: Dict[str, Any] = {} env_banner = { "app": "This project's app instance", "context": "The context for this shell instance's span", } app = make_app(config.app) env["app"] = app baseplate: Baseplate = app.baseplate # type: ignore context = baseplate.make_context_object() span = baseplate.make_server_span(context, "shell") env["context"] = span.context if config.shell and "setup" in config.shell: setup = _load_factory(config.shell["setup"]) setup(env, env_banner) configure_logging(config, args.debug) # generate banner text banner = "Available Objects:\n" for var in sorted(env_banner.keys()): banner += f"\n {var:<12} {env_banner[var]}" console_logpath = _get_shell_log_path() try: # try to use IPython if possible from IPython import start_ipython try: # IPython 5.x+ from traitlets.config.loader import Config except ImportError: # IPython 4 and below from IPython import Config ipython_config = Config() ipython_config.InteractiveShellApp.exec_lines = [ # monkeypatch IPython's log-write() to enable formatted input logging, copying original code: # https://github.com/ipython/ipython/blob/a54bf00feb5182fa821bd5457897b3b30a313436/IPython/core/logger.py#L187-L201 f""" ip = get_ipython() from functools import partial def log_write(self, data, kind="input", message_id="IEXC"): import datetime, os if self.log_active and data: write = self.logfile.write if kind=='input': # Generate an RFC 5424 compliant syslog format write(f'<13>1 {{datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")}} {{os.uname().nodename}} baseplate-shell {{os.getpid()}} {{message_id}} - {{data}}') elif kind=='output' and self.log_output: odata = u'\\n'.join([u'#[Out]# %s' % s for s in data.splitlines()]) write(u'%s\\n' % odata) self.logfile.flush() ip.logger.logstop = None ip.logger.log_write = partial(log_write, ip.logger) ip.magic('logstart {console_logpath} append') ip.logger.log_write(data="Start IPython logging\\n", message_id="ISTR") """ ] ipython_config.TerminalInteractiveShell.banner2 = banner ipython_config.LoggingMagics.quiet = True start_ipython(argv=[], user_ns=env, config=ipython_config) raise SystemExit except ImportError: pass newbanner = f"Baseplate Interactive Shell\nPython {sys.version}\n\n" banner = newbanner + banner try: import readline readline.set_completer(Completer(env).complete) readline.parse_and_bind("tab: complete") except ImportError: pass shell = LoggedInteractiveConsole(_locals=env, logpath=console_logpath) shell.interact(banner)
def keyPressEvent(self, event): qt = QtCore.Qt if event.key() == qt.Key_Tab: line = str(self.document().lastBlock().text())[4:] completer = Completer(self.interpreter.locals) suggestion = completer.complete(line, 0) if suggestion is not None: self.insertPlainText(suggestion[len(line):]) return None if event.key() == qt.Key_Down: if self.historyIndex == len(self.history): self.historyIndex -= 1 try: if self.historyIndex > -1: self.historyIndex -= 1 self.recallHistory() else: self.clearCurrentBlock() except: pass return None if event.key() == qt.Key_Up: try: if len(self.history) - 1 > self.historyIndex: self.historyIndex += 1 self.recallHistory() else: self.historyIndex = len(self.history) except: pass return None if event.key() == qt.Key_Home: # set cursor to position 4 in current block. 4 because that's where # the marker stops blockLength = len(self.document().lastBlock().text()[4:]) lineLength = len(self.document().toPlainText()) position = lineLength - blockLength textCursor = self.textCursor() textCursor.setPosition(position) self.setTextCursor(textCursor) return None if event.key() in [qt.Key_Left, qt.Key_Backspace]: # don't allow deletion of marker if self.textCursor().positionInBlock() == 4: return None if event.key() in [qt.Key_Return, qt.Key_Enter]: # set cursor to end of line to avoid line splitting textCursor = self.textCursor() position = len(self.document().toPlainText()) textCursor.setPosition(position) self.setTextCursor(textCursor) line = str(self.document().lastBlock().text())[4:] # remove marker line.rstrip() self.historyIndex = -1 if self.customCommands(line): return None else: try: # pylint: disable=pointless-statement line[-1] self.haveLine = True if line[-1] == ':': self.multiLine = True self.history.insert(0, line) except: self.haveLine = False if self.haveLine and self.multiLine: # multi line command self.command += line + '\n' # + command and line self.append('') # move down one line self.marker() # handle marker style return None if self.haveLine and not self.multiLine: # one line command self.command = line # line is the command self.append('') # move down one line self.interpreter.runIt(self.command) self.command = '' # clear command self.marker() # handle marker style return None if self.multiLine and not self.haveLine: # multi line done self.append('') # move down one line self.interpreter.runIt(self.command) self.command = '' # clear command self.multiLine = False # back to single line self.marker() # handle marker style return None if not self.haveLine and not self.multiLine: # just enter self.append('') self.marker() return None return None # allow all other key events super(PyInterp, self).keyPressEvent(event)
def __init__(self, tabcomplete=True, spaces=True, tabwidth=2, font=defaultFont(), bgcolor=Qt.black, textcolor=Qt.white, width=800, height=600, startup="", silentStartup=False, parent=None, *, catchstd=False): super(QPlainTextEdit, self).__init__(parent) self.setLineWrapMode(QPlainTextEdit.NoWrap) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(self._tr("pyTSon Console")) self.tabcomplete = tabcomplete self.spaces = spaces self.tabwidth = tabwidth self.setFont(font) self.resize(width, height) self.setContextMenuPolicy(Qt.PreventContextMenu) p = self.palette p.setColor(QPalette.Base, bgcolor) p.setColor(QPalette.Text, textcolor) self.palette = p self.history = [] self.curhistory = -1 self.lastinp = "" self.locked = False self.globals = {} self.inmulti = False self.multi = "" self.incmd = False self.comp = Completer(self.globals) self.selformat = self.currentCharFormat() self.selformat.setBackground(Qt.white) self.selformat.setForeground(Qt.black) self.norformat = self.currentCharFormat() if catchstd: self.redirector = StdRedirector(self.appendLine) self.stdout = sys.stdout sys.stdout = self.redirector self.connect("destroyed()", self._resetStdout) else: self.redirector = None if os.path.isfile(startup): with open(startup, "r") as f: self.runCommand(f.read(), silentStartup) self.writePrompt(self.plainText != "")
def __init__(self, locals: Dict[str, object], banner=banner): Gtk.ScrolledWindow.__init__(self) self.locals = locals locals["help"] = Help() self.set_min_content_width(640) self.set_min_content_height(480) self.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.text = Gtk.TextView() self.text.set_wrap_mode(True) self.text.set_monospace(True) self.text.set_border_width(4) self.interpreter = code.InteractiveInterpreter(locals) self.completer = Completer(locals) self.buffer: List[str] = [] self.history: List[str] = [] self.banner = banner self.ps1 = ">>> " self.ps2 = "... " self.text.add_events(Gdk.EventMask.KEY_PRESS_MASK) self.text.connect("key_press_event", self.key_pressed) self.current_history = -1 self.mark = self.text.get_buffer().create_mark( "End", self.text.get_buffer().get_end_iter(), False ) # setup colors self.style_banner = Gtk.TextTag.new("banner") self.style_banner.set_property("foreground", "saddle brown") self.style_ps1 = Gtk.TextTag.new("ps1") self.style_ps1.set_property("foreground", "DarkOrchid4") self.style_ps1.set_property("editable", False) self.style_ps2 = Gtk.TextTag.new("ps2") self.style_ps2.set_property("foreground", "DarkOliveGreen") self.style_ps2.set_property("editable", False) self.style_out = Gtk.TextTag.new("stdout") self.style_out.set_property("foreground", "midnight blue") self.style_out.set_property("editable", False) self.style_err = Gtk.TextTag.new("stderr") self.style_err.set_property("style", Pango.Style.ITALIC) self.style_err.set_property("foreground", "red") self.style_err.set_property("editable", False) self.text.get_buffer().get_tag_table().add(self.style_banner) self.text.get_buffer().get_tag_table().add(self.style_ps1) self.text.get_buffer().get_tag_table().add(self.style_ps2) self.text.get_buffer().get_tag_table().add(self.style_out) self.text.get_buffer().get_tag_table().add(self.style_err) self.stdout = TextViewWriter("stdout", self.text, self.style_out) self.stderr = TextViewWriter("stderr", self.text, self.style_err) self.current_prompt = lambda: "" self.add(self.text) self.text.show() self.write_line(self.banner, self.style_banner) self.prompt_ps1()
def _make_completer(self): l = {} l.update(builtins.__dict__) l.update(locals()) l.update(self._locals) self._completer = Completer(l)