def __init__(self, kwargs): argv = [ '-prompt_in1','\C_Blue\#) \C_Greenrestcli\$ ', ] IPShellEmbed.__init__(self,argv,banner='restkit shell %s' % __version__, exit_msg=None,rc_override=None, user_ns=kwargs)
def __call__(self, context, args): # hijacked from pylons locs = {'ctx': context} banner_header = 'Melkman Interactive Shell\n' banner_footer = '\n\nYou may access the current context as "ctx"' try: # try to use IPython if possible from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=sys.argv) banner = banner_header + shell.IP.BANNER + banner_footer shell.set_banner(banner) shell(local_ns=locs, global_ns={}) except ImportError: import code pyver = 'Python %s' % sys.version banner = banner_header + pyver + banner_footer shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass try: shell.interact(banner) finally: pass
def sh(banner): """Wrapper around interactive ipython shell that factors out ipython version depencies. """ from distutils.version import LooseVersion import IPython if hasattr(IPython, 'release'): try: from IPython.terminal.embed import InteractiveShellEmbed InteractiveShellEmbed(banner1=banner)() except ImportError: try: from IPython.frontend.terminal.embed \ import InteractiveShellEmbed InteractiveShellEmbed(banner1=banner)() except ImportError: from IPython.Shell import IPShellEmbed IPShellEmbed(banner=banner)() else: from IPython.Shell import IPShellEmbed IPShellEmbed(banner=banner)()
def run(self, args): banner = None if not sys.stdin.isatty() or args.files: opts = [ '-noautoindent', '-nobanner', '-colors', 'NoColor', '-noconfirm_exit', '-nomessages', '-nosep', '-prompt_in1', '\x00', '-prompt_in2', '\x00', '-prompt_out', '\x00', '-xmode', 'Plain', ] else: opts = [ '-prompt_in1', 'clusto [\#]> ', '-prompt_out', 'out [\#]> ', ] banner = '\nThis is the clusto shell. Respect it.' if args.loglevel == 'DEBUG': opts.append('-debug') ipshell = IPShellEmbed(opts) if banner: ipshell.set_banner(banner) ipshell()
def __init__(self, *args, **kwargs): IPShellEmbed.__init__(self, *args, **kwargs) # now self.IP exisits old_interact = self.IP.interact # save the real method def new_interact(self, *args): """ wrapper method which checks the user namespace """ self.IP.user_ns.update({'_ips_exit':False}) old_interact(*args) # call the real interact method # now look if the user wants to stop if self.IP.user_ns['_ips_exit']: def do_nothing(*args, **kwargs): pass # harakiri # the calling method replaces itself with a the dummy self.IP.interact = do_nothing # replace the original interact method with the wrapper self.IP.interact = new.instancemethod(new_interact, self, type(self))
def __init__(self, *args, **kwargs): IPShellEmbed.__init__(self, *args, **kwargs) # now self.IP exisits old_interact = self.IP.interact # save the real method def new_interact(self, *args): """ wrapper method which checks the user namespace """ self.IP.user_ns.update({'_ips_exit': False}) old_interact(*args) # call the real interact method # now look if the user wants to stop if self.IP.user_ns['_ips_exit']: def do_nothing(*args, **kwargs): pass # harakiri # the calling method replaces itself with a the dummy self.IP.interact = do_nothing # replace the original interact method with the wrapper self.IP.interact = new.instancemethod(new_interact, self, type(self))
def run(self, args): banner = None if IPython.__version__ >= '0.11': config=IPython.config.application.Config() if not sys.stdin.isatty() or args.files: opts = [ '-noautoindent', '-nobanner', '-colors', 'NoColor', '-noconfirm_exit', '-nomessages', '-nosep', '-prompt_in1', '\x00', '-prompt_in2', '\x00', '-prompt_out', '\x00', '-xmode', 'Plain', ] if IPython.__version__ >= '0.11': config.TerminalInteractiveShell.autoindent = False config.TerminalIPythonApp.display_banner = False config.TerminalInteractiveShell.color_info = False config.TerminalInteractiveShell.confirm_exit = False config.TerminalInteractiveShell.quiet = True config.TerminalIPythonApp.ignore_old_config = True config.TerminalInteractiveShell.separate_in = '' config.PromptManager.in_template = '\x00' config.PromptManager.in_template1 = '\x00' config.PromptManager.in_template2 = '\x00' config.PromptManager.out_template = '\x00' config.TerminalInteractiveShell.xmode = 'Plain' else: opts = [ '-prompt_in1', 'clusto [\#]> ', '-prompt_out', 'out [\#]> ', ] banner = '\nThis is the clusto shell. Respect it.' if IPython.__version__ >= '0.11': config.PromptManager.in_template = 'clusto [\#]> ' config.PromptManager.out_template = 'out [\#]> ' if args.loglevel == 'DEBUG': opts.append('-debug') config.debug = True plugins = script_helper.load_plugins(self.config) plugins.update(globals()) if IPython.__version__ < '0.11': from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(opts, user_ns=plugins) if banner: ipshell.set_banner(banner) elif IPython.__version__ < '1.0': from IPython.frontend.terminal import embed ipshell = embed.InteractiveShellEmbed(banner1=banner, config=config, user_ns=plugins) else: from IPython.terminal import embed ipshell = embed.InteractiveShellEmbed(banner1=banner, config=config, user_ns=plugins) ipshell()
def ipython(self, locs, banner): try: from IPython import embed embed(user_ns=locs, banner2=banner) except ImportError: from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=[]) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) shell(local_ns=locs, global_ns={})
def __init__(self, section=''): argv = [ '-prompt_in1', '\C_Blue\#) \C_Greenldap/%s\$ ' % section, ] IPShellEmbed.__init__(self, argv, banner='', exit_msg=None, rc_override=None, user_ns=None)
def main(): clear() banner = '+----------------------------------------------------+\n' banner += ' SimpleCV [interactive shell]\n' banner += '+----------------------------------------------------+\n' banner += '\n' banner += 'Commands: \n' banner += '\t"exit()" or press "Ctrl+ D" to exit the shell\n' banner += '\t"clear" to clear the shell screen\n' banner += '\t"tutorial" to begin the SimpleCV interactive tutorial\n' banner += '\t"cheatsheet" gives a cheatsheet of all the shell functions\n' banner += '\t"simplehelp" gives list of commands or help on a certain command\n' banner += '\t"example" gives a list of examples you can run' banner += '\n' banner += 'Usage:\n' banner += '\tdot complete works to show library\n' banner += '\tfor example: Image().save("/tmp/test.jpg") will dot complete\n' banner += '\tjust by touching TAB after typing Image().\n' banner += '\n' banner += 'API Documentation:\n' banner += '\t"help function_name" will give in depth documentation of API\n' banner += '\t\texample:' banner += 'help Image or ?Image\n' banner += '\t\twill give the in-depth information about that class\n' banner += '\t"?function_name" will give the quick API documentation\n' banner += '\t\texample:' banner += '?Image.save\n' banner += '\t\twill give help on the image save function' exit_msg = '\nExiting the SimpleCV interactive shell\n' #setup terminal to show SCV prompt argsv = ['-pi1','SimpleCV:\\#>','-pi2',' .\\D.:','-po','SimpleCV:\\#>','-nosep'] scvShell = IPShellEmbed(argsv) scvShell.set_banner(banner) scvShell.set_exit_msg(exit_msg) scvShell.IP.api.expose_magic("tutorial",magic_tutorial) scvShell.IP.api.expose_magic("clear", magic_clear) scvShell.IP.api.expose_magic("simplehelp", magic_help) scvShell.IP.api.expose_magic("cheatsheet", magic_cheatsheet) scvShell.IP.api.expose_magic("example", magic_examples) #Note that all loaded libraries are inherited in the embedded ipython shell sys.exit(scvShell())
def __call__(self): class ShellCommands: pass cmds = ShellCommands() ShellCommands.__doc__ = "Commands:" for Command in sorted(plugins.get(COMMANDLINE_PLUGIN), key=attrgetter('command_name')): # help is skipped because it relates to the command line option # info for the commands. The built-in python help should be # used in the shell. if (not hasattr(Command, '__call__') or Command == HelpCommand or isinstance(self, Command)): continue shell_cmd = Command(self.config).__call__ shell_cmd.__func__.__name__ = Command.command_name setattr(cmds, Command.command_name, shell_cmd) ShellCommands.__doc__ += "\n " ShellCommands.__doc__ += Command.command_name.ljust(20) ShellCommands.__doc__ += Command.description ShellCommands.__doc__ += "\n\nType: help(cmds.<function>) for more info" locs = {'config': self.config, 'cmds': cmds } banner_header = 'RadarPost Interactive Shell\n' banner_footer = '\n\nYou may access the current config as "config"' banner_footer += '\nCLI commands are available as "cmds.<command>"' banner_footer += '\nType: help(cmds) for more info' try: # try to use IPython if possible from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=sys.argv) banner = banner_header + shell.IP.BANNER + banner_footer shell.set_banner(banner) shell(local_ns=locs, global_ns={}) except ImportError: import code pyver = 'Python %s' % sys.version banner = banner_header + pyver + banner_footer shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass try: shell.interact(banner) finally: pass
def ipython(self, locals=None): """Provides an interactive shell aka console inside your testcase. Uses ipython for on steroids shell... It looks exact like in a doctestcase and you can copy and paste code from the shell into your doctest. The locals in the testcase are available, becasue you are in the testcase. In your testcase or doctest you can invoke the shell at any point by calling:: >>> self.ipython( locals() ) locals -- passed to InteractiveInterpreter.__init__() """ savestdout = sys.stdout sys.stdout = sys.stderr sys.stderr.write('=' * 70) embedshell = IPShellEmbed( argv=[], banner=""" IPython Interactive Console Note: You have the same locals available as in your test-case. """, exit_msg="""end of ZopeTestCase Interactive Console session""", user_ns=locals) embedshell() sys.stdout.write('=' * 70 + '\n') sys.stdout = savestdout
def ipython(): from IPython.Shell import IPShellEmbed Base.metadata.create_all(engine) session = Session() student = session.query(User).filter_by(name='curtis').first() _class = session.query(Class).filter_by(name='OPENSTACK 101').first() image = session.query(Image).filter_by(name='CentOS 6').first() try: servers = nova.servers.list() except: servers = None #reservation = Reservation(user_id=student.id, class_id=_class.id, image_id=image.id) #session.add(reservation) #session.commit() ipshell = IPShellEmbed() ipshell()
def shell(): ''' shell() Return ipython shell. To actually start the shell, invoke the function returned by this function. This is particularly useful for debugging embedded python or for crawling over the data when something has gone wrong. ''' import sys if not hasattr(sys, "argv"): sys.argv = [] try: from IPython.Shell import IPShellEmbed except ImportError: sys.stderr.write(""" ***************************************************** *** Failed to import IPython. This probably means *** *** you don't have it installed. Please install *** *** IPython and try again. *** ***************************************************** """) raise banner = """ This is an IPython shell embedded in Fluidity. You can use it to examine or even set variables. Press CTRL+d to exit and return to Fluidity. """ ipshell = IPShellEmbed(banner=banner) return ipshell
def ipython(frame_or_depth=1, runs=1, argv=None, _frame_type=type(sys._getframe()), _lock=threading.RLock(), **kwargs): """Embed an IPython shell in-line for debugging""" try: with _lock: from IPython.Shell import IPShellEmbed if IPShellEmbed.__dict__.setdefault('runs', 0) < runs: IPShellEmbed.runs += 1 if isinstance(frame_or_depth, numbers.Integral): frame = sys._getframe(frame_or_depth) elif isinstance(frame_or_depth, _frame_type): frame = frame_or_depth else: raise TypeError('arg 1 must be frame or depth, not ' + type(frame_or_depth).__name__) if argv is None: argv = ['ipython'] old_argv, sys.argv[:] = sys.argv[:], argv[:] try: IPShellEmbed(user_ns=kwargs)( header='locals: ' + ' '.join(sorted(frame.f_locals)) if frame.f_locals else '', local_ns=frame.f_locals, global_ns=frame.f_globals) finally: sys.argv[:] = old_argv[:] except (SystemExit, KeyboardInterrupt, EOFError): raise except: exc_info = sys.exc_info() traceback.print_exception(*exc_info)
def use_ipython(options, sched, plasm, locals={}): '''Launch a plasm using ipython, and a scheduler of choice. Keyword arguments: options -- are from scheduler_options sched -- is an already initialized scheduler for plasm. plasm -- The graph to execute locals -- are a dictionary of locals to forward to the ipython shell, use locals() ''' #expose the locals to the ipython prompt. for key, val in locals.items(): vars()[key] = val sched.prepare_jobs(options.niter) print "Scheduler ready to run. To execute for some number of microseconds, type:" print "sched.run(1000)" import IPython if IPython.__version__ < '0.11': from IPython.Shell import IPShellEmbed #the argv is important so that the IPShellEmbed doesn't use the global #Also fancy colors!!!! ipython_argv = ['-prompt_in1', 'Input <\\#>', '-colors', 'LightBG'] ipshell = IPShellEmbed(ipython_argv) ipshell() else: from IPython import embed embed() # this call anywhere in your program will start IPython
def setupIpython(): try: import IPython from IPython.config.loader import Config from IPython.frontend.terminal.embed import InteractiveShellEmbed cfg = Config() cfg.PromptManager.in_template = "BinPy:\\#> " cfg.PromptManager.out_template = "BinPy:\\#: " bpyShell = InteractiveShellEmbed(config=cfg, banner1=banner, exit_msg=exit_msg) bpyShell.define_magic("clear", magic_clear) except ImportError: try: from IPython.Shell import IPShellEmbed argsv = [ '-pi1', 'BinPY:\\#>', '-pi2', ' .\\D.:', '-po', 'BinPy:\\#>', '-nosep' ] bpyShell = IPShellEmbed(argsv) bpyShell.set_banner(banner) bpyShell.set_exit_msg(exit_msg) except ImportError: raise return bpyShell()
def start_python_console(namespace=None, noipython=False, banner=''): """Start Python console binded to the given namespace. If IPython is available, an IPython console will be started instead, unless `noipython` is True. Also, tab completion will be used on Unix systems. """ if namespace is None: namespace = {} try: try: # use IPython if available if noipython: raise ImportError() try: try: from IPython.terminal import embed except ImportError: from IPython.frontend.terminal import embed sh = embed.InteractiveShellEmbed(banner1=banner) except ImportError: from IPython.Shell import IPShellEmbed sh = IPShellEmbed(banner=banner) sh(global_ns={}, local_ns=namespace) except ImportError: import code try: # readline module is only available on unix systems import readline except ImportError: pass else: import rlcompleter readline.parse_and_bind("tab:complete") code.interact(banner=banner, local=namespace) except SystemExit: # raised when using exit() in python code.interact pass
def startIpythonShell(in_template='CING \#> ', in2_template='CING \#>> ', out_template='CING \#: ', banner='--------Dropping to IPython--------', exit_msg='--------Leaving IPython--------'): iPythonVersionType = getIpythonVersionType() if iPythonVersionType == None: nTerror("Failed to getIpythonVersionType") elif iPythonVersionType == IPYTHON_VERSION_A: # The next import is missing in one OSX installation but is on all others. # The new way of doing this would be the below but that still fails on all OSX installs but the one above. # from IPython.frontend.terminal.embed import InteractiveShellEmbed # The next method started to fail in 2012 see issue 329 # pylint: disable=W0404 # pylint: disable=E0611 from IPython.Shell import IPShellEmbed #@UnresolvedImport ipshell = IPShellEmbed( ['-prompt_in1', in_template ], # Fails to be set correctly on ipython version 0.11. banner=banner, exit_msg=exit_msg) ipshell() elif iPythonVersionType == IPYTHON_VERSION_B: # pylint: disable=W0404 # pylint: disable=E0611 from IPython.config.loader import Config #@UnresolvedImport cfg = Config() cfg.PromptManager.in_template = in_template cfg.PromptManager.in2_template = in2_template cfg.PromptManager.out_template = out_template IPython.embed(config=cfg, banner1=banner, exit_msg=exit_msg) #@UnresolvedImport # pylint: disable=E1101 else: nTerror("Got unexpected value %s from getIpythonVersionType" % str(iPythonVersionType))
def shell(*args): """Interactive Shell""" if "--ipython" in args: """IPython Interactive Shell - IPython must be installed to use.""" # remove an argument that confuses ipython sys.argv.pop(sys.argv.index("--ipython")) from IPython.Shell import IPShellEmbed import infogami # noqa: F401 from infogami.utils import delegate from infogami.core import db # noqa: F401 from infogami.utils.context import context as ctx # noqa: F401 delegate.fakeload() ipshell = IPShellEmbed() ipshell() else: from code import InteractiveConsole console = InteractiveConsole() console.push("import infogami") console.push("from infogami.utils import delegate") console.push("from infogami.core import db") console.push("from infogami.utils.context import context as ctx") console.push("delegate.fakeload()") console.interact()
def ip_thread(): from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed( argv='', banner='OpenRAVE Dropping into IPython, variables:' + 'env, robot', exit_msg='Leaving Interpreter and ' + 'closing program.') ipshell(local_ns=locals())
def start_shell(self, runner): try: import IPython except: IPython = None if not hasattr(self, 'bridge'): self.start_jsbridge_network() jsobj = JSObject(self.bridge, window_string) if IPython is None or self.options.usecode: import code code.interact( local={ "jsobj": jsobj, "getBrowserWindow": lambda: getBrowserWindow(self.bridge), "back_channel": self.back_channel, }) else: from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed([]) ipshell( local_ns={ "jsobj": jsobj, "getBrowserWindow": lambda: getBrowserWindow(self.bridge), "back_channel": self.back_channel, }) runner.stop()
def ipython_break(frame, depth, #pylint: disable-msg=W0613 color_scheme='Linux'): '''Start an interactive debugger session based on the IPython debugger''' #This code is a pretty dirty hack to get around some obscure #IPython issue global IPYTHON_TRACER if not IPYTHON_TRACER: # This is the first time this procedure is called # Due to some funky IPython 0.10 internals, we need the following: import IPython if map(int, IPython.__version__.split('.'))[:2] == [0, 10]: from IPython.Shell import IPShellEmbed IPShellEmbed(argv=[]) old_colors = ExceptionColors.active_scheme_name ExceptionColors.active_scheme_name = color_scheme if not IPYTHON_TRACER: IPYTHON_TRACER = Tracer(color_scheme) IPYTHON_TRACER.debugger.set_trace(frame) ExceptionColors.active_scheme_name = old_colors
def command_shell(*args): ''' Runs a Python shell inside the application context. ''' context = None banner = 'Open Media Library' import db with db.session(): # Try BPython try: from bpython import embed embed(banner=banner, locals_=context) return except ImportError: pass # Try IPython try: try: # 0.10.x from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(banner=banner) ipshell(global_ns=dict(), local_ns=context) except ImportError: # 0.12+ from IPython import embed embed(banner1=banner, user_ns=context) return except ImportError: pass import code # Use basic python shell code.interact(banner, local=context)
def __call__(self, pm, args): import gentoopm.filters as f import gentoopm.matchers as m our_imports = (('pm', pm), ('f', f), ('m', m)) welc = '''The following objects have been imported for you:\n''' welc += '\n'.join( ['\t%s: %s' % (key, repr(var)) for key, var in our_imports]) kwargs = {} try: from IPython import embed except ImportError: try: from IPython.Shell import IPShellEmbed except ImportError: print('For better user experience, install IPython.') from code import InteractiveConsole embed = InteractiveConsole({'pm': pm}).interact kwargs['banner'] = welc else: embed = IPShellEmbed() embed.set_banner(embed.IP.BANNER + '\n\n' + welc) else: kwargs['banner2'] = welc embed(**kwargs)
def shell(): try: from IPython.Shell import IPShellEmbed IPShellEmbed()(INTRO_MESSAGE) except ImportError: import code code.InteractiveConsole(globals()).interact(INTRO_MESSAGE)
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:v", ["help", "file"]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None verbose = False global dat dat = {} for o, a in opts: if o == "-v": verbose = True if o in ("-h", "--help"): usage() sys.exit() if o in ("-o", "--output"): output = a if o in ("-f", "--file"): filename = a dat = load_data(filename) filename = args[0] dat = (load_data(filename)) from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() pl.ion() ipshell("Interactive Qucs Data Plotter")
def ishell(local_ns): """Embed an IPython shell handing it the local namespace from :var:`local_ns`. """ banner = ( "Welcome to the pystuck interactive shell.\nUse the 'modules' dictionary " "to access remote modules (like 'os', or '__main__')\nUse the `%show " "threads` magic to display all thread stack traces.\n") try: from IPython.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed(banner1=banner) ipshell.register_magics(IntrospectMagics) ipshell(local_ns=local_ns) except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(argv=[], user_ns=local_ns, banner1=banner) ipshell.register_magics(IntrospectMagics) ipshell() except ImportError: # IPython not found at all, raise ImportError raise
def use_ipython(options, sched, plasm, locals={}): '''Launch a plasm using ipython, and a scheduler of choice. Keyword arguments: options -- are from scheduler_options sched -- is an already initialized scheduler for plasm. plasm -- The graph to execute locals -- are a dictionary of locals to forward to the ipython shell, use locals() ''' #expose the locals to the ipython prompt. for key, val in locals.items(): vars()[key] = val if type(sched) == ecto.schedulers.Singlethreaded: sched.execute_async(options.niter) else: sched.execute_async(options.niter, options.nthreads) import IPython if IPython.__version__ < '0.11': from IPython.Shell import IPShellEmbed #the argv is important so that the IPShellEmbed doesn't use the global #Also fancy colors!!!! ipython_argv = ['-prompt_in1', 'Input <\\#>', '-colors', 'LightBG'] ipshell = IPShellEmbed(ipython_argv) ipshell() else: from IPython import embed embed() # this call anywhere in your program will start IPython
def __call__(self, args): """ Copied from IPython embed-short example """ import logging logging.basicConfig() from omero.util.upgrade_check import UpgradeCheck check = UpgradeCheck("shell") check.run() if check.isUpgradeNeeded(): self.ctx.out("") ns = {} if args.login: import omero client = self.ctx.conn(args) ns = {"client": client, "omero": omero} try: # IPython 0.11 (see #7112) from IPython import embed embed(user_ns=ns) except ImportError: from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(args.arg) ipshell(local_ns=ns)
def embedd_ipython010(local_ns={}, global_ns={}): from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed( [""], banner = IPYTHON_BANNER, exit_msg = IPYTHON_EXIT_MSG ) ipshell(local_ns=local_ns, global_ns=global_ns)
def run(self, args): from IPython.Shell import IPShellEmbed from werkzeug import Client, EnvironBuilder from dextrose.context import Context from dextrose.http import Response app = load_application(args.package, args.environment) environ_builder = EnvironBuilder() environ = environ_builder.get_environ() request = environ_builder.get_request() client = Client(app, Response) with Context(app, environ, request, {}) as context: banner = "Dextrose IPython shell\n%s" % args.package shell = IPShellEmbed( banner=banner, argv=[ '-prompt_in1', '%s> ' % args.package, '-prompt_in2', '%s... ' % (' ' * (len(args.package) - 3)), '-prompt_out', '=> ' ]) shell(global_ns={}, local_ns={ 'app': app, 'environ': environ, 'client': client, 'context': context })
def run_rpc_shell(self, app_name): settings = self.get_app_settings(app_name) api = self.get_api(self.settings.__dict__, app_name, use_bind=True) # Make PyFlakes ignore the 'unused' variables settings, api = settings, api logfile_root = os.path.expanduser("~/.dirt_api_logs/") if not os.path.exists(logfile_root): print "%r doesn't exist - not logging API calls" %(logfile_root, ) else: logfile = os.path.join(logfile_root, app_name) from .rpc import connection connection.full_message_log_enable(logfile) print "Logging API calls to %r", logfile print "access the api using the `api` variable" print try: from IPython.frontend.terminal.embed import embed embed() except ImportError: # compat with older ipython from IPython.Shell import IPShellEmbed IPShellEmbed(argv='')()
def shell(no_ipython): """Start a new interactive python session.""" banner = ('\nWelcome to the interactive shell environment of LodgeIt!\n' '\n' 'You can use the following predefined objects: app, local, db.\n' 'To run the application (creates a request) use *run_app*.') namespace = make_shell() if not no_ipython: try: try: from IPython.frontend.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed.instance(banner1=banner) except ImportError: from IPython.Shell import IPShellEmbed sh = IPShellEmbed(banner=banner) except ImportError: pass else: sh(local_ns=namespace) return from code import interact interact(banner, local=namespace)
def command(self): # load the application config = self.load_configuration(self.args[0]) setattr(config.app, 'reload', False) app = self.load_app(config) # prepare the locals locs = dict(__name__='pecan-admin') locs['wsgiapp'] = app locs['app'] = TestApp(app) # find the model for the app model = self.load_model(config) if model: locs['model'] = model # insert the pecan locals exec('from pecan import abort, conf, redirect, request, response') in locs # prepare the banner banner = ' The following objects are available:\n' banner += ' %-10s - This project\'s WSGI App instance\n' % 'wsgiapp' banner += ' %-10s - The current configuration\n' % 'conf' banner += ' %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app' if model: model_name = getattr(model, '__module__', getattr(model, '__name__', 'model')) banner += ' %-10s - Models from %s\n' % ('model', model_name) # launch the shell, using IPython if available try: from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=self.args) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) shell(local_ns=locs, global_ns={}) except ImportError: import code py_prefix = sys.platform.startswith('java') and 'J' or 'P' shell_banner = 'Pecan Interactive Shell\n%sython %s\n\n' % \ (py_prefix, sys.version) shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass shell.interact(shell_banner + banner)
def ipython(globals=None, locals=None): calling_frame = sys._getframe(1) if globals == None: globals = calling_frame.f_globals if locals == None: locals = calling_frame.f_locals from IPython.Shell import IPShellEmbed IPShellEmbed([])(local_ns=locals, global_ns=globals)
def do_shell(self, backend_name): """ shell BACKEND Debug a backend. """ try: backend = self.weboob.load_backends(names=[backend_name])[backend_name] except KeyError: print >>sys.stderr, u'Unable to load backend "%s"' % backend_name return 1 browser = backend.browser from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=[]) locs = dict(backend=backend, browser=browser, application=self, weboob=self.weboob) banner = 'Weboob debug shell\nBackend "%s" loaded.\nAvailable variables: %s' % (backend_name, locs) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) shell(local_ns=locs, global_ns={})
def setup_shell(): banner = '+----------------------------------------------------+\n' banner += ' SimpleCV [interactive shell] - http://simplecv.org\n' banner += '+----------------------------------------------------+\n' banner += '\n' banner += 'Commands: \n' banner += '\t"exit()" or press "Ctrl+ D" to exit the shell\n' banner += '\t"clear" to clear the shell screen\n' banner += '\t"tutorial" to begin the SimpleCV interactive tutorial\n' banner += '\t"cheatsheet" gives a cheatsheet of all the shell functions\n' banner += '\t"example" gives a list of examples you can run' banner += '\n' banner += 'Usage:\n' banner += '\tdot complete works to show library\n' banner += '\tfor example: Image().save("/tmp/test.jpg") will dot complete\n' banner += '\tjust by touching TAB after typing Image().\n' banner += 'API Documentation:\n' banner += '\t"help function_name" will give in depth documentation of API\n' banner += '\texample: help Image\n' banner += 'Editor:\n' banner += '\t"editor" will run the SimpleCV code editor in a browser\n' banner += '\t\texample:' banner += 'help Image or ?Image\n' banner += '\t\twill give the in-depth information about that class\n' banner += '\t"?function_name" will give the quick API documentation\n' banner += '\t\texample:' banner += '?Image.save\n' banner += '\t\twill give help on the image save function' exit_msg = '\nExiting the SimpleCV interactive shell\n' #setup terminal to show SCV prompt argsv = ['-pi1','SimpleCV:\\#>','-pi2',' .\\D.:','-po','SimpleCV:\\#>','-nosep'] scvShell = IPShellEmbed(argsv) scvShell.set_banner(banner) scvShell.set_exit_msg(exit_msg) scvShell.IP.api.expose_magic("tutorial",magic_tutorial) scvShell.IP.api.expose_magic("clear", magic_clear) scvShell.IP.api.expose_magic("cheatsheet", magic_cheatsheet) scvShell.IP.api.expose_magic("example", magic_examples) scvShell.IP.api.expose_magic("editor", magic_editor) return scvShell
def main(): options, args, proxy = default_main() # pylint: disable=W0612 ipshell = IPShellEmbed() ipshell.set_banner(""" Launching IPython shell... Available variables: - proxy: the ArduinoProxy instance. - options, args: parsed argument options. To import ArduinoProxy class: >>> from arduino_proxy import ArduinoProxy Enter 'quit()' to exit. """) ipshell()
import sys from IPython.Shell import IPShellEmbed from evnet import pyevThread from pwrcall import Node, expose, loop, unloop from pwrcall.util import NodeException, parse_url CERT = 'clientside.pem' t = pyevThread() t.start() n = Node(cert=CERT) ipshell = IPShellEmbed() def establish(pwrurl): return t.blockingCall(n.establish, pwrurl) def pwrcall(obj, fn, *args): return t.blockingCall(obj.call, fn, *args) if __name__ == '__main__': ipshell.set_banner( '''pwrcall Interactive Shell ------------------------- starts up a evnet loop and pwrcall Node use the Node through the t.blockingCall function''') ipshell.set_exit_msg('Exit.') ipshell() sys.exit(0)
def setup_shell(): banner = '+----------------------------------------------------+\n' banner += ' SimpleCV [interactive shell] - http://simplecv.org\n' banner += '+----------------------------------------------------+\n' banner += '\n' banner += 'Commands: \n' banner += '\t"exit()" or press "Ctrl+ D" to exit the shell\n' banner += '\t"clear" to clear the shell screen\n' banner += '\t"tutorial" to begin the SimpleCV interactive tutorial\n' banner += '\t"cheatsheet" gives a cheatsheet of all the shell functions\n' banner += '\t"example" gives a list of examples you can run' banner += '\n' banner += 'Usage:\n' banner += '\tdot complete works to show library\n' banner += '\tfor example: Image().save("/tmp/test.jpg") will dot complete\n' banner += '\tjust by touching TAB after typing Image().\n' banner += 'API Documentation:\n' banner += '\t"help function_name" will give in depth documentation of API\n' banner += '\texample: help Image\n' banner += 'Editor:\n' banner += '\t"editor" will run the SimpleCV code editor in a browser\n' banner += '\t\texample:' banner += 'help Image or ?Image\n' banner += '\t\twill give the in-depth information about that class\n' banner += '\t"?function_name" will give the quick API documentation\n' banner += '\t\texample:' banner += '?Image.save\n' banner += '\t\twill give help on the image save function' exit_msg = '\n... [Exiting the SimpleCV interactive shell] ...\n' #IPython version is less than 11 if IPVER <= 10: #setup terminal to show SCV prompt argsv = ['-pi1','SimpleCV:\\#>','-pi2',' .\\D.:','-po','SimpleCV:\\#>','-nosep'] scvShell = IPShellEmbed(argsv) scvShell.set_banner(banner) scvShell.set_exit_msg(exit_msg) scvShell.IP.api.expose_magic("tutorial",magic_tutorial) scvShell.IP.api.expose_magic("clear", magic_clear) scvShell.IP.api.expose_magic("cheatsheet", magic_cheatsheet) scvShell.IP.api.expose_magic("example", magic_examples) scvShell.IP.api.expose_magic("editor", magic_editor) return scvShell #IPython version 0.11 or higher else: cfg = Config() cfg.PromptManager.in_template = "SimpleCV:\\#> " cfg.PromptManager.out_template = "SimpleCV:\\#: " #~ cfg.InteractiveShellEmbed.prompt_in1 = "SimpleCV:\\#> " #~ cfg.InteractiveShellEmbed.prompt_out="SimpleCV:\\#: " scvShell = InteractiveShellEmbed(config=cfg, banner1=banner, exit_msg = exit_msg) scvShell.define_magic("tutorial",magic_tutorial) scvShell.define_magic("clear", magic_clear) scvShell.define_magic("cheatsheet", magic_cheatsheet) scvShell.define_magic("example", magic_examples) scvShell.define_magic("editor", magic_editor) return scvShell
def command(self): """Main command to create a new shell""" self.verbose = 3 if len(self.args) == 0: # Assume the .ini file is ./development.ini config_file = 'development.ini' if not os.path.isfile(config_file): raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n' 'Please specify a CONFIG_FILE' % \ (self.parser.get_usage(), os.path.sep, config_file)) else: config_file = self.args[0] config_name = 'config:%s' % config_file here_dir = os.getcwd() if not self.options.quiet: # Configure logging from the config file self.logging_file_config(config_file) conf = appconfig(config_name, relative_to=here_dir) conf.update(dict(app_conf=conf.local_conf, global_conf=conf.global_conf)) paste.deploy.config.CONFIG.push_thread_config(conf) # Load locals and populate with objects for use in shell sys.path.insert(0, here_dir) # Load the wsgi app first so that everything is initialized right wsgiapp = loadapp(config_name, relative_to=here_dir) test_app = paste.fixture.TestApp(wsgiapp) # Query the test app to setup the environment tresponse = test_app.get('/_test_vars') request_id = int(tresponse.body) # Disable restoration during test_app requests test_app.pre_request_hook = lambda self: paste.registry.restorer.restoration_end() test_app.post_request_hook = lambda self: paste.registry.restorer.restoration_begin(request_id) paste.registry.restorer.restoration_begin(request_id) locs = dict(__name__="webcore-admin", application=wsgiapp, test=test_app) exec 'import web' in locs exec 'from web.core import http, Controller, request, response, cache, session' in locs if len(self.args) == 2: execfile(self.args[1], {}, locs) return banner = "Welcome to the WebCore shell." try: if self.options.disable_ipython: raise ImportError() # try to use IPython if possible from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=self.args) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) try: shell(local_ns=locs, global_ns={}) finally: paste.registry.restorer.restoration_end() except ImportError: import code py_prefix = sys.platform.startswith('java') and 'J' or 'P' newbanner = "WebCore Interactive Shell\n%sython %s\n\n" % (py_prefix, sys.version) banner = newbanner + banner shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass try: shell.interact(banner) finally: paste.registry.restorer.restoration_end()
maps = DF.maps refc = dict(pydfhack=pydfhack, API=pydfhack.API, DF=DF, pos=pos, maps=maps) cursor = pos.get_cursor() msize = maps.get_size() block = None tile = None if cursor: block = maps.get_block(point=cursor) if block: tile = block.get_tile(point=cursor) DF.Resume() locs = dict(pydfhack=pydfhack, API=pydfhack.API, DF=DF, pos=pos, maps=maps, msize=msize, cursor=cursor, block=block, tile=tile) banner = """DFHack Shell\n\n"""\ """\tpydfhack = {pydfhack}\n"""\ """\tAPI = {API}\n"""\ """\tDF = {DF}\n"""\ """\tpos = {pos}\n"""\ """\tmaps = {maps}\n"""\ """\tmsize = {msize}\n"""\ """\tcursor = {cursor}\n"""\ """\tblock = {block}\n"""\ """\ttile = {tile}\n""".format(**locs) from IPython.Shell import IPShellEmbed shell = IPShellEmbed() shell.set_banner(shell.IP.BANNER + '\n\n' + banner) shell(local_ns=locs, global_ns={}) DF.Detach()
def command(self): """Main command to create a new shell""" self.verbose = 3 if len(self.args) == 0: # Assume the .ini file is ./development.ini config_file = 'development.ini' if not os.path.isfile(config_file): raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n' 'Please specify a CONFIG_FILE' % \ (self.parser.get_usage(), os.path.sep, config_file)) else: config_file = self.args[0] config_name = 'config:%s' % config_file here_dir = os.getcwd() locs = dict(__name__="pylons-admin") # XXX: Note, initializing CONFIG here is Legacy support. pylons.config # will automatically be initialized and restored via the registry # restorer along with the other StackedObjectProxys # Load app config into paste.deploy to simulate request config # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy # code conf = appconfig(config_name, relative_to=here_dir) conf.update(dict(app_conf=conf.local_conf, global_conf=conf.global_conf)) paste.deploy.config.CONFIG.push_thread_config(conf) # Load locals and populate with objects for use in shell sys.path.insert(0, here_dir) # Load the wsgi app first so that everything is initialized right wsgiapp = loadapp(config_name, relative_to=here_dir) test_app = paste.fixture.TestApp(wsgiapp) # Query the test app to setup the environment tresponse = test_app.get('/_test_vars') request_id = int(tresponse.body) # Disable restoration during test_app requests test_app.pre_request_hook = lambda self: \ paste.registry.restorer.restoration_end() test_app.post_request_hook = lambda self: \ paste.registry.restorer.restoration_begin(request_id) # Restore the state of the Pylons special objects # (StackedObjectProxies) paste.registry.restorer.restoration_begin(request_id) # Determine the package name from the .egg-info top_level.txt. egg_info = find_egg_info_dir(here_dir) f = open(os.path.join(egg_info, 'top_level.txt')) packages = [l.strip() for l in f.readlines() if l.strip() and not l.strip().startswith('#')] f.close() # Start the rest of our imports now that the app is loaded found_base = False for pkg_name in packages: # Import all objects from the base module base_module = pkg_name + '.lib.base' found_base = can_import(base_module) if not found_base: # Minimal template base_module = pkg_name + '.controllers' found_base = can_import(base_module) if found_base: break if not found_base: raise ImportError("Could not import base module. Are you sure " "this is a Pylons app?") base = sys.modules[base_module] base_public = [__name for __name in dir(base) if not \ __name.startswith('_') or __name == '_'] for name in base_public: locs[name] = getattr(base, name) locs.update(dict(wsgiapp=wsgiapp, app=test_app)) mapper = tresponse.config.get('routes.map') if mapper: locs['mapper'] = mapper banner = " All objects from %s are available\n" % base_module banner += " Additional Objects:\n" if mapper: banner += " %-10s - %s\n" % ('mapper', 'Routes mapper object') banner += " %-10s - %s\n" % ('wsgiapp', "This project's WSGI App instance") banner += " %-10s - %s\n" % ('app', 'paste.fixture wrapped around wsgiapp') if not self.options.quiet: # Configure logging from the config file self.logging_file_config(config_file) try: if self.options.disable_ipython: raise ImportError() # try to use IPython if possible from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=self.args) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) try: shell(local_ns=locs, global_ns={}) finally: paste.registry.restorer.restoration_end() except ImportError: import code newbanner = "Pylons Interactive Shell\nPython %s\n\n" % sys.version banner = newbanner + banner shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass try: shell.interact(banner) finally: paste.registry.restorer.restoration_end()
else: print "Running nested copies of IPython." print "The prompts for the nested copy have been modified" nested = 1 # what the embedded instance will see as sys.argv: args = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:','-nosep'] # First import the embeddable shell class from IPython.Shell import IPShellEmbed # Now create an instance of the embeddable shell. The first argument is a # string with options exactly as you would type them if you were starting # IPython at the system command line. Any parameters you want to define for # configuration can thus be specified here. ipshell = IPShellEmbed(args, banner = 'Dropping into IPython', exit_msg = 'Leaving Interpreter, back to program.') # Make a second instance, you can have as many as you want. if nested: args[1] = 'In2<\\#>' else: args = ['-pi1','In2<\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:','-nosep'] ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') print '\nHello. This is printed from the main controller program.\n' # You can then call ipshell() anywhere you need it (with an optional # message): ipshell('***Called from top level. ' 'Hit Ctrl-D to exit interpreter and continue program.')
def command(self): """Main command to create a new shell""" self.verbose = 3 if len(self.args) == 0: # Assume the .ini file is ./development.ini config_file = 'development.ini' if not os.path.isfile(config_file): raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n' 'Please specify a CONFIG_FILE' % (self.parser.get_usage(), os.path.sep, config_file)) else: config_file = self.args[0] config_name = 'config:%s' % config_file here_dir = os.getcwd() locs = dict(__name__="pylons-admin") if not self.options.quiet: # Configure logging from the config file self.logging_file_config(config_file) # XXX: Note, initializing CONFIG here is Legacy support. pylons.config # will automatically be initialized and restored via the registry # restorer along with the other StackedObjectProxys # Load app config into paste.deploy to simulate request config # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy # code conf = appconfig(config_name, relative_to=here_dir) conf.update(dict(app_conf=conf.local_conf, global_conf=conf.global_conf)) paste.deploy.config.CONFIG.push_thread_config(conf) # Load locals and populate with objects for use in shell sys.path.insert(0, here_dir) # Load the wsgi app first so that everything is initialized right wsgiapp = loadapp(config_name, relative_to=here_dir) test_app = paste.fixture.TestApp(wsgiapp) # Query the test app to setup the environment tresponse = test_app.get('/_test_vars') request_id = int(tresponse.body) # Disable restoration during test_app requests test_app.pre_request_hook = lambda self: \ paste.registry.restorer.restoration_end() test_app.post_request_hook = lambda self: \ paste.registry.restorer.restoration_begin(request_id) # Restore the state of the Pylons special objects # (StackedObjectProxies) paste.registry.restorer.restoration_begin(request_id) # Determine the package name from the pylons.config object pkg_name = pylons.config['pylons.package'] # Start the rest of our imports now that the app is loaded if is_minimal_template(pkg_name, True): model_module = None helpers_module = pkg_name + '.helpers' base_module = pkg_name + '.controllers' else: model_module = pkg_name + '.model' helpers_module = pkg_name + '.lib.helpers' base_module = pkg_name + '.lib.base' if model_module and can_import(model_module): locs['model'] = sys.modules[model_module] if can_import(helpers_module): locs['h'] = sys.modules[helpers_module] exec ('from pylons import app_globals, c, config, g, request, ' 'response, session, tmpl_context, url') in locs exec ('from pylons.controllers.util import abort, redirect_to') in locs exec 'from pylons.i18n import _, ungettext, N_' in locs exec 'from pylons.templating import render' in locs # Import all objects from the base module __import__(base_module) base = sys.modules[base_module] base_public = [__name for __name in dir(base) if not __name.startswith('_') or __name == '_'] for name in base_public: locs[name] = getattr(base, name) locs.update(dict(wsgiapp=wsgiapp, app=test_app)) mapper = tresponse.config.get('routes.map') if mapper: locs['mapper'] = mapper banner = " All objects from %s are available\n" % base_module banner += " Additional Objects:\n" if mapper: banner += " %-10s - %s\n" % ('mapper', 'Routes mapper object') banner += " %-10s - %s\n" % ('wsgiapp', "This project's WSGI App instance") banner += " %-10s - %s\n" % ('app', 'paste.fixture wrapped around wsgiapp') try: if self.options.disable_ipython: raise ImportError() # try to use IPython if possible from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=self.args) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) try: shell(local_ns=locs, global_ns={}) finally: paste.registry.restorer.restoration_end() except ImportError: import code py_prefix = sys.platform.startswith('java') and 'J' or 'P' newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \ (py_prefix, sys.version) banner = newbanner + banner shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass try: shell.interact(banner) finally: paste.registry.restorer.restoration_end()
argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] banner = '*** Starting Interactive Shell - Ctrl-D to exit...\n\nnapi is your NexposeAPI variable to play with\n' if IPython.__version__ >= "0.11": from IPython.config.loader import Config cfg = Config() cfg.InteractiveShellEmbed.prompt_in1="myprompt [\\#]> " cfg.InteractiveShellEmbed.prompt_out="myprompt [\\#]: " #cfg.InteractiveShellEmbed.profile=ipythonprofile # directly open the shell IPython.embed(config=cfg, banner2=banner) else: try: from IPython.Shell import IPShellEmbed argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] ipshell = IPShellEmbed(argv,banner='*** Starting Interactive Shell - Ctrl-D to exit...\n\nnapi is your NexposeAPI variable to play with\n') ipshell.set_exit_msg('Buh-bye!') ipshell() except ImportError, e: sys.exit("IPython not installed, won't continue...") if options.listvulns: vuln_class = VulnData(napi.sessionid) vuln_class.populate_summary() if (vuln_class.vulnerabilities) > 0: if options.listvulns.upper() == "CSV": print vuln_class.csvout() else: print vuln_class.vulnxml else: print "Error: No Vulnerabilities loaded, check your Nexpose server address or user/pass"
def command(self): self.verbose = 3 if len(self.args) == 0: config_file = "development.ini" if not os.path.isfile(config_file): raise BadCommand( "%sError: CONFIG_FILE not found at: .%s%s\n" "Please specify a CONFIG_FILE" % (self.parser.get_usage(), os.path.sep, config_file) ) else: config_file = self.args[0] config_name = "config:%s" % config_file here_dir = os.getcwd() locs = dict(__name__="pylons-admin") if not self.options.quiet: self.logging_file_config(config_file) sys.path.insert(0, here_dir) wsgiapp = loadapp(config_name, relative_to=here_dir) test_app = paste.fixture.TestApp(wsgiapp) tresponse = test_app.get("/_test_vars") request_id = int(tresponse.body) test_app.pre_request_hook = lambda self: paste.registry.restorer.restoration_end() test_app.post_request_hook = lambda self: paste.registry.restorer.restoration_begin(request_id) paste.registry.restorer.restoration_begin(request_id) pkg_name = pylons.config["pylons.package"] if is_minimal_template(pkg_name, True): model_module = None helpers_module = pkg_name + ".helpers" base_module = pkg_name + ".controllers" else: model_module = pkg_name + ".model" helpers_module = pkg_name + ".lib.helpers" base_module = pkg_name + ".lib.base" if model_module and can_import(model_module): locs["model"] = sys.modules[model_module] if can_import(helpers_module): locs["h"] = sys.modules[helpers_module] exec ("from pylons import app_globals, config, request, response, " "session, tmpl_context, url") in locs exec ("from pylons.controllers.util import abort, redirect") in locs exec "from pylons.i18n import _, ungettext, N_" in locs locs.pop("__builtins__", None) __import__(base_module) base = sys.modules[base_module] base_public = [__name for __name in dir(base) if not __name.startswith("_") or __name == "_"] locs.update((name, getattr(base, name)) for name in base_public) locs.update(dict(wsgiapp=wsgiapp, app=test_app)) mapper = tresponse.config.get("routes.map") if mapper: locs["mapper"] = mapper banner = " All objects from %s are available\n" % base_module banner += " Additional Objects:\n" if mapper: banner += " %-10s - %s\n" % ("mapper", "Routes mapper object") banner += " %-10s - %s\n" % ("wsgiapp", "This project's WSGI App instance") banner += " %-10s - %s\n" % ("app", "paste.fixture wrapped around wsgiapp") try: if self.options.disable_ipython: raise ImportError() from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=self.args) shell.set_banner(shell.IP.BANNER + "\n\n" + banner) try: shell(local_ns=locs, global_ns={}) finally: paste.registry.restorer.restoration_end() except ImportError: import code py_prefix = sys.platform.startswith("java") and "J" or "P" newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % (py_prefix, sys.version) banner = newbanner + banner shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass try: shell.interact(banner) finally: paste.registry.restorer.restoration_end()
def setup_shell(): banner = '+-----------------------------------------------------------+\n' banner += ' SimpleCV ' banner += SIMPLECV_VERSION banner += ' [interactive shell] - http://simplecv.org\n' banner += '+-----------------------------------------------------------+\n' banner += '\n' banner += 'Commands: \n' banner += '\t"exit()" or press "Ctrl+ D" to exit the shell\n' banner += '\t"clear" to clear the shell screen\n' banner += '\t"tutorial" to begin the SimpleCV interactive tutorial\n' banner += '\t"example" gives a list of examples you can run\n' banner += '\t"forums" will launch a web browser for the help forums\n' banner += '\t"walkthrough" will launch a web browser with a walkthrough\n' banner += '\n' banner += 'Usage:\n' banner += '\tdot complete works to show library\n' banner += '\tfor example: Image().save("/tmp/test.jpg") will dot complete\n' banner += '\tjust by touching TAB after typing Image().\n' banner += '\n' banner += 'Documentation:\n' banner += '\thelp(Image), ?Image, Image?, or Image()? all do the same\n' banner += '\t"docs" will launch webbrowser showing documentation' banner += '\n' exit_msg = '\n... [Exiting the SimpleCV interactive shell] ...\n' #IPython version is less than 11 if IPVER <= 10: #setup terminal to show SCV prompt argsv = ['-pi1','SimpleCV:\\#>','-pi2',' .\\D.:','-po','SimpleCV:\\#>','-nosep'] scvShell = IPShellEmbed(argsv) scvShell.set_banner(banner) scvShell.set_exit_msg(exit_msg) scvShell.IP.api.expose_magic("tutorial",magic_tutorial) scvShell.IP.api.expose_magic("clear", magic_clear) scvShell.IP.api.expose_magic("example", magic_examples) scvShell.IP.api.expose_magic("forums", magic_forums) scvShell.IP.api.expose_magic("walkthrough", magic_walkthrough) scvShell.IP.api.expose_magic("docs", magic_docs) return scvShell #IPython version 0.11 or higher else: cfg = Config() cfg.PromptManager.in_template = "SimpleCV:\\#> " cfg.PromptManager.out_template = "SimpleCV:\\#: " #~ cfg.InteractiveShellEmbed.prompt_in1 = "SimpleCV:\\#> " #~ cfg.InteractiveShellEmbed.prompt_out="SimpleCV:\\#: " scvShell = InteractiveShellEmbed(config=cfg, banner1=banner, exit_msg = exit_msg) scvShell.define_magic("tutorial",magic_tutorial) scvShell.define_magic("clear", magic_clear) scvShell.define_magic("example", magic_examples) scvShell.define_magic("forums", magic_forums) scvShell.define_magic("walkthrough", magic_walkthrough) scvShell.define_magic("docs", magic_docs) return scvShell
def __init__(self, banner=None, locals=None): IPShellEmbed.__init__(self, argv=[], banner=banner, user_ns=locals)