def __init__(self): """Constructor. Imports Python's classic shell""" Shell.__init__(self) ConsoleProgressBarMixin.__init__(self) self._shell = None
def __init__(self): """Constructor. Imports Python's classic shell""" Shell.__init__(self) self._shell = None try: self.__class__.progress_bar = ProgressBar(TerminalController()) except ValueError: # Terminal is not capable enough, disable progress handler del self.__class__._progress_handler
def random_surf(self): link_or_form = self._random_pick() from IPython import Shell Shell.IPShellEmbed()() if isinstance(link_or_form, Link): self._follow_link(link_or_form) elif isinstance(link_or_form, Form): self._use_form(link_or_form)
def IPShell(argv=None, user_ns=None, banner=None): if argv is None: argv = [] try: from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=user_ns, banner2=str(banner)) shell(local_ns=user_ns) except ImportError: from IPython import Shell # IPython < 0.11 Shell.IPShell(argv=argv, user_ns=user_ns).mainloop(banner=banner)
def newcomment(request, urlCode): """Adds a new comment to the database""" output = "OK" debugvar = 0 try: if (request.method == "POST"): name = request.POST["name"] name = javaScriptEscape(name) message = request.POST["message"] message = javaScriptEscape(message) side = request.POST["side"] side = javaScriptEscape(side) chunk = int(request.POST["chunk"]) line = int(request.POST["line"]) # basic sanity check if (not (side == 'lhs' or side == 'rhs')): output = "ERROR" else: targetPatch = get_object_or_404(Patch, pk=urlCode) print "patch - ", urlCode, " chunknum ", chunk targetChunks = Chunk.objects.filter(patch=targetPatch, chunkNum=chunk) print "Target chunks length - " + str(len(targetChunks)) targetChunk = targetChunks[0] newComment = Comment() newComment.chunk = targetChunk newComment.commentAuthor = name newComment.commentText = message newComment.diffSide = side newComment.commentLine = line newComment.chunkID = chunk newComment.commentID = 0 newComment.save() else: output = "ERROR" except Exception as e: from IPython import Shell Shell.IPShellEmbed() print "exception ", e output = "ERROR" return HttpResponse(output)
def IPShell(argv=None, user_ns=None, banner=None): if argv is None: argv = [] try: from IPython.terminal.embed import InteractiveShellEmbed from IPython.config.loader import Config cfg = Config() cfg.InteractiveShellEmbed.autocall = 2 shell = InteractiveShellEmbed(config=cfg, user_ns=user_ns, banner2=banner) shell(local_ns=user_ns) except ImportError: from IPython import Shell # IPython < 0.11 Shell.IPShell(argv=argv, user_ns=user_ns).mainloop(banner=banner)
def IPShell(argv=None, user_ns=None, banner=None): if argv is None: argv = [] try: # pylint: disable=g-import-not-at-top from IPython.terminal.embed import InteractiveShellEmbed from IPython.config.loader import Config # pylint: enable=g-import-not-at-top cfg = Config() cfg.InteractiveShellEmbed.autocall = 2 shell = InteractiveShellEmbed(config=cfg, user_ns=user_ns) shell(local_ns=user_ns) except ImportError: # pylint: disable=g-import-not-at-top from IPython import Shell # pylint: enable=g-import-not-at-top # IPython < 0.11 Shell.IPShell(argv=argv, user_ns=user_ns).mainloop(banner=banner)
def __init__(self, doc, nbk, logid, *args, **kwds): self.doc = doc self.notebook = nbk self.log = nbk.get_log(logid) self.logid = logid #this is also self.log.id self.last = False self._lastcell = None #used by self.lastcell #set up wrapper to use for long output self.wrapper = textwrap.TextWrapper() #Here I will sort the cells, according to their numbers #self.log.element[:] = sorted(self.log, key = lambda x:int(x.attrib['number'])) #XXX modifies the xml element(tree) that nb Log wraps so it may be bad #then again, as log.cells is a list (array), #as far as i can see the elements are always sorted already #(so that sorting never does anything in the current impl, right?) #Set up plotting self.plot_api = backend.PlotLibraryInterface(self.filename_iter()) #Set up the interpreter #For now we will keep our own excepthook self.stdin_orig = sys.stdin self.stdout_orig = sys.stdout self.stderr_orig = sys.stderr self.excepthook_orig = sys.excepthook import __builtin__ __builtin__.close = __builtin__.exit = __builtin__.quit = \ 'Click on the close button to leave the application.' user_ns = {'__name__' :'__main__',\ '__builtins__' : __builtin__,\ '__app':self.doc.app } user_ns['grab_figure'] = self.grab_figure #I'll keep that for now, if we decide to go with initialization in profiles # # XXX Hack to preload matptlotlib. This will be moved out once we # # have restored ipython's profile support # # mplstart = """ #from pylab import * #switch_backend('WXAgg') #ion() #""" # exec mplstart in user_ns excepthook_orig = sys.excepthook self.interp = Shell.IPShellGUI(argv=['-colors', 'NoColor'], user_ns=user_ns) self.interp_log = self.interp.IP.log def donothing(*args, **kwds): pass self.interp.IP.log = donothing del self.interp.IP.input_hist[0] self.excepthook_IP = sys.excepthook sys.excepthook = excepthook_orig #Set up the number 0 cell. It is used for code which is not supposed to #be edited. And it has to be hidden #etree.dump(self.log) #dbg if not self.log: #This is a new log self.Append(input=""" ############DO NOT EDIT THIS CELL############ from pylab import * switch_backend('WXAgg') ion() """, number=0) self.Run() elif self.log[0] is not None: self.__run(self.Get(0)) #Append the empty element at the end self.SetLastInput() del __builtin__
def _test(self,argv,ans): shell = Shell._select_shell(argv) err = 'Got %s != %s' % (shell,ans) self.failUnlessEqual(shell,ans,err)
class Shell(CommandWithDB): """Convenient version of the Python interactive shell. This shell attempts to locate your configuration file and model module so that it can import everything from your model and make it available in the Python shell namespace. """ desc = "Start a Python prompt with your database available" need_project = True def run(self): """Run the shell""" self.find_config() locals = dict(__name__="tg-admin") try: mod = get_model() if mod: locals.update(mod.__dict__) except (pkg_resources.DistributionNotFound, ImportError), e: mod = None print "Warning: Failed to import your data model: %s" % e print "You will not have access to your data model objects." print if config.get("sqlalchemy.dburi"): using_sqlalchemy = True database.bind_metadata() locals.update(session=database.session, metadata=database.metadata) else: using_sqlalchemy = False class CustomShellMixin(object): def commit_changes(self): if mod: # XXX Can we check somehow, if there are actually any # database changes to be commited? r = raw_input("Do you wish to commit" " your database changes? [yes]") if not r.startswith("n"): if using_sqlalchemy: self.push("session.flush()") else: self.push("hub.commit()") try: # try to use IPython if possible from IPython import iplib, Shell class CustomIPShell(iplib.InteractiveShell, CustomShellMixin): def raw_input(self, *args, **kw): try: # needs decoding (see below)? return iplib.InteractiveShell.raw_input( self, *args, **kw) except EOFError: self.commit_changes() raise EOFError shell = Shell.IPShell(user_ns=locals, shell_class=CustomIPShell) shell.mainloop() except ImportError: import code class CustomShell(code.InteractiveConsole, CustomShellMixin): def raw_input(self, *args, **kw): try: import readline except ImportError: pass try: r = code.InteractiveConsole.raw_input( self, *args, **kw) for encoding in (getattr(sys.stdin, 'encoding', None), sys.getdefaultencoding(), 'utf-8', 'latin-1'): if encoding: try: return r.decode(encoding) except UnicodeError: pass return r except EOFError: self.commit_changes() raise EOFError shell = CustomShell(locals=locals) shell.interact()
def do_ipshell(self, line): ipshell = Shell.IPShellEmbed() ipshell()
def execute(self, *args): ipshell = Shell.IPShellEmbed() ipshell()
def help(self): for item in APIREF.items(): print "%s\t%s" % item if __name__ == '__main__': nargs = len(sys.argv[1:]) if nargs < 2 or nargs > 3: print "usage: %s username password [machine]" % sys.argv[0] sys.exit() banner = """ A convenient Webfaction api wrapper See docs: http://docs.webfaction.com/xmlrpc-api/apiref.html Available objects: api example: api.create_createdb api.list_dbs() api.system('ls') api.help() Just do not use session_id parameter that it is already added to each api call.""" try: api = Webfaction(*sys.argv[1:]) except xmlrpclib.Fault, e: print >> sys.stderr, "RPC Error: %s" % e else: from IPython import Shell Shell.IPShellEmbed([], banner)()
def ipython(): from IPython import Shell Shell.IPShellEmbed(argv=['-noconfirm_exit'])()
def _test(self, argv, ans): shell = Shell._select_shell(argv) err = 'Got %s != %s' % (shell, ans) self.failUnlessEqual(shell, ans, err)
class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--ipython', action='store_true', dest='ipython', help='Tells Django to use IPython, not BPython.'), make_option( '--plain', action='store_true', dest='plain', help='Tells Django to use plain Python, not BPython nor IPython.'), make_option('--no-pythonrc', action='store_true', dest='no_pythonrc', help='Tells Django to use plain Python, not IPython.'), make_option('--print-sql', action='store_true', default=False, help="Print SQL queries as they're executed"), make_option( '--dont-load', action='append', dest='dont_load', default=[], help= 'Ignore autoloading of some apps/models. Can be used several times.' ), ) help = "Like the 'shell' command but autoloads the models of all installed Django apps." requires_model_validation = True def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. (this is fixed by now, but leaving it here # for people using 0.96 or older trunk (pre [5919]) versions. from django.db.models.loading import get_models, get_apps loaded_models = get_models() use_ipython = options.get('ipython', False) use_plain = options.get('plain', False) use_pythonrc = not options.get('no_pythonrc', True) if options.get("print_sql", False): # Code from http://gist.github.com/118990 from django.db.backends import util try: import sqlparse except ImportError: sqlparse = None class PrintQueryWrapper(util.CursorDebugWrapper): def execute(self, sql, params=()): try: return self.cursor.execute(sql, params) finally: raw_sql = self.db.ops.last_executed_query( self.cursor, sql, params) if sqlparse: print sqlparse.format(raw_sql, reindent=True) else: print raw_sql print util.CursorDebugWrapper = PrintQueryWrapper # 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. from django.conf import settings imported_objects = {'settings': settings} dont_load_cli = options.get( 'dont_load') # optparse will set this to [] if it doensnt exists dont_load_conf = getattr(settings, 'SHELL_PLUS_DONT_LOAD', []) dont_load = dont_load_cli + dont_load_conf model_aliases = getattr(settings, 'SHELL_PLUS_MODEL_ALIASES', {}) for app_mod in get_apps(): app_models = get_models(app_mod) if not app_models: continue app_name = app_mod.__name__.split('.')[-2] if app_name in dont_load: continue app_aliases = model_aliases.get(app_name, {}) model_labels = [] for model in app_models: try: imported_object = getattr( __import__(app_mod.__name__, {}, {}, model.__name__), model.__name__) model_name = model.__name__ if "%s.%s" % (app_name, model_name) in dont_load: continue alias = app_aliases.get(model_name, model_name) imported_objects[alias] = imported_object if model_name == alias: model_labels.append(model_name) else: model_labels.append("%s (as %s)" % (model_name, alias)) except AttributeError, e: print self.style.ERROR( "Failed to import '%s' from '%s' reason: %s" % (model.__name__, app_name, str(e))) continue print self.style.SQL_COLTYPE( "From '%s' autoload: %s" % (app_mod.__name__.split('.')[-2], ", ".join(model_labels))) try: if use_plain: # Don't bother loading B/IPython, because the user wants plain Python. raise ImportError try: if use_ipython: # User wants IPython raise ImportError from bpython import embed embed(imported_objects) except ImportError: # Explicitly pass an empty list as arguments, because otherwise IPython # would use sys.argv from this script. try: from IPython import embed embed(user_ns=imported_objects) except ImportError: from IPython import Shell shell = Shell.IPShell(argv=[], user_ns=imported_objects) shell.mainloop() except ImportError: # Using normal Python shell 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 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 import user. if use_pythonrc: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
label = "knows" created = DateTime(default=current_datetime, nullable=False) #from people import Person, Knows from bulbs.neo4jserver import Graph def build_parser(): parser = argparse.ArgumentParser(conflict_handler='resolve') parser.add_argument('-w', '--worker', action='store_true') return parser if __name__ == '__main__': parser = build_parser() args = parser.parse_args() g = Graph() g.config.set_logger(DEBUG) g.add_proxy("people", Person) g.add_proxy("knows", Knows) james = g.people.create(name="James") julie = g.people.create(name="Julie") relationship = g.knows.create(james, julie) friends = james.outV('knows') friends = julie.inV('knows') print relationship.data() from IPython import Shell Shell.IPShellEmbed(argv=['-noconfirm_exit'])()