def ipython_console(): """ Run ipython console """ from traitlets.config import Config from IPython.terminal.embed import InteractiveShellEmbed config = Config() # basic configuration config.TerminalInteractiveShell.confirm_exit = False # embed = InteractiveShellEmbed(config=config, banner1='') embed.mainloop()
def ipython_console(): """ Run ipython console """ from traitlets.config import Config from IPython.terminal.embed import InteractiveShellEmbed config = Config() # basic configuration config.TerminalInteractiveShell.confirm_exit = False # embed = InteractiveShellEmbed(config=config, banner1='') embed.mainloop()
def debughook(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: # we are NOT in interactive mode, print the exception... #traceback.print_exception(type, value, tb) colorhook(type, value, tb) frame = tb.tb_next.tb_frame sh = InteractiveShellEmbed( banner1=termcolor.colored("Custom Debug IPython Shell:\n", 'red')) sh.confirm_exit = False sh.mainloop(local_ns=frame.f_locals, global_ns=frame.f_globals)
def make_shell(banner=u'IPython', **namespace): cfg = Config() prompt_config = cfg.PromptManager prompt_config.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> ' prompt_config.out_template = r'<\#> ' sh = InteractiveShellEmbed(config=cfg, banner1=banner) return sh.mainloop(local_ns=namespace)
def debughook(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: # we are NOT in interactive mode, print the exception... #traceback.print_exception(type, value, tb) colorhook(type, value, tb) frame = tb.tb_next.tb_frame sh = InteractiveShellEmbed( banner1=termcolor.colored( "Custom Debug IPython Shell:\n", 'red')) sh.confirm_exit = False sh.mainloop(local_ns=frame.f_locals, global_ns=frame.f_globals)
from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return elif IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') enable_autocomplete_and_history(adir,_env) code.interact(local=_env) def parse_path_info(path_info, av=False): """ Parse path info formatted like a/c/f where c and f are optional and a leading / accepted. Return tuple (a, c, f). If invalid path_info a is set to None. If c or f are omitted they are set to None. If av=True, parse args and vars
from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return elif IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') enable_autocomplete_and_history(adir, _env) code.interact(local=_env) def parse_path_info(path_info, av=False): """ Parses path info formatted like a/c/f where c and f are optional and a leading `/` is accepted. Return tuple (a, c, f). If invalid path_info a is set to None. If c or f are omitted they are set to None. If av=True, parse args and vars
def run(appname, plain=False, import_models=False, startfile=None, bpython=False, python_code=False, cronjob=False): """ Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like: - a : web2py application name - a/c : exec the controller c into the application environment """ (a, c, f, args, vars) = parse_path_info(appname, av=True) errmsg = 'invalid application name: %s' % appname if not a: die(errmsg) adir = os.path.join('applications', a) if not os.path.exists(adir): if sys.stdin and not sys.stdin.name == '/dev/null': confirm = raw_input( 'application %s does not exist, create (y/n)?' % a) else: logging.warn('application does not exist and will not be created') return if confirm.lower() in ['y', 'yes']: os.mkdir(adir) w2p_unpack('welcome.w2p', adir) for subfolder in [ 'models', 'views', 'controllers', 'databases', 'modules', 'cron', 'errors', 'sessions', 'languages', 'static', 'private', 'uploads' ]: subpath = os.path.join(adir, subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(adir, 'models/db.py') if os.path.exists(db): data = fileutils.read_file(db) data = data.replace('<your secret key>', 'sha512:' + web2py_uuid()) fileutils.write_file(db, data) if c: import_models = True extra_request = {} if args: extra_request['args'] = args if vars: extra_request['vars'] = vars _env = env(a, c=c, f=f, import_models=import_models, extra_request=extra_request) if c: pyfile = os.path.join('applications', a, 'controllers', c + '.py') pycfile = os.path.join('applications', a, 'compiled', "controllers_%s_%s.pyc" % (c, f)) if ((cronjob and os.path.isfile(pycfile)) or not os.path.isfile(pyfile)): exec(read_pyc(pycfile), _env) elif os.path.isfile(pyfile): execfile(pyfile, _env) else: die(errmsg) if f: exec('print( %s())' % f, _env) return _env.update(exec_pythonrc()) if startfile: try: ccode = None if startfile.endswith('.pyc'): ccode = read_pyc(startfile) exec(ccode, _env) else: execfile(startfile, _env) if import_models: BaseAdapter.close_all_instances('commit') except Exception as e: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') elif python_code: try: exec(python_code, _env) if import_models: BaseAdapter.close_all_instances('commit') except Exception as e: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning('import bpython error; trying ipython...') else: try: import IPython if IPython.__version__ > '1.0.0': IPython.start_ipython(user_ns=_env) return elif IPython.__version__ == '1.0.0': from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return elif IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') enable_autocomplete_and_history(adir, _env) code.interact(local=_env)
def process_argv(argv): """ Process command-line arguments (minus argv[0]!), rearrange and execute. """ # Initial preparation import __main__ for (k, v) in global_constants.items(): exec '%s = %s' % (k, v) in __main__.__dict__ # Allow param.normalize_path.prefix to be overridden in the # startup files, but otherwise force it to exist before doing # anything else param.normalize_path.prefix = default_output_path() exec_startup_files() set_output_path(param.normalize_path.prefix) # Tell the user how many cores are in use, if available openmp_main = Parameterized( name="OpenMP") # Dummy object just for messages try: import os, multiprocessing total_cores = multiprocessing.cpu_count() num_threads = int(os.environ.get('OMP_NUM_THREADS', total_cores)) openmp_main.verbose( "Using %d threads on a machine with %d detected CPUs", num_threads, total_cores) except: pass # Repeatedly process options, if any, followed by filenames, if any, until nothing is left topo_parser.disable_interspersed_args() args = argv option = None global something_executed while True: # Process options up until the first filename (option, args) = topo_parser.parse_args(args, option) # Handle filename if args: filename = args.pop(0) #print "Executing %s" % (filename) filedir = os.path.dirname(os.path.abspath(filename)) sys.path.insert( 0, filedir) # Allow imports relative to this file's path sim_name_from_filename(filename) # Default value of topo.sim.name execfile(filename, __main__.__dict__) something_executed = True if not args: break global_params.check_for_unused_names() # If no scripts and no commands were given, pretend -i was given. if not something_executed: interactive() if option.gui: topo.guimain.title(topo.sim.name) ## INTERACTIVE SESSION BEGINS HERE (i.e. can't have anything but ## some kind of cleanup code afterwards) if os.environ.get('PYTHONINSPECT'): print "Output path: %s" % param.normalize_path.prefix print BANNER # CBALERT: should probably allow a way for users to pass # things to IPython? Or at least set up some kind of # topographica ipython config file. Right now, a topo_parser # option has to be added for every ipython option we want to # support (e.g. see --pdb) if ipython_shell_interface == "IPython.Shell": # IPython 0.10 and earlier # Stop IPython namespace hack? # http://www.nabble.com/__main__-vs-__main__-td14606612.html __main__.__name__ = "__mynamespace__" ipython_args = [ '-noconfirm_exit', '-nobanner', '-pi1', CommandPrompt.get_format(), '-pi2', CommandPrompt2.get_format(), '-po', OutputPrompt.get_format() ] if option.pdb: ipython_args.append('-pdb') ipshell = IPShell(ipython_args, user_ns=__main__.__dict__) ipshell.mainloop(sys_exit=1) elif ipython_shell_interface == "InteractiveShellEmbed": # IPython 0.11 and later config = Config() if ipython_prompt_interface == "PromptManager": config.PromptManager.in_template = CommandPrompt.get_format() config.PromptManager.in2_template = CommandPrompt2.get_format() config.PromptManager.out_template = OutputPrompt.get_format() else: config.InteractiveShell.prompt_in1 = CommandPrompt.get_format() config.InteractiveShell.prompt_in2 = CommandPrompt2.get_format( ) config.InteractiveShell.prompt_out = OutputPrompt.get_format() config.InteractiveShell.confirm_exit = False ipshell = IPShell(config=config, user_ns=__main__.__dict__, banner1="", exit_msg="") if option.pdb: ipshell.call_pdb = True # Load Topographica IPython extension in embedded shell try: ipshell.extension_manager.load_extension('topo.misc.ipython') except: cmdline_main.warning( "Could not load IPython extension 'topo.misc.ipython'; ignored error was:\n%s" % traceback.format_exc()) ipshell() global return_code if return_code != 0: cmdline_main.warning( "Errors encountered; exiting with return code %d" % return_code) sys.exit(return_code)
def run( appname, plain=False, import_models=False, startfile=None, bpython=False, python_code=None, cronjob=False, scheduler_job=False): """ Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like: - a : web2py application name - a/c : exec the controller c into the application environment - a/c/f : exec the controller c, then the action f into the application environment - a/c/f?x=y : as above """ (a, c, f, args, vars) = parse_path_info(appname, av=True) errmsg = 'invalid application name: %s' % appname if not a: die(errmsg, error_preamble=False) adir = os.path.join('applications', a) if not os.path.exists(adir): if not cronjob and not scheduler_job and \ sys.stdin and not sys.stdin.name == '/dev/null': confirm = raw_input( 'application %s does not exist, create (y/n)?' % a) else: logging.warn('application does not exist and will not be created') return if confirm.lower() in ('y', 'yes'): os.mkdir(adir) fileutils.create_app(adir) if c: import_models = True extra_request = {} if args: extra_request['args'] = args if scheduler_job: extra_request['is_scheduler'] = True if vars: # underscore necessary because request.vars is a property extra_request['_vars'] = vars _env = env(a, c=c, f=f, import_models=import_models, extra_request=extra_request) if c: pyfile = os.path.join('applications', a, 'controllers', c + '.py') pycfile = os.path.join('applications', a, 'compiled', "controllers_%s_%s.pyc" % (c, f)) if ((cronjob and os.path.isfile(pycfile)) or not os.path.isfile(pyfile)): exec(read_pyc(pycfile), _env) elif os.path.isfile(pyfile): execfile(pyfile, _env) else: die(errmsg, error_preamble=False) if f: exec('print( %s())' % f, _env) return _env.update(exec_pythonrc()) if startfile: try: ccode = None if startfile.endswith('.pyc'): ccode = read_pyc(startfile) exec(ccode, _env) else: execfile(startfile, _env) if import_models: BaseAdapter.close_all_instances('commit') except: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') elif python_code: try: exec(python_code, _env) if import_models: BaseAdapter.close_all_instances('commit') except: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning( 'import bpython error; trying ipython...') else: try: import IPython if IPython.__version__ > '1.0.0': IPython.start_ipython(user_ns=_env) return elif IPython.__version__ == '1.0.0': from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return elif IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') enable_autocomplete_and_history(adir, _env) code.interact(local=_env)
def process_argv(argv): """ Process command-line arguments (minus argv[0]!), rearrange and execute. """ # Initial preparation import __main__ for (k,v) in global_constants.items(): exec '%s = %s' % (k,v) in __main__.__dict__ # Allow param.normalize_path.prefix to be overridden in the # startup files, but otherwise force it to exist before doing # anything else param.normalize_path.prefix = default_output_path() exec_startup_files() set_output_path(param.normalize_path.prefix) # Tell the user how many cores are in use, if available openmp_main=Parameterized(name="OpenMP") # Dummy object just for messages try: import os,multiprocessing total_cores = multiprocessing.cpu_count() num_threads = int(os.environ.get('OMP_NUM_THREADS',total_cores)) openmp_main.verbose("Using %d threads on a machine with %d detected CPUs" % (num_threads, total_cores)) except: pass # Repeatedly process options, if any, followed by filenames, if any, until nothing is left topo_parser.disable_interspersed_args() args=argv option=None global something_executed while True: # Process options up until the first filename (option,args) = topo_parser.parse_args(args,option) # Handle filename if args: filename=args.pop(0) #print "Executing %s" % (filename) filedir = os.path.dirname(os.path.abspath(filename)) sys.path.insert(0,filedir) # Allow imports relative to this file's path sim_name_from_filename(filename) # Default value of topo.sim.name execfile(filename,__main__.__dict__) something_executed=True if not args: break global_params.check_for_unused_names() # If no scripts and no commands were given, pretend -i was given. if not something_executed: interactive() if option.gui: topo.guimain.title(topo.sim.name) ## INTERACTIVE SESSION BEGINS HERE (i.e. can't have anything but ## some kind of cleanup code afterwards) if os.environ.get('PYTHONINSPECT'): print "Output path: %s" % param.normalize_path.prefix print BANNER # CBALERT: should probably allow a way for users to pass # things to IPython? Or at least set up some kind of # topographica ipython config file. Right now, a topo_parser # option has to be added for every ipython option we want to # support (e.g. see --pdb) if ipython_shell_interface == "IPython.Shell": # IPython 0.10 and earlier # Stop IPython namespace hack? # http://www.nabble.com/__main__-vs-__main__-td14606612.html __main__.__name__="__mynamespace__" ipython_args = ['-noconfirm_exit','-nobanner', '-pi1',CommandPrompt.get_format(), '-pi2',CommandPrompt2.get_format(), '-po',OutputPrompt.get_format()] if option.pdb: ipython_args.append('-pdb') ipshell = IPShell(ipython_args,user_ns=__main__.__dict__) ipshell.mainloop(sys_exit=1) elif ipython_shell_interface == "InteractiveShellEmbed": # IPython 0.11 and later config = Config() if ipython_prompt_interface == "PromptManager": config.PromptManager.in_template = CommandPrompt.get_format() config.PromptManager.in2_template = CommandPrompt2.get_format() config.PromptManager.out_template = OutputPrompt.get_format() else: config.InteractiveShell.prompt_in1 = CommandPrompt.get_format() config.InteractiveShell.prompt_in2 = CommandPrompt2.get_format() config.InteractiveShell.prompt_out = OutputPrompt.get_format() config.InteractiveShell.confirm_exit = False ipshell = IPShell(config=config,user_ns=__main__.__dict__, banner1="",exit_msg="") if option.pdb: ipshell.call_pdb = True # Load Topographica IPython extension in embedded shell ipshell.extension_manager.load_extension('topo.misc.ipython') ipshell() global return_code if return_code != 0: cmdline_main.warning("Errors encountered; exiting with return code %d" % return_code) sys.exit(return_code)
class Repl(Application): """ Repl is a Application that collects all registered functions and injects them into an interactive Python shell, or REPL. This is useful for experimenting with an API from a command-line interface. """ def __init__(self, autoreload=True, *args, **kwargs): super().__init__(*args, **kwargs) self._autoreload = autoreload self.shell = None @property def action_type(self) -> Type['ReplFunction']: return ReplFunction @property def autoreload(self) -> bool: return self._autoreload @autoreload.setter def autoreload(self, new_value: bool): if (not new_value) and self._autoreload: self.shell.extension_manager.unload_extension('autoreload') elif new_value and (not self._autoreload): self.shell.extension_manager.load_extension('autoreload') self._autoreload = new_value @property def namespace(self) -> Dict: """ iPython's embedded shell session namespace dict. Update this dict from methods when you want to, say, rerun and reload fixture data inside a REPL, like: ```python3 @repl() def reset_fixtures(): fixtures = { 'foo': Foo().save(), 'bar': Bar().save() } repl.namespace.update(fixtures) return fixtures ``` Now, inside the REPL session, you can do `reset_fixtures()` to reset the global variables available to you in the shell. """ if not self.is_bootstrapped: return super().namespace else: return self.shell.user_ns @property def functions(self) -> List[Text]: """ Get list of names of all registered functions in the REPL. """ return sorted(self.actions.keys()) def on_start(self): """ Start a new REPL with all registered functions available in the REPL namespace. """ from IPython.terminal.embed import InteractiveShellEmbed self.shell = InteractiveShellEmbed() if self._autoreload: self.shell.extension_manager.load_extension('autoreload') # build the shell namespace local_ns = {} local_ns['repl'] = self local_ns.update(self._namespace) local_ns.update(self.actions) local_ns.update(self.manifest.resource_classes) local_ns.update(self.manifest.store_classes) # enter an ipython shell self.shell.mainloop(local_ns=local_ns) def on_response(self, repl_function: 'ReplFunction', result, *args, **kwargs) -> object: if repl_function.memoized: repl_function.memoize(result) return super().on_response(repl_function, result, *args, **kwargs)
You can script the device's SCSI interface too: sc c ac # Backdoor signature sc 8 ff 00 ff # Undocumented firmware version ALSO: reset, eject, sc_sense, sc_read, scsi_in, scsi_out Happy hacking! -- Type 'thing?' for help on 'thing' or ~MeS`14 '?' for IPython, '%h' for this again. """ from IPython.terminal.embed import InteractiveShellEmbed from shell_magics import ShellMagics from remote import Device import shell_namespace # Make a global device, but only give it to the user namespace. # Make it default by assigning it to 'd', our current device. shell_namespace.d = shell_namespace.d_remote = Device() # Make a shell that feels like a debugger ipy = InteractiveShellEmbed(user_ns = shell_namespace.__dict__) shell_namespace.ipy = ipy ipy.register_magics(ShellMagics) ipy.register_magic_function(lambda _: ipy.write(__doc__), magic_name='h') ipy.alias_manager.define_alias('git', 'git') ipy.alias_manager.define_alias('make', 'make') # Hello, tiny world ipy.mainloop(display_banner = __doc__)
from shell_magics import ShellMagics from remote import Device import shell_namespace import sys messages = '' user_ns = dict(shell_namespace.__dict__) # Make a global device, but only give it to the user namespace. # Make it default by assigning it to 'd', our current device. try: user_ns['d'] = user_ns['d_remote'] = Device() except IOError as e: messages += "\n-------- There is NO DEVICE available! --------\n" messages += "\n%s\n\n" % e messages += "--> Try again to attach via USB: %reset\n" messages += "--> Reattach over bitbang serial: %bitbang -a /dev/tty.usb<tab>\n" user_ns['d'] = user_ns['d_remote'] = None # Make a shell that feels like a debugger ipy = InteractiveShellEmbed(user_ns=user_ns) user_ns['ipy'] = ipy ipy.register_magics(ShellMagics) ipy.register_magic_function(lambda _: ipy.write(__doc__), magic_name='h') ipy.alias_manager.define_alias('git', 'git') ipy.alias_manager.define_alias('make', 'make') # Hello, tiny world sys.stdout.write(__doc__ + messages) ipy.mainloop()
~MeS`14 '?' for IPython, '%h' for this again. """ from IPython.terminal.embed import InteractiveShellEmbed from shell_magics import ShellMagics from remote import Device import shell_namespace messages = '' # Make a global device, but only give it to the user namespace. # Make it default by assigning it to 'd', our current device. try: shell_namespace.d = shell_namespace.d_remote = Device() except IOError, e: messages += "\n-------- There is NO DEVICE available! --------\n" messages += "\n%s\n\n" % e messages += "--> Try again to attach via USB: %reset\n" messages += "--> Reattach over bitbang serial: %bitbang -a /dev/tty.usb<tab>\n" shell_namespace.d = shell_namespace.d_remote = None # Make a shell that feels like a debugger ipy = InteractiveShellEmbed(user_ns = shell_namespace.__dict__) shell_namespace.ipy = ipy ipy.register_magics(ShellMagics) ipy.register_magic_function(lambda _: ipy.write(__doc__), magic_name='h') ipy.alias_manager.define_alias('git', 'git') ipy.alias_manager.define_alias('make', 'make') # Hello, tiny world ipy.mainloop(display_banner = __doc__ + messages)
def run( appname, plain=False, import_models=False, startfile=None, bpython=False, python_code=False, cronjob=False): """ Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like: - a : web2py application name - a/c : exec the controller c into the application environment """ (a, c, f, args, vars) = parse_path_info(appname, av=True) errmsg = 'invalid application name: %s' % appname if not a: die(errmsg) adir = os.path.join('applications', a) if not os.path.exists(adir): if sys.stdin and not sys.stdin.name == '/dev/null': confirm = raw_input( 'application %s does not exist, create (y/n)?' % a) else: logging.warn('application does not exist and will not be created') return if confirm.lower() in ['y', 'yes']: os.mkdir(adir) w2p_unpack('welcome.w2p', adir) for subfolder in ['models', 'views', 'controllers', 'databases', 'modules', 'cron', 'errors', 'sessions', 'languages', 'static', 'private', 'uploads']: subpath = os.path.join(adir, subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(adir, 'models/db.py') if os.path.exists(db): data = fileutils.read_file(db) data = data.replace( '<your secret key>', 'sha512:' + web2py_uuid()) fileutils.write_file(db, data) if c: import_models = True extra_request = {} if args: extra_request['args'] = args if vars: extra_request['vars'] = vars _env = env(a, c=c, f=f, import_models=import_models, extra_request=extra_request) if c: pyfile = os.path.join('applications', a, 'controllers', c + '.py') pycfile = os.path.join('applications', a, 'compiled', "controllers_%s_%s.pyc" % (c, f)) if ((cronjob and os.path.isfile(pycfile)) or not os.path.isfile(pyfile)): exec(read_pyc(pycfile), _env) elif os.path.isfile(pyfile): execfile(pyfile, _env) else: die(errmsg) if f: exec('print %s()' % f, _env) return _env.update(exec_pythonrc()) if startfile: try: ccode = None if startfile.endswith('.pyc'): ccode = read_pyc(startfile) exec(ccode, _env) else: execfile(startfile, _env) if import_models: BaseAdapter.close_all_instances('commit') except Exception as e: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') elif python_code: try: exec(python_code, _env) if import_models: BaseAdapter.close_all_instances('commit') except Exception as e: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning( 'import bpython error; trying ipython...') else: try: import IPython if IPython.__version__ > '1.0.0': IPython.start_ipython(user_ns=_env) return elif IPython.__version__ == '1.0.0': from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return elif IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') enable_autocomplete_and_history(adir, _env) code.interact(local=_env)