我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用code.interact()。
def interactive(self): utils.set_prompt(ps1="(rudra) ", ps2="... ") import os import readline import rlcompleter import atexit histfile = os.path.join(os.environ["HOME"], ".rudrahistory") if os.path.isfile(histfile): readline.read_history_file(histfile) atexit.register(readline.write_history_file, histfile) r = self print "Use the \"r\" object to analyze files" vars = globals() vars.update(locals()) readline.set_completer(rlcompleter.Completer(vars).complete) readline.parse_and_bind("tab: complete") del os, histfile, readline, rlcompleter, atexit code.interact(banner="", local=vars)
def do_python(self,arg): """ start the local python interpreter (for debugging purposes) """ orig_exit=builtins.exit orig_quit=builtins.quit def disabled_exit(*args, **kwargs): self.display_warning("exit() disabled ! use ctrl+D to exit the python shell") builtins.exit=disabled_exit builtins.quit=disabled_exit oldcompleter=readline.get_completer() try: local_ns={"pupsrv":self.pupsrv} readline.set_completer(PythonCompleter(local_ns=local_ns).complete) readline.parse_and_bind('tab: complete') code.interact(local=local_ns) except Exception as e: self.display_error(str(e)) finally: readline.set_completer(oldcompleter) readline.parse_and_bind('tab: complete') builtins.exit=orig_exit builtins.quit=orig_quit
def handle(self, **options): print('... starting jawaf shell ...') waf = Jawaf(settings.PROJECT_NAME) # Use IPython if it exists try: import IPython IPython.embed() return except ImportError: pass # Use bypython if it exists try: import bpython bpython.embed() return except ImportError: pass # Ok, just do the pumpkin spice python shell. import code code.interact(local=locals())
def shell(env): """Runs a dummy generator.""" import code banner = 'Python %s on %s\nEnvironment: %s' % ( sys.version, sys.platform, env, ) ctx = {} # Support the regular Python interpreter startup script if someone # is using it. startup = os.environ.get('PYTHONSTARTUP') if startup and os.path.isfile(startup): with open(startup, 'r') as f: eval(compile(f.read(), startup, 'exec'), ctx) ctx['env'] = env code.interact(banner=banner, local=ctx)
def main(): parser = argparse.ArgumentParser() parser.add_argument('--package', action='append') parser.add_argument('--dir', action='append') parser.add_argument('-m', action='store', metavar='MODULE') args, rest = parser.parse_known_args() if args.package: PACKAGES.extend(args.package) if args.dir: DIRS.extend(os.path.abspath(d) for d in args.dir) if not PACKAGES and not DIRS: DIRS.append(os.getcwd()) if args.m: sys.argv[1:] = rest runpy.run_module(args.m, run_name='__main__', alter_sys=True) elif rest: sys.argv = rest converted = maybe_2to3(rest[0]) with open(converted) as f: new_globals = dict(__name__='__main__', __file__=rest[0]) exec(f.read(), new_globals) else: import code code.interact()
def interact(pid=0, server=None, trace=None): """ Just a cute and dirty way to get a tracer attached to a pid and get a python interpreter instance out of it. """ global remote remote = server if trace is None: trace = getTrace() if pid: trace.attach(pid) mylocals = {"trace": trace} code.interact(local=mylocals)
def do_python(self, line): """ Start an interactive python interpreter. The namespace of the interpreter is updated with expression niceties. You may also specify a line of python code as an argument to be exec'd without beginning an interactive python interpreter on the controlling terminal. Usage: python [pycode] """ locals = self.getExpressionLocals() if len(line) != 0: cobj = compile(line, 'cli_input', 'exec') exec(cobj, locals) else: code.interact(local=locals)
def start_console(self): # Set up initial console environment console_env = { 'ad': self._ad, 'pprint': pprint.pprint, } # Start the services self._start_services(console_env) # Start the console console_banner = self._get_banner(self._ad.serial) code.interact(banner=console_banner, local=console_env) # Tear everything down self._ad.stop_services()
def _spawn_python_shell(self, arg): import winappdbg banner = ('Python %s on %s\nType "help", "copyright", ' '"credits" or "license" for more information.\n') platform = winappdbg.version.lower() platform = 'WinAppDbg %s' % platform banner = banner % (sys.version, platform) local = {} local.update(__builtins__) local.update({ '__name__' : '__console__', '__doc__' : None, 'exit' : self._python_exit, 'self' : self, 'arg' : arg, 'winappdbg' : winappdbg, }) try: code.interact(banner=banner, local=local) except SystemExit: # We need to catch it so it doesn't kill our program. pass
def fit(self, X, y, alpha=1): '''??,?????P(xi|y=k), p(y=k) Args: X: ????, m * n y: ??, n * 1 lambda: ???? ''' y = np.array(y) feature_nums = len(X[0]) sample_nums = len(X) classes_nums = len(self.classes) self.prob_matrix = {} self.prob_classes = {} for k in self.classes: # code.interact(local=locals()) sample_nums_k = len(y[y == k]) # ??p(y) self.prob_classes[k] = (sample_nums_k + alpha) / (sample_nums + classes_nums * alpha) # ??p(x|y) self.prob_matrix[k] = (np.sum(X[y == k, :], axis=0) + alpha) / (sample_nums_k * feature_nums + feature_nums * alpha) return self
def str_to_float( r ): try: r = r.strip().replace(',', '').replace('%','').strip() except: r = 'None' try: #try directly converting f = float(r) return f except ValueError: try: #try brackets eg: (4500)==> -4500 f = -float(str(r).translate(None,"(),")) # code.interact( local=locals() ) return f except: return 0.0 # Million returns 1; Thousand returns 0.001; Billion returns 1000;
def load_preprocess(self, filename): print("Loading preprocessed data...") if filename.endswith("gz"): handle = gzip.open else: handle = open with handle(filename, "rb") as f: stored = pickle.load(f) stored_preprocesser, self._train, self._dev, self._verified_dev = stored if stored_preprocesser.get_config() != self.preprocesser.get_config(): # print("WARNING") import code code.interact(local=locals()) raise ValueError() print("done")
def run_console(): locals = {'self': c, 'do': do} try: from IPython.terminal import embed except ImportError: import code interact = lambda: code.interact(local=locals) else: from IPython.core import magic @magic.magics_class class AsyncMagics(magic.Magics): @magic.line_magic def await(self, line): return do(eval(line, self.shell.user_global_ns, self.shell.user_ns)) shell = embed.InteractiveShellEmbed(user_ns=locals) shell.register_magics(AsyncMagics) interact = shell
def check_forever(checkers): global reload_conf_pending, interrupted, open_backdoor schedule_checks(checkers) logger.info("Starting infinite loop") while not reload_conf_pending: if interrupted: break if open_backdoor: open_backdoor = False code.interact( banner="Kibitzr debug shell", local=locals(), ) schedule.run_pending() if interrupted: break time.sleep(1)
def _run(): global _run _run = lambda: None msg = """ =================================================== Welcome to Face++ Interactive Shell! Here, you can explore and play with Face++ APIs :) --------------------------------------------------- Getting Started: 0. Register a user and API key on https://cloud.megvii.com/ 1. Write your API key/secret in apikey.cfg 2. Start this interactive shell and try various APIs For example, to find all faces in a local image file, just type: api.detect(image_file = File(r'<path to the image file>')) Enjoy! """ try: from IPython import embed embed(banner2 = msg) except ImportError: import code code.interact(msg, local = globals())
def main(): kb = Keyboard() if appex.is_widget(): appex.set_widget_view(kb.root) else: kb.root.present("sheet") def read(self, size=-1): return kb.read(size) def readline(self): return kb.read() sys.stdin.__class__.read = read sys.stdin.__class__.readline = readline code.interact()
def encode(en_sentences, cn_sentences, en_dict, cn_dict, sort_by_len=True): ''' Encode the sequences. ''' length = len(en_sentences) out_en_sentences = [] out_cn_sentences = [] for i in range(length): # code.interact(local=locals()) en_seq = [en_dict[w] if w in en_dict else 0 for w in en_sentences[i]] cn_seq = [cn_dict[w] if w in cn_dict else 0 for w in cn_sentences[i]] out_en_sentences.append(en_seq) out_cn_sentences.append(cn_seq) # sort sentences by english lengths def len_argsort(seq): return sorted(range(len(seq)), key=lambda x: len(seq[x])) if sort_by_len: sorted_index = len_argsort(out_en_sentences) out_en_sentences = [out_en_sentences[i] for i in sorted_index] out_cn_sentences = [out_cn_sentences[i] for i in sorted_index] return out_en_sentences, out_cn_sentences
def NativePythonSupport(user_session): """Launch the rekall session using the native python interpreter. Returns: False if we failed to use IPython. True if the session was run and exited. """ # If the ipython shell is not available, we can use the native python shell. import code # Try to enable tab completion try: import rlcompleter, readline # pylint: disable=unused-variable readline.parse_and_bind("tab: complete") except ImportError: pass # Prepare the session for running within the native python interpreter. user_session.PrepareLocalNamespace() code.interact(banner=constants.BANNER, local=user_session.locals)
def run(self, no_ipython, no_bpython): """ Runs the shell. If no_bpython is False or use_bpython is True, then a BPython shell is run (if installed). Else, if no_ipython is False or use_python is True then a IPython shell is run (if installed). """ context = self.get_context() if not no_bpython: # Try BPython try: from bpython import embed embed(banner=self.banner, locals_=context) return except ImportError: pass if not no_ipython: # Try IPython try: try: # 0.10.x from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(banner=self.banner) ipshell(global_ns=dict(), local_ns=context) except ImportError: # 0.12+ from IPython import embed embed(banner1=self.banner, user_ns=context) return except ImportError: pass # Use basic python shell code.interact(self.banner, local=context)
def remote_test(f): with ClusterRpcProxy(get_yml(f), timeout=3) as s: try: from IPython import embed embed() except: scope = dict(s=s) import code code.interact(None, None, scope)
def shell_command(): """Runs an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to it's configuration. This is useful for executing small snippets of management code without having to manually configuring the application. """ import code from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % ( sys.version, sys.platform, app.import_name, app.debug and ' [debug]' or '', app.instance_path, ) ctx = {} # Support the regular Python interpreter startup script if someone # is using it. startup = os.environ.get('PYTHONSTARTUP') if startup and os.path.isfile(startup): with open(startup, 'r') as f: eval(compile(f.read(), startup, 'exec'), ctx) ctx.update(app.make_shell_context()) code.interact(banner=banner, local=ctx)
def main(): opts = command_line() print('Connecting...') client = create_client_from_config(opts) print('Connected.') banner = '\nIMAPClient instance is "c"' def ipython_011(c): from IPython.frontend.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed(banner1=banner) ipshell('') def ipython_010(c): from IPython.Shell import IPShellEmbed IPShellEmbed('', banner=banner)() def builtin(c): import code code.interact(banner, local=dict(c=c)) for shell_attempt in (ipython_011, ipython_010, builtin): try: shell_attempt(client) break except ImportError: pass
def run_plain(imported_objects): import code code.interact(local=imported_objects)
def handle(self, **options): try: if options['plain']: # Don't bother loading IPython, because the user wants plain Python. raise ImportError self.run_shell(shell=options['interface']) except ImportError: import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. imported_objects = {} try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'): if not pythonrc: continue pythonrc = os.path.expanduser(pythonrc) if not os.path.isfile(pythonrc): continue try: with open(pythonrc) as handle: exec(compile(handle.read(), pythonrc, 'exec'), imported_objects) except NameError: pass code.interact(local=imported_objects)
def python(self, options): import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. imported_objects = {} try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) # Enable tab completion on systems using libedit (e.g. Mac OSX). # These lines are copied from Lib/site.py on Python 3.4. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'): if not pythonrc: continue pythonrc = os.path.expanduser(pythonrc) if not os.path.isfile(pythonrc): continue try: with open(pythonrc) as handle: exec(compile(handle.read(), pythonrc, 'exec'), imported_objects) except NameError: pass code.interact(local=imported_objects)
def run(self, shell=None): """Runs a Python interactive interpreter.""" if not shell: shell = 'bpython' if shell == 'bpython': try: import bpython bpython.embed() except ImportError: shell = 'ipython' if shell == 'ipython': try: from IPython import embed embed() except ImportError: # Ipython < 0.11 try: import IPython # Explicitly pass an empty list as arguments, because # otherwise IPython would use sys.argv from this script. shell = IPython.Shell.IPShell(argv=[]) shell.mainloop() except ImportError: # no IPython module shell = 'python' if shell == 'python': import code try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', # because we already know 'readline' was imported successfully. import rlcompleter # noqa readline.parse_and_bind("tab:complete") code.interact()
def run_command(args): from drift.appmodule import app import code code.interact(local=locals())
def do_python(self, line): """Open a full python shell if "python" was typed in the command line. From here, you can look at and manipulate any variables in the application. This can be used to look at this instance's "self.app" variable which contains the game object. Usage: python """ print("Available variables:") print("self.pp.pprint(self.__dict__)") self.pp.pprint(self.__dict__) code.interact(local=locals())
def python(self, options): import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. imported_objects = {} try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) # Enable tab completion on systems using libedit (e.g. macOS). # These lines are copied from Lib/site.py on Python 3.4. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options['no_startup']: for pythonrc in OrderedSet([os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')]): if not pythonrc: continue if not os.path.isfile(pythonrc): continue try: with open(pythonrc) as handle: exec(compile(handle.read(), pythonrc, 'exec'), imported_objects) except NameError: pass code.interact(local=imported_objects)
def interact(conn): """remote interactive interpreter :param conn: the RPyC connection :param namespace: the namespace to use (a ``dict``) """ with redirected_stdio(conn): conn.execute("""def _rinteract(): def new_exit(): print "use ctrl+D to exit the interactive python interpreter." import code code.interact(local = dict({"exit":new_exit, "quit":new_exit}))""") conn.namespace["_rinteract"]()
def __init__(self, path): @bottle.route(path) def interact(): backup_stdin = os.dup(sys.stdin.fileno()) os.dup2(sys.stdout.fileno(), sys.stdin.fileno()) code.interact(local=globals(), banner=u'Ctrl + D to detach.') os.dup2(backup_stdin, sys.stdin.fileno()) return ''
def main(): params, pipes, _ = command.configure() def run_shell(): shell_vars = { 'p': ParamsProxy(params), 'm': MeterProxy(pipes), } code.interact(banner=BANNER, local=shell_vars) deferred = threads.deferToThread(run_shell) deferred.addCallback(lambda result: reactor.stop()) reactor.run()
def do_interact(self, arg): """ interact Start an interative interpreter whose global namespace contains all the names found in the current scope. """ ns = self.curframe.f_globals.copy() ns.update(self.curframe.f_locals) code.interact("*interactive*", local=ns)
def __call__(self, twitter, options): upload = Twitter( auth=twitter.auth, domain="upload.twitter.com") printNicely( "\nUse the 'twitter' object to interact with" " the Twitter REST API.\n" "Use twitter_upload to interact with " "upload.twitter.com\n\n") code.interact(local={ "twitter": twitter, "t": twitter, "twitter_upload": upload, "u": upload })
def interact(locals=None, plain=False): with RestoredStandardInputContext(): code.interact(local=locals or inspect.currentframe().f_back.f_locals)
def iter_raw_results(self): """ Iterate over the contents of the results file and return strings containing one result entry each. :return: A generator for iterating over the contents of the results file and returning strings containing one result entry each """ with open(self.file_path, "r") as f: current_entry = "" for line in f: line = line.strip() if not line: continue current_entry = current_entry + line try: int(current_entry[-1]) yield current_entry current_entry = "" except ValueError: pass except Exception: import code code.interact(local=locals()) # Protected Methods # Private Methods # Properties
def handle(self, *args, **options): use_plain = options.get('plain', False) show_imports = options.get('show_imports', True) imported_objects = self.import_objects(show_imports) try: if use_plain: # Don't bother loading IPython, because the user wants plain Python. raise ImportError from IPython import start_ipython except ImportError: # Plain import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") code.interact(banner='', local=imported_objects) else: # IPython start_ipython(argv=['--no-banner', '--no-confirm-exit'], user_ns=imported_objects)