def __init__(self, master=None, **kw): font_specs = ("courier", 14) kw.setdefault('width', 83) kw.setdefault('height', 43) kw.setdefault('font', font_specs) kw.setdefault('wrap', 'word') kw.setdefault('prompt1', 'Dip> ') kw.setdefault('prompt2', '... ') banner = kw.pop('banner', 'Dip Version 0.1 - Beta\nType "help", "copyright", "credits" or "about" for more information.\n\n') self._prompt1 = kw.pop('prompt1') self._prompt2 = kw.pop('prompt2') tk.Text.__init__(self, master, **kw) # --- history self.history = History() self._hist_item = 0 self._hist_match = '' # --- initialization self._console = InteractiveConsole() # python console to execute commands self.insert('end', banner, 'banner') self.prompt() self.mark_set('input', 'insert') self.mark_gravity('input', 'left') # --- bindings self.bind('<Control-Return>', self.on_ctrl_return) self.bind('<Shift-Return>', self.on_shift_return) self.bind('<KeyPress>', self.on_key_press) self.bind('<KeyRelease>', self.on_key_release) self.bind('<Tab>', self.on_tab) self.bind('<Down>', self.on_down) self.bind('<Up>', self.on_up) self.bind('<Return>', self.on_return) self.bind('<BackSpace>', self.on_backspace) self.bind('<Control-c>', self.on_ctrl_c) self.bind('<<Paste>>', self.on_paste)
def __init__(self, master, **kw): kw.setdefault('width', 50) kw.setdefault('wrap', 'word') kw.setdefault('prompt1', '>>> ') kw.setdefault('prompt2', ' ') banner = kw.pop('banner', 'Python %s\n' % sys.version) self._prompt1 = kw.pop('prompt1') self._prompt2 = kw.pop('prompt2') ColorText.__init__(self, master, **kw) self.linenumbers.pack_forget() # --- history self.history = History() self._hist_item = 0 self._hist_match = '' # --- initialization self._console = InteractiveConsole( ) # python console to execute commands self.insert('end', banner, 'banner') self.prompt() self.mark_set('input', 'insert') self.mark_gravity('input', 'left') # --- bindings self.bind('<Control-Return>', self.on_ctrl_return) self.bind('<Shift-Return>', self.on_shift_return) self.bind('<KeyPress>', self.on_key_press) self.bind('<KeyRelease>', self.on_key_release) self.bind('<Tab>', self.on_tab) self.bind('<Down>', self.on_down) self.bind('<Up>', self.on_up) self.bind('<Return>', self.on_return) self.bind('<BackSpace>', self.on_backspace) self.bind('<Control-c>', self.on_ctrl_c) self.bind('<<Paste>>', self.on_paste) self.unbind('<Control-Shift-Home>') self.unbind('<Control-Shift-End>')
def debug_breakpoint(): """ Python debug breakpoint. Python script stopes here and gives back controll to the user. All variables and namespaces stay intacted for debugging. """ from code import InteractiveConsole from inspect import currentframe try: import readline # noqa except ImportError: pass caller = currentframe().f_back env = {} env.update(caller.f_globals) env.update(caller.f_locals) shell = InteractiveConsole(env) shell.interact('* Break: {} ::: Line {}\n' '* Continue with Ctrl+D or raise SystemExit...'.format( caller.f_code.co_filename, caller.f_lineno))
def _start_repl(api): # type: (Iota) -> None """ Starts the REPL. """ banner = ( 'IOTA API client for {uri} ({testnet}) initialized as variable `api`.\n' 'Type `help(api)` for list of API commands.'.format( testnet='testnet' if api.testnet else 'mainnet', uri=api.adapter.get_uri(), )) scope_vars = {'api': api} try: # noinspection PyUnresolvedReferences import IPython except ImportError: # IPython not available; use regular Python REPL. from code import InteractiveConsole InteractiveConsole(locals=scope_vars).interact(banner, '') else: print(banner) IPython.start_ipython(argv=[], user_ns=scope_vars)
def handle(self, conn, address): f = getcurrent()._fileobj = _fileobject(conn) f.stderr = self.stderr getcurrent().switch_in() try: console = InteractiveConsole(self.locals) # __builtins__ may either be the __builtin__ module or # __builtin__.__dict__ in the latter case typing # locals() at the backdoor prompt spews out lots of # useless stuff try: import __builtin__ except ImportError: import builtins as __builtin__ console.locals["__builtins__"] = __builtin__ console.interact(banner=self.banner) except SystemExit as ex: # raised by quit() if PY3: ex.__traceback__ = None else: sys.exc_clear() finally: conn.close() f.close()
def run(options): db_name = options.database_name pool = Pool(db_name) with Transaction().start(db_name, 0, readonly=True): pool.init() with Transaction().start(db_name, 0, readonly=options.readonly) as transaction: local = { 'pool': pool, 'transaction': transaction, } if sys.stdin.isatty(): console = Console(local, histsize=options.histsize) banner = "Tryton %s, Python %s on %s" % (__version__, sys.version, sys.platform) console.interact(banner=banner, exitmsg='') else: console = InteractiveConsole(local) console.runcode(sys.stdin.read()) transaction.rollback() while transaction.tasks: task_id = transaction.tasks.pop() run_task(pool, task_id)
def run_classic_shell(globals, locals): if SHELL_FIRST_TIME: banner = "Hit Ctrl-D to return to PuDB." SHELL_FIRST_TIME.pop() else: banner = "" ns = SetPropagatingDict([locals, globals], locals) from pudb.settings import get_save_config_path from os.path import join hist_file = join(get_save_config_path(), "shell-history") try: import readline import rlcompleter have_readline = True except ImportError: have_readline = False if have_readline: readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") readline.clear_history() try: readline.read_history_file(hist_file) except OSError: pass from code import InteractiveConsole cons = InteractiveConsole(ns) cons.interact(banner) if have_readline: readline.write_history_file(hist_file)
def init_interpreter(self): self.interp_setup_done = False self.interp_history = [] self.interp_history_lineno = 0 le = self.ui.lineedit_interpreter_input te = self.ui.textedit_interpreter_output le.installEventFilter(self) le.editingFinished.connect(self.handle_interp_line) self.PS1 = '>>> ' self.PS2 = '... ' self.interp_prompt = self.PS1 le.setText(self.interp_prompt) le.textEdited.connect(self.handle_interp_key) class Output: def __init__(self, textedit=te, err=False): self.textedit = te self.err = err def write(self, text): text = text.rstrip() if text: cursor = te.textCursor() cursor.movePosition(cursor.End) char_format = QtGui.QTextCharFormat() char_format.setForeground(QtGui.QColor('red' if self.err else 'black')) cursor.setCharFormat(char_format) cursor.insertText(text+'\n') #te.ensureCursorVisible() #scrollbar = te.verticalScrollBar() # this scrolls too far #scrollbar.setValue(scrollbar.maximum()) self.stdout = Output() self.stderr = Output(err=True) self.interp = InteractiveConsole() banner = 'Python ' + sys.version + ' on ' + sys.platform + '\n' banner += 'MFiX-GUI version %s' % __version__ + '\n' te.insertPlainText(banner)
def debug_breakpoint(): """ Python debug breakpoint. """ from code import InteractiveConsole from inspect import currentframe try: import readline # noqa except ImportError: pass caller = currentframe().f_back env = {} env.update(caller.f_globals) env.update(caller.f_locals) shell = InteractiveConsole(env) shell.interact( '* Break: {} ::: Line {}\n' '* Continue with Ctrl+D...'.format( caller.f_code.co_filename, caller.f_lineno ) )
print "\nr0=GenerateFitAndPlot(configMgr.topLvls[0])" print "r1=GenerateFitAndPlot(configMgr.topLvls[1])" print "r2=GenerateFitAndPlot(configMgr.topLvls[2])" pass if printLimits: configMgr.cppMgr.doUpperLimitAll() #for tl in configMgr.topLvls: # GetLimits(tl,f) # pass pass if doHypoTests: configMgr.cppMgr.doHypoTestAll() pass if configMgr.nTOYs>0 and doHypoTests==False and printLimits==False and runFit==False: RooRandom.randomGenerator().SetSeed( configMgr.toySeed ) configMgr.cppMgr.runToysAll() pass if runInterpreter: from code import InteractiveConsole from ROOT import Util cons = InteractiveConsole(locals()) cons.interact("Continuing interactive session... press Ctrl+d to exit") pass print "Leaving HistFitter... Bye!"
if __name__ == '__main__': fname = "load-csv.csv" data = load_csv(fname, header_row=2) print( ('Data has been loaded from "%s" into the "data" dictionary.' % fname)) print("It contains these keys:") print((list(data.keys()))) print("Use the Python prompt to explore the data.") # Embed an IPython or standard Python interpreter. # Based on # http://writeonly.wordpress.com/2008/09/08/embedding-a-python-shell-in-a-python-script/, # accessed 2010/11/2 try: # IPython from IPython import embed embed() except ImportError: try: # IPython via old API style from IPython.Shell import IPShellEmbed IPShellEmbed(argv=['-noconfirm_exit'])() # Note: The -pylab option can't be embedded (see # http://article.gmane.org/gmane.comp.python.ipython.user/1190/match=pylab). except ImportError: # Standard Python from code import InteractiveConsole InteractiveConsole(globals()).interact()
def start_backend(data, save): # this will modify the backendlocals to contain the actual backendlocals. # it is used in create(T), to eval() stuff like 'data["kinepolis"]...' global backendlocals console = InteractiveConsole() backendlocals = { "switchDataStructure": switchDataStructure, "data": data, "save": save, "create": create, "example_cinema": example_cinema, } backendlocals.update(classes.__dict__) # add module classes to console backendlocals.update(datastruct.__dict__) # add module datastruct to console backendlocals.update(sorting.__dict__) # add module sorting to console backendlocals.update(origlocals) # reset the stuff that might otherwise be modifed by importing other modules (like __package__ and __name__) console.locals = backendlocals console.locals['credits'] = type(credits)("credits", "\n\n"+fancytext("Anthony")+"\n\n"+fancytext("Pieter")+"\n\n"+fancytext("Stijn")+"\n\n"+fancytext("Evert")) # OMG Tab completion!!! readline.set_completer(rlcompleter.Completer(console.locals).complete) if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") # Hi, I'm an Apple computer and I'm special. else: readline.parse_and_bind("tab: complete") # Hi, I'm a Linux computer and things just work for me. # OMG own modification to rlcompleter #readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>/?') # original readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+{]}\\|;:,<>/?') # no [,' or " in here! # even more imports console.push("import datetime") while True: # no more color for input, too much bugs c = input("> ") if c == "q": return # exit else: try: if console.push(c): # console.push(c) executes the string c in the console. # if it is True, it means it expects more input (for example a function definition) _input = ' ' totalcommand = '' while _input!='': _input = input('. ') totalcommand += _input+'\n' console.push(totalcommand) except Exception as e: print(rgbtext('Error: %s'%e)) console.resetbuffer() backendlocals = console.locals # again for create(T)
#!/usr/bin/env python from warnings import catch_warnings, simplefilter with catch_warnings(): simplefilter('ignore') from psycopg2 import connect from psycopg2.extras import NamedTupleCursor from contextlib import closing from code import InteractiveConsole from os import environ from rlcompleter import readline DBNAME = environ.get('DBNAME', 'nc') DBHOST = environ.get('DBHOST', None) DBUSER = environ.get('DBUSER', 'postgres') DBPARAMS = {'dbname': DBNAME, 'user': DBUSER} if DBHOST is not None: DBPARAMS['host'] = DBHOST if __name__ == '__main__': with closing(connect(**DBPARAMS, cursor_factory=NamedTupleCursor)) as db: db.set_session(autocommit=True) with db.cursor() as cur: def q(query): cur.execute(query) return [row for row in cur] readline.parse_and_bind('tab:complete') InteractiveConsole(locals=globals()).interact('')
def __init__(self, mainThread, connect_status_queue=None, rpc_client=None): BaseInterpreterInterface.__init__(self, mainThread, connect_status_queue, rpc_client) self.namespace = {} self.save_main() self.interpreter = InteractiveConsole(self.namespace) self._input_error_printed = False
from threading import Thread from time import sleep import friendly_traceback.source_cache import stack_data from main import simple_settings from main.exercises import assert_equal from main.text import pages from main.workers.limits import set_limits from main.workers.tracebacks import TracebackSerializer, print_friendly_syntax_error from main.workers.utils import internal_error_result, make_result, output_buffer log = logging.getLogger(__name__) console = InteractiveConsole() console.locals = {"assert_equal": assert_equal} def execute(code_obj): sys.setrecursionlimit(100) try: # noinspection PyTypeChecker exec(code_obj, console.locals) except Exception as e: sys.setrecursionlimit(1000) return TracebackSerializer().format_exception(e) finally: sys.setrecursionlimit(1000)
def __init__(self, args=None, description=None, usage=None, interspersed=False, nr=None, changeVersion=True, exactNr=True, subcommands=None, inputApp=None, **kwArgs): """ @param description: description of the command @param usage: Usage @param interspersed: Is the command line allowed to be interspersed (options after the arguments) @param args: Command line arguments when using the Application as a 'class' from a script @param nr: Number of required arguments @param changeVersion: May this application change the version of OF used? @param exactNr: Must not have more than the required number of arguments @param subcommands: parse and use subcommands from the command line. Either True or a list with subcommands @param inputApp: Application with input data. Used to allow a 'pipe-like' behaviour if the class is used from a Script """ if subcommands: self.subs = True if interspersed: self.error( "Subcommand parser does not work with 'interspersed'") if subcommands == True: subcommands = [] self.parser = SubcommandFoamOptionParser(args=args, description=description, usage=usage, subcommands=subcommands) nr = None exactNr = False else: self.subs = False self.parser = FoamOptionParser(args=args, description=description, usage=usage, interspersed=interspersed) self.calledName = sys.argv[0] self.calledAsClass = (args != None) if self.calledAsClass: self.calledName = self.__class__.__name__ + " used by " + sys.argv[ 0] self.parser.prog = self.calledName self.generalOpts = None self.__appData = self.iDict() if inputApp: self.__appData["inputData"] = inputApp.getData() grp = OptionGroup(self.parser, "Default", "Options common to all PyFoam-applications") if changeVersion: # the options are evaluated in Basics.FoamOptionParser grp.add_option( "--foamVersion", dest="foamVersion", default=None, help= "Change the OpenFOAM-version that is to be used. To get a list of know Foam-versions use the pyFoamVersion.py-utility" ) if "WM_PROJECT_VERSION" in environ: grp.add_option("--currentFoamVersion", dest="foamVersion", const=environ["WM_PROJECT_VERSION"], default=None, action="store_const", help="Use the current OpenFOAM-version " + environ["WM_PROJECT_VERSION"]) grp.add_option( "--force-32bit", dest="force32", default=False, action="store_true", help= "Forces the usage of a 32-bit-version if that version exists as 32 and 64 bit. Only used when --foamVersion is used" ) grp.add_option( "--force-64bit", dest="force64", default=False, action="store_true", help= "Forces the usage of a 64-bit-version if that version exists as 32 and 64 bit. Only used when --foamVersion is used" ) grp.add_option( "--force-debug", dest="compileOption", const="Debug", default=None, action="store_const", help= "Forces the value Debug for the WM_COMPILE_OPTION. Only used when --foamVersion is used" ) grp.add_option( "--force-opt", dest="compileOption", const="Opt", default=None, action="store_const", help= "Forces the value Opt for the WM_COMPILE_OPTION. Only used when --foamVersion is used" ) grp.add_option( "--force-system-compiler", dest="foamCompiler", const="system", default=None, action="store_const", help= "Force using a 'system' compiler (compiler installed in the system)" ) grp.add_option( "--force-openfoam-compiler", dest="foamCompiler", const="OpenFOAM", default=None, action="store_const", help= "Force using a 'OpenFOAM' compiler (compiler installed in ThirdParty)" ) grp.add_option( "--force-compiler", dest="wmCompiler", default=None, action="store", help="Overwrite value for WM_COMPILER (for instance Gcc47 ...)" ) grp.add_option( "--psyco-accelerated", dest="psyco", default=False, action="store_true", help= "Accelerate the script using the psyco-library (EXPERIMENTAL and requires a separatly installed psyco)" ) grp.add_option( "--profile-python", dest="profilePython", default=False, action="store_true", help= "Profile the python-script (not the OpenFOAM-program) - mostly of use for developers" ) grp.add_option( "--profile-cpython", dest="profileCPython", default=False, action="store_true", help= "Profile the python-script (not the OpenFOAM-program) using the better cProfile library - mostly of use for developers" ) grp.add_option( "--profile-hotshot", dest="profileHotshot", default=False, action="store_true", help= "Profile the python-script using the hotshot-library (not the OpenFOAM-program) - mostly of use for developers - EXPERIMENTAL" ) dbg = OptionGroup( self.parser, "Debugging", "Options mainly used for debugging PyFoam-Utilities") dbg.add_option( "--traceback-on-error", dest="traceback", default=False, action="store_true", help= "Prints a traceback when an error is encountered (for debugging)") dbg.add_option( "--interactive-debugger", dest="interactiveDebug", default=False, action="store_true", help= "In case of an exception start the interactive debugger PDB. Also implies --traceback-on-error" ) dbg.add_option( "--catch-USR1-signal", dest="catchUSR1Signal", default=False, action="store_true", help= "If the USR1-signal is sent to the application with 'kill -USR1 <pid>' the application ens and prints a traceback. If interactive debugging is enabled then the debugger is entered. Use to investigate hangups" ) dbg.add_option("--also-catch-TERM-signal", dest="alsoCatchTERMsignal", default=False, action="store_true", help="In addition to USR1 catch the regular TERM-kill") dbg.add_option( "--keyboard-interrupt-trace", dest="keyboardInterrupTrace", default=False, action="store_true", help= "Make the application behave like with --catch-USR1-signal if <Ctrl>-C is pressed" ) dbg.add_option( "--syntax-error-debugger", dest="syntaxErrorDebugger", default=False, action="store_true", help= "Only makes sense with --interactive-debugger: Do interactive debugging even when a syntax error was encountered" ) dbg.add_option( "--i-am-a-developer", dest="developerMode", default=False, action="store_true", help= "Switch on all of the above options. Usually this makes only sense if you're developing PyFoam'" ) dbg.add_option( "--interactive-after-execution", dest="interacticeAfterExecution", default=False, action="store_true", help= "Instead of ending execution drop to an interactive shell (which is IPython if possible)" ) grp.add_option( "--dump-application-data", dest="dumpAppData", default=False, action="store_true", help= "Print the dictionary with the generated application data after running" ) grp.add_option("--pickle-application-data", dest="pickleApplicationData", default=None, action="store", type="string", help="""\ Write a pickled version of the application data to a file. If the filename given is 'stdout' then the pickled data is written to stdout. The usual standard output is then captured and added to the application data as an entry 'stdout' (same for 'stderr'). Be careful with these option for commands that generate a lot of output""") self.parser.add_option_group(grp) self.parser.add_option_group(dbg) self.addOptions() self.parser.parse(nr=nr, exactNr=exactNr) if len(kwArgs) > 0: self.parser.processKeywordArguments(kwArgs) self.opts = self.parser.getOptions() if self.subs: self.cmdname = self.parser.cmdname if "WM_PROJECT_VERSION" not in environ: warning( "$WM_PROJECT_VERSION unset. PyFoam will not be able to determine the OpenFOAM-version and behave strangely" ) if self.opts.developerMode: self.opts.syntaxErrorDebugger = True self.opts.keyboardInterrupTrace = True self.opts.alsoCatchTERMsignal = True self.opts.catchUSR1Signal = True self.opts.interactiveDebug = True self.opts.traceback = True if self.opts.interactiveDebug: sys.excepthook = lambda a1, a2, a3: pyFoamExceptionHook( a1, a2, a3, debugOnSyntaxError=self.opts.syntaxErrorDebugger) self.opts.traceback = True if self.opts.catchUSR1Signal: import signal signal.signal(signal.SIGUSR1, pyFoamSIG1HandlerPrintStack) if self.opts.alsoCatchTERMsignal: signal.signal(signal.SIGTERM, pyFoamSIG1HandlerPrintStack) self.opts.traceback = True if self.opts.keyboardInterrupTrace: import signal signal.signal(signal.SIGINT, pyFoamSIG1HandlerPrintStack) self.opts.traceback = True if self.opts.psyco: try: import psyco psyco.full() except ImportError: warning("No psyco installed. Continuing without acceleration") if self.opts.profilePython or self.opts.profileCPython or self.opts.profileHotshot: if sum([ self.opts.profilePython, self.opts.profileCPython, self.opts.profileHotshot ]) > 1: self.error( "Profiling with hotshot and regular profiling are mutual exclusive" ) print_("Running profiled") if self.opts.profilePython: import profile elif self.opts.profileCPython: import cProfile as profile else: import hotshot profileData = path.basename(sys.argv[0]) + ".profile" if self.opts.profilePython or self.opts.profileCPython: profile.runctx('self.run()', None, {'self': self}, profileData) print_("Reading python profile") import pstats stats = pstats.Stats(profileData) else: profileData += ".hotshot" prof = hotshot.Profile(profileData) prof.runctx('self.run()', {}, {'self': self}) print_("Writing and reading hotshot profile") prof.close() import hotshot.stats stats = hotshot.stats.load(profileData) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) self.parser.restoreEnvironment() else: try: if self.opts.pickleApplicationData == "stdout": # Redirect output to memory from PyFoam.ThirdParty.six.moves import StringIO oldStdout = sys.stdout oldStderr = sys.stderr sys.stdout = StringIO() sys.stderr = StringIO() result = self.run() # do this at the earliest possible moment self.parser.restoreEnvironment() if self.opts.pickleApplicationData == "stdout": # restore stdout self.__appData["stdout"] = sys.stdout.getvalue() self.__appData["stderr"] = sys.stderr.getvalue() sys.stdout = oldStdout sys.stderr = oldStderr if self.opts.pickleApplicationData: from PyFoam.ThirdParty.six.moves import cPickle as pickle if self.opts.pickleApplicationData == "stdout": pick = pickle.Pickler(sys.stdout) else: pick = pickle.Pickler( open(self.opts.pickleApplicationData, 'wb')) pick.dump(self.__appData) del pick if self.opts.dumpAppData: import pprint print_("Application data:") printer = pprint.PrettyPrinter() printer.pprint(self.__appData) if self.opts.interacticeAfterExecution: print_("\nDropping to interactive shell ... ", end="") ns = {} ns.update(locals()) ns.update(globals()) try: import IPython print_("found IPython ...", end="") if "embed" in dir(IPython): print_("up-to-date IPython\n") IPython.embed(user_ns=ns) else: print_("old-school IPython\n") IPython.Shell.IPythonShellEmbed(argv="", user_ns=ns)() except ImportError: print_("no IPython -> regular shell\n") from code import InteractiveConsole c = InteractiveConsole(ns) c.interact() print_("\nEnding interactive shell\n") return result except PyFoamException: e = sys.exc_info()[1] if self.opts.traceback or self.calledAsClass: raise else: self.errorPrint(str(e))
def __init__(self, globals): self.globals = globals self.console = InteractiveConsole(self.globals) self.prompt = ">>> "
def start_shell_thread(namespace, banner, prompt): return start_interaction_thread(InteractiveConsole(namespace).push, banner, prompt)
def __init__(self): super(CodeExecutor, self).__init__() self.namespace = {} self.interpreter = InteractiveConsole(self.namespace)
def handle_failure(error, suite, global_frame, interactive): """Handles a test failure. PARAMETERS: error -- TestException; contains information about the failed test suite -- int; suite number (for informational purposes) global_frame -- dict; global frame interactive -- bool; True if interactive mode is enabled DESCRIPTION: Expected output and actual output are checked with shallow equality (==). RETURNS: bool; True if error actually occurs, which should always be the case -- handle_failure should only be called if a test fails. """ print(underline('Test case failed:'.format(suite), under='-')) console = InteractiveConsole(locals=global_frame) incomplete = False for line in process_input(error.preamble): if not incomplete and not line: incomplete = False continue prompt = PS2 if incomplete else PS1 print(display_prompt(line, prompt)) incomplete = console.push(line) incomplete = False outputs = iter(error.outputs) lines = process_input(error.test_src) prompts = 0 for i, line in enumerate(lines): if line.startswith('$ ') or \ (i == len(lines) - 1 and prompts == 0): line = line.lstrip('$ ') prompt = PS2 if incomplete else PS1 print(display_prompt(line, prompt)) expect = eval(next(outputs), global_frame.copy()) try: actual = timed(eval, (line, global_frame.copy())) except RuntimeError: print('# Error: maximum recursion depth exceeded') if interactive: interact(console) print() return True except TimeoutError as e: print('# Error: evaluation exceeded {} seconds'.format(e.timeout)) return True except Exception as e: console.push(line) print('# Error: expected', expect, 'got', e.__class__.__name__) if interactive: interact(console) print() return True print(display_prompt(actual, prompt='')) if expect != actual: print('# Error: expected', expect, 'got', actual) if interactive: interact(console) print() return True incomplete = False else: if not incomplete and not line: incomplete = False continue prompt = PS2 if incomplete else PS1 print(display_prompt(line, prompt)) incomplete = console.push(line) print() return False
def __init__(self, host, client_port): self.client_port = client_port self.host = host self.namespace = globals() self.interpreter = InteractiveConsole(self.namespace)
def startInteractiveShell(self): vars = globals() vars.update(locals()) shell = InteractiveConsole(vars) shell.interact()
def get_console(console_id): """ helper function for console operators currently each text data block gets its own console - code.InteractiveConsole() ...which is stored in this function. console_id can be any hashable type """ from code import InteractiveConsole consoles = getattr(get_console, "consoles", None) hash_next = hash(bpy.context.window_manager) if consoles is None: consoles = get_console.consoles = {} get_console.consoles_namespace_hash = hash_next else: # check if clearing the namespace is needed to avoid a memory leak. # the window manager is normally loaded with new blend files # so this is a reasonable way to deal with namespace clearing. # bpy.data hashing is reset by undo so cant be used. hash_prev = getattr(get_console, "consoles_namespace_hash", 0) if hash_prev != hash_next: get_console.consoles_namespace_hash = hash_next consoles.clear() console_data = consoles.get(console_id) if console_data: console, stdout, stderr = console_data # XXX, bug in python 3.1.2, 3.2 ? (worked in 3.1.1) # seems there is no way to clear StringIO objects for writing, have to # make new ones each time. import io stdout = io.StringIO() stderr = io.StringIO() else: if _BPY_MAIN_OWN: import types bpy_main_mod = types.ModuleType("__main__") namespace = bpy_main_mod.__dict__ else: namespace = {} namespace["__builtins__"] = sys.modules["builtins"] namespace["bpy"] = bpy # weak! - but highly convenient namespace["C"] = bpy.context namespace["D"] = bpy.data replace_help(namespace) console = InteractiveConsole(locals=namespace, filename="<blender_console>") console.push("from mathutils import *") console.push("from math import *") if _BPY_MAIN_OWN: console._bpy_main_mod = bpy_main_mod import io stdout = io.StringIO() stderr = io.StringIO() consoles[console_id] = console, stdout, stderr return console, stdout, stderr
# Copyright © 2005-2016 EventGhost Project <http://www.eventghost.org/> # # EventGhost is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 2 of the License, or (at your option) # any later version. # # EventGhost is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along # with EventGhost. If not, see <http://www.gnu.org/licenses/>. import os import sys sys.path.append(os.getcwd()) if len(sys.argv) > 1: mainFilePath = os.path.abspath(sys.argv[1].encode('mbcs')) sys.argv = sys.argv[1:] sys.argv[0] = mainFilePath import types types.ModuleType("__main__", mainFilePath) else: if getattr(sys, "frozen", None) == "console_exe": from code import InteractiveConsole InteractiveConsole().interact()
def main(client, args=[]): console = InteractiveConsole({"tank": client}) console.interact(banner="TANKSH (%s%s)" % (client.__dict__['_ServerProxy__host'], client.__dict__['_ServerProxy__handler']))
# Note how we are connected result += 'Connected to %s' % cli.url if cli.creds is not None: result += ' as %s' % cli.creds[0] return result # Read previous command line history histfile = '%s/.wbemcli_history' % os.environ['HOME'] try: if have_readline: readline.read_history_file(histfile) except IOError, arg: if arg[0] != errno.ENOENT: raise # Interact i = InteractiveConsole(globals()) i.interact(get_banner()) # Save command line history if have_readline: readline.write_history_file(histfile)
def do_py(self, arg): ''' :: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive python mode is entered. The python mode can be ended with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``,'`exit()``. Non-python commands can be issued with ``cmd("your command")``. If the python code is located in an external file it can be run with ``run("filename.py")``. In case a COMMAND is provided it will be executed and the python interpreter will return to the command shell. This code is copied from Cmd2. ''' self.pystate['self'] = self arg = arg.strip() localvars = (self.locals_in_py and self.pystate) or {} interp = InteractiveConsole(locals=localvars) interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())') if arg: interp.runcode(arg) else: def quit(): raise EmbeddedConsoleExit def onecmd(arg): return self.onecmd(arg + '\n') def run(arg): try: file = open(arg) interp.runcode(file.read()) file.close() except IOError, e: self.perror(e) self.pystate['quit'] = quit self.pystate['exit'] = quit self.pystate['cmd'] = onecmd self.pystate['run'] = run try: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' keepstate = Statekeeper(sys, ('stdin', 'stdout')) sys.stdout = self.stdout sys.stdin = self.stdin interp.interact(banner="Python %s on %s\n%s\n(%s)\n%s" % (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) except EmbeddedConsoleExit: pass keepstate.restore()
def new_console(self, locals): """Creates and returns a new interactive console that implements the same interfaces as code.InteractiveConsole. Locals are copied before modification.""" return InteractiveConsole(locals.copy())
def handle_failure(error, test, suite_number, global_frame, interactive): """Handles a test failure. PARAMETERS: error -- TestError; contains information about the failed test test -- dict; contains information about the test suite_number -- int; suite number (for informational purposes) global_frame -- dict; global frame interactive -- bool; True if interactive mode is enabled DESCRIPTION: Expected output and actual output are checked with shallow equality (==). RETURNS: bool; True if error actually occurs, which should always be the case -- handle_failure should only be called if a test fails. """ code_source, outputs = error.get(test, suite_number) underline('Test case failed:', under='-') try: compile(code_source.replace('$ ', ''), 'Test {} suite {} case {}'.format(get_name(test), suite_number, error.case), 'exec') except SyntaxError as e: print('SyntaxError:', e) return global_frame console = InteractiveConsole(locals=global_frame) if type(outputs) == str: outputs = (outputs,) out_iter = iter(outputs) current, prompts = '', 0 lines = split(code_source) + [''] for i, line in enumerate(lines): if line.startswith(' ') or compile_command(current.replace('$ ', '')) is None: current += line + '\n' display_prompt(line.replace('$ ', ''), PS2) continue if current.startswith('$ ') or \ (i == len(lines) - 1 and prompts == 0): try: expect = handle_test(eval, (next(out_iter), global_frame.copy()), console=console, current=current, interactive=interactive) actual = handle_test(eval, (current.replace('$ ', ''), global_frame), console=console, current=current, interactive=interactive, expect=expect) except TestError: return global_frame display_prompt(actual, '') if expect != actual: print('# Error: expected', repr(expect), 'got', repr(actual)) if interactive: interact(console) print() return global_frame else: try: handle_test(exec, (current, global_frame), console=console, current=current, interactive=interactive) except TestError: return global_frame current = '' if line.startswith('$ '): prompts += 1 current += line + '\n' display_prompt(line.replace('$ ', ''), PS1) print() return global_frame
def console(**kwargs): """ An REPL fully configured for experimentation. usage: blueberrypy console [options] options: -e ENVIRONMENT, --environment=ENVIRONMENT apply the given config environment -C ENV_VAR_NAME, --env-var ENV_VAR_NAME add the given config from environment variable name [default: BLUEBERRYPY_CONFIG] --ipython use IPython shell instead of Python one -h, --help show this help message and exit """ banner = """ ***************************************************************************** * If the configuration file you specified contains a [sqlalchemy_engine*] * * section, a default SQLAlchemy engine and session should have been created * * for you automatically already. * ***************************************************************************** """ environment = kwargs.get("environment") config_dir = kwargs.get("config_dir") environment and cherrypy.config.update({"environment": environment}) configuration = BlueberryPyConfiguration( config_dir=config_dir, environment=environment, env_var_name=kwargs.get('env_var'), ) use_ipython = kwargs.get("ipython", False) package_name = shell.get_package_name(configuration) if use_ipython: try: from IPython.terminal.interactiveshell import TerminalInteractiveShell except ImportError as e: print(e) print("""Cannot import iPython. Did you install it?""") return try: app_package = import_module(package_name) except ImportError as e: print(e) app_package = None repl = TerminalInteractiveShell( user_ns=shell.get_user_namespace(configuration), user_module=app_package, display_completions='multicolumn', # oldstyle is 'readlinelike' mouse_support=True, space_for_menu=10, # reserve N lines for the completion menu ) repl.show_banner(banner) repl.mainloop() else: try: import readline except ImportError as e: print(e) else: import rlcompleter sys.ps1 = "[%s]>>> " % package_name sys.ps2 = "[%s]... " % package_name ns = shell.get_user_namespace(configuration, include_pkg=True) repl = InteractiveConsole(locals=ns) repl.prompt = package_name repl.interact(banner)