def dbg_interact(lcls, gbls): intro = "Let's interact!" try: import IPython.Shell ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls) print(intro) ipsh.mainloop() except ImportError as e: try: from IPython.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! print(intro) ipsh.mainloop() except ImportError as e: try: from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! print(intro) ipsh.mainloop() except ImportError, e: print(e) shell = code.InteractiveConsole(gbls) print(intro) shell.interact()
def dbg_interact(lcls, gbls, intro=None): shelltype = STYPE_NONE if intro is None: intro = "Let's interact!" print(intro) try: from IPython import embed shelltype = STYPE_IPYTHON_NEW except ImportError as e: try: import IPython.Shell ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls) shelltype = STYPE_IPYTHON except ImportError as e: try: from IPython.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! shelltype = STYPE_IPYTHON except ImportError as e: try: from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! shelltype = STYPE_IPYTHON except ImportError as e: print(e) shell = code.InteractiveConsole(gbls) shelltype = STYPE_IPYTHON if shelltype == STYPE_IPYTHON_NEW: globals().update(gbls) locals().update(lcls) embed() elif shelltype == STYPE_IPYTHON: ipsh.mainloop() elif shelltype == STYPE_CODE_INTERACT: shell.interact() else: print("SORRY, NO INTERACTIVE OPTIONS AVAILABLE!! wtfo?")
def interactive(idx=0, DongleClass=RfCat, intro=''): global d import rflib.chipcon_nic as rfnic import atexit d = DongleClass(idx=idx) d.setModeRX() # this puts the dongle into receive mode atexit.register(cleanupInteractiveAtExit) gbls = globals() lcls = locals() shellfailed = False try: from IPython.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! print(intro) ipsh.mainloop() except ImportError as e: shellfailed = True if shellfailed: try: import IPython.Shell ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls) print(intro) ipsh.mainloop() except ImportError as e: shellfailed = True if shellfailed: try: from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! print(intro) ipsh.mainloop() except ImportError as e: shellfailed = True if shellfailed: print("falling back to straight Python... (%r)" % e) shell = code.InteractiveConsole(gbls) print(intro) shell.interact()
def shell(): from api.app import rowboat namespace = {} try: from IPython.terminal.interactiveshell import TerminalInteractiveShell console = TerminalInteractiveShell(user_ns=namespace) print 'Starting iPython Shell' except ImportError: import code import rlcompleter c = rlcompleter.Completer(namespace) # Setup readline for autocomplete. try: # noinspection PyUnresolvedReferences import readline readline.set_completer(c.complete) readline.parse_and_bind('tab: complete') readline.parse_and_bind('set show-all-if-ambiguous on') readline.parse_and_bind('"\C-r": reverse-search-history') readline.parse_and_bind('"\C-s": forward-search-history') except ImportError: pass console = code.InteractiveConsole(namespace) print 'Starting Poverty Shell (install IPython to use improved shell)' with rowboat.app.app_context(): console.interact()
def __call__(self): from IPython.terminal.prompts import Prompts, Token from IPython.terminal.interactiveshell import TerminalInteractiveShell token = self._token class RFQuackShellPrompts(Prompts): def in_prompt_tokens(self, cli=None): return [(Token, token), (Token.Prompt, '> ')] TerminalInteractiveShell.prompts_class = RFQuackShellPrompts shell = TerminalInteractiveShell() shell.autocall = 0 shell.show_banner(self._banner) q = RFQuack(self._transport, "rfquack", shell, self._select_first_dongle) shell_objs = dict(q=q, pb=rfquack_pb2) # For each message field add a fake object with the same name, # this to achieve a **very basic** autocomp. for message_type in rfquack_pb2.DESCRIPTOR.message_types_by_name.values( ): for message_field in message_type.fields: shell_objs[ message_field. name] = "This is a fake variable, used for autocompletion" shell.push(shell_objs) shell.mainloop()
def interactive(idx=0, DongleClass=RfCat, intro=''): global d import rflib.chipcon_nic as rfnic import atexit d = DongleClass(idx=idx) d.setModeIDLE() # this puts the dongle into Idle mode atexit.register(cleanupInteractiveAtExit) gbls = globals() lcls = locals() try: import IPython.Shell ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls) print intro ipsh.mainloop(intro) except ImportError, e: try: from IPython.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! ipsh.mainloop(intro) except ImportError, e: print e shell = code.InteractiveConsole(gbls) shell.interact(intro)
def repl(ctx, config, community, network, keyfile, password, trezor, trezor_path, derivation_path, chain, artifactdir, input, timeout): config = Config.from_yaml(config, Chain.from_str(chain)) if network not in config.network_configs: click.echo('No such network {0} defined, check configuration', network) sys.exit(1) network = configure_network(config, network, keyfile, password, trezor, trezor_path, derivation_path) deployer = Deployer(community, network, artifactdir) # Default to homechain.json/sidechain.json if not input: input = chain + 'chain.json' click.echo('Waiting for deployment results') if not wait_for_file(input, timeout): click.echo('Timeout waiting for deployment results file') sys.exit(1) with open(input, 'r') as f: deployer.load_results(f) user_ns = { 'config': config, 'network': network, 'deployer': deployer, } shell = TerminalInteractiveShell(user_ns=user_ns) shell.mainloop()
def init_shell(self): self.shell = TerminalInteractiveShell(prompts_class=MyPrompt, highlighting_style='emacs', display_banner=False, profile_dir=self.profile_dir, ipython_dir=self.ipython_dir, banner1=get_banner(), banner2='') self.shell.configurables.append(self)
def setUp(self) -> None: super().setUp() ip = get_ipython() if ip is None: ip = TerminalInteractiveShell().instance() self.ip = ip self.ip.magic('load_ext graph_notebook.magics') self.ip.run_cell_magic('graph_notebook_config', '', json.dumps(self.config.to_dict()))
def interact(lcls, gbls): shellexception = None try: from IPython.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! ipsh.mainloop() except ImportError as e: shellexception = e if shellexception: try: import IPython.Shell ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls) ipsh.mainloop() except ImportError as e: shellexception = e if shellexception: try: from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(gbls) ipsh.user_global_ns.update(lcls) ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart! ipsh.mainloop() except ImportError as e: shellexception = e if shellexception: print("falling back to straight Python... (%r)" % shellexception) shell = code.InteractiveConsole(gbls) shell.interact()
def get_jeanmishell(): try: import IPython.Shell return IPython.Shell.IPShell(argv=[''], user_ns=locals(), user_global_ns=globals()) except ImportError as e: try: from IPython.terminal.interactiveshell import TerminalInteractiveShell except ImportError: try: from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell except ImportError: return None ipsh = TerminalInteractiveShell() ipsh.user_global_ns.update(globals()) ipsh.user_global_ns.update(locals()) ipsh.autocall = 2 return ipsh
def get_python_console(namespace=None): """ Return a interactive python console instance with caller's stack """ if namespace is None: import inspect frame = inspect.currentframe() caller = frame.f_back if not caller: logging.error("can't find caller who start this console.") caller = frame namespace = dict(caller.f_globals) namespace.update(caller.f_locals) try: from IPython.terminal.interactiveshell import TerminalInteractiveShell shell = TerminalInteractiveShell(user_ns=namespace) except ImportError: try: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(namespace).complete) readline.parse_and_bind("tab: complete") except ImportError: pass import code shell = code.InteractiveConsole(namespace) shell._quit = False def exit(): shell._quit = True def readfunc(prompt=""): if shell._quit: raise EOFError return six.moves.input(prompt) # inject exit method shell.ask_exit = exit shell.raw_input = readfunc return shell
def __call__(self): from IPython.terminal.prompts import Prompts, Token from IPython.terminal.interactiveshell import TerminalInteractiveShell token = self._token class RFQuackShellPrompts(Prompts): def in_prompt_tokens(self, cli=None): return [(Token, token), (Token.Prompt, '> ')] TerminalInteractiveShell.prompts_class = RFQuackShellPrompts shell = TerminalInteractiveShell() shell.autocall = 2 shell.show_banner(self._banner) q = RFQuack(self._transport, shell) q.idle() shell.push(dict(q=q, rfquack_pb2=rfquack_pb2)) shell.mainloop()
def post_mortem(self): try: traceback.print_exc() tb = sys.exc_info()[2] if self.force_ipdb or is_ipython(): # https://github.com/gotcha/ipdb/blob/master/ipdb/__main__.py from IPython.terminal.interactiveshell import ( TerminalInteractiveShell) p = TerminalInteractiveShell().debugger_cls() p.botframe = sys._getframe().f_back # I do not know why this # is nessesary, but without this hack it does not work p.interaction(None, tb) else: pdb.post_mortem(tb) except Exception as e: print('#' * 40) print('debug_on does not alwais work with sacred. ' 'Use -D for sacred applications') print('#' * 40) raise e
def example_notebook(extra_flags_as_one_string=None): r""" Open the example notebook in the default browser. The ipython terminal stays active while the notebook is still active. Ctr+C in the ipython terminal will close the notebook. Note: This notebook is a working copy of the original notebook. Feel free to mess around with it """ from IPython.terminal.interactiveshell import TerminalInteractiveShell import shutil, os origfile = _molpxdir('notebooks/Projection_Explorer.ipynb') with TemporaryDirectory(suffix='_test_molpx_notebook') as tmpdir: tmpfile = os.path.abspath( os.path.join(tmpdir, 'Projection_Explorer.ipynb')) shutil.copy(origfile, tmpfile) nbstring = open(tmpfile).read() f = open(tmpfile, 'w') f.write( nbstring.replace( "# molPX intro", "<font color='red', size=1>" "This is a temporary copy of the original notebook found in `%s`. " "This temporary copy is located in `%s`. " "Feel free to play around, modify or even break this notebook. " "It wil be deleted on exit it and a new one created next time you issue " "`molpx.example_notebook()`</font>\\n\\n" "# molPX intro" % (origfile, tmpfile))) f.close() cmd = 'jupyter notebook %s' % tmpfile if isinstance(extra_flags_as_one_string, str): cmd = '%s %s' % (cmd, extra_flags_as_one_string) eshell = TerminalInteractiveShell() eshell.system_raw(cmd)
def main(): url = sys.argv[1] context['url'] = url pkg = app.dispatch_url(url) context['pkg'] = pkg for item in pkg.to_dict().items(): print '{} = {}'.format(*item) def prepare_readline(): import os import readline import atexit readline.parse_and_bind('tab: complete') histfile = os.path.expanduser("~/.daenerys_history") try: readline.read_history_file(histfile) except IOError: pass def savehist(histfile): readline.write_history_file(histfile) atexit.register(savehist, histfile) del atexit try: from IPython.terminal.interactiveshell import TerminalInteractiveShell shell = TerminalInteractiveShell(user_ns=context) shell.mainloop() except ImportError: import code shell = code.InteractiveConsole(locals=context) shell.runcode(prepare_readline.__code__) shell.interact()
def main(): import optparse parser = optparse.OptionParser() # Shall we fuzz the request, response, or both? # Set via optparse in main global sr_request # search/replace tuple for requests - (True, [search, replace]) where true means to use regex global sr_response # search/replace tuple for responses - (True, [search, replace]) where true means to use regex global fuzz_request global fuzz_response # Other module-wide variables global debug global term global logger global fwdr parser.add_option( '-l','--local-addr', dest='local_addr',default='127.0.0.1', help='Local address to bind to') parser.add_option( '-p','--local-port', type='int',dest='local_port',default=1234, help='Local port to bind to') parser.add_option( '-r','--remote-addr',dest='remote_addr', help='Remote address to bind to') parser.add_option( '-P','--remote-port', type='int',dest='remote_port',default=80, help='Remote port to bind to') parser.add_option( '--search-request', dest='search_request',default='', help='String that if found will be replaced by --replace-request\'s value') parser.add_option( '--replace-request', dest='replace_request',default='', help='String to replace the value of --search-request') parser.add_option( '--search-response', dest='search_response',default='', help='String that if found will be replaced by --replace-request\'s value') parser.add_option( '--replace-response', dest='replace_response',default='', help='String to replace the value of --search-request') parser.add_option( '--regex-request', action='store_true' ,dest='request_use_regex', help='Requests: Use regular expressions for search and replace instead of string constants') parser.add_option( '--regex-response', action='store_true' ,dest='response_use_regex', help='Responses: Use regular expressions for search and replace instead of string constants') parser.add_option( '--fuzz-request', action='store_true' ,dest='fuzz_request', help='Fuzz the request which the proxy gets from the connecting client \ prior to sending it to the remote host') parser.add_option( '--fuzz-response', action='store_true' ,dest='fuzz_response', help='Fuzz the response which the proxy gets from the remote host prior \ to sending it to the conecting client') parser.add_option( '-i','--run-info', dest='run_info',default='', help='Additional information string to add to database run_info entry') parser.add_option( '-d','--debug', type='int',dest='debug',default=0, help='Debug level (0-5, 0: No debugging; 1: Simple conneciton \ information; 2: Simple data information; 3: Listener data display; 4: \ Sender data display; 5: All data display)') (options, args) = parser.parse_args() if not options.remote_addr or not options.remote_port: parser.print_help() exit(1) # Validate options for search/replace if (options.search_request and not options.replace_request) or (options.replace_request and not options.search_request): print >>sys.stderr, "Both --search-request and --replace-request must be provided together" exit(1) if (options.search_response and not options.replace_response) or (options.replace_response and not options.search_response): print >>sys.stderr, "Both --search-response and --replace-response must be provided together" exit(1) # Setup a TerminalController for formatted output term = TerminalController() # Print the current run information print(term.render("""\nSetting up asynch. TCP proxy with the following settings: ${GREEN}Local binding Address: %s Local binding Port: %s${NORMAL} ${RED}Remote host address: %s Remote host port: %s${NORMAL} """) % (options.local_addr, options.local_port, options.remote_addr, options.remote_port)) # Set the debug value debug = options.debug # If run info was passed in on the command line, use that for the run_info table # additional info field (It will have what's being fuzzed prepended to it as well) run_additional_info = options.run_info # Print the selected debug value if(debug > 0): if(debug == 1): print(" Debug: Level 1 (Show simple connection information)") elif(debug == 2): print(" Debug: Level 2 (Show simple data information, such as the size of sent/received messages)") elif(debug == 3): print(" Debug: Level 3 (Show listener data and size of sent/received messages)") elif(debug == 4): print(" Debug: Level 4 (Show sender data and size of sent/received messages)") elif(debug == 5): print(" Debug: Level 5 (Show all possible information, including the size of sent/received messages, and their data for listener and sender)") print("") # Display and setup search/replace things if options.search_request and options.replace_request: sr_request = [None, options.search_request.decode('string-escape'), options.replace_request.decode('string-escape')] # Check if we want to use regex instead of string constants if options.request_use_regex: # Use regex instead of string replace print(term.render("Running regex search/replace on ${BOLD}REQUESTS${NORMAL} with regex: 's/%s/%s'" % (sr_request[1], sr_request[2]))) sr_request[0] = True else: print(term.render("Running string search/replace on ${BOLD}REQUESTS${NORMAL} with search/replace: 's/%s/%s'" % (sr_request[1], sr_request[2]))) sr_request[0] = False else: sr_request = None if options.search_response and options.replace_response: sr_response = [None, options.search_response.decode('string-escape'), options.replace_response.decode('string-escape')] # Check if we want to use regex instead of string constants if options.response_use_regex: print(term.render("Running regex search/replace on ${BOLD}RESPONSES${NORMAL} with regex: 's/%s/%s'" % (sr_response[1], sr_response[2]))) sr_response[0] = True else: print(term.render("Running string search/replace on ${BOLD}RESPONSES${NORMAL} with search/replace: 's/%s/%s'" % (sr_response[1], sr_response[2]))) sr_response[0] = False else: sr_response = None # Setup which to fuzz - request, response, neither, both? if(options.fuzz_request): fuzz_request = options.fuzz_request run_additional_info = "Fuzzing REQUESTS; " + run_additional_info print(term.render("Fuzzing ${BOLD}REQUESTS${NORMAL}")) else: fuzz_request = False if(options.fuzz_response): fuzz_response = options.fuzz_response run_additional_info = "Fuzzing RESPONSES; " + run_additional_info print(term.render("Fuzzing ${BOLD}RESPONSES${NORMAL}")) else: fuzz_response = False if(not(options.fuzz_response or options.fuzz_request)): run_additional_info = "Fuzzing NONE; " + run_additional_info print(term.render("Fuzzing ${BOLD}<NOTHING>${NORMAL} (Maybe you wanted ${BOLD}--fuzz-request or --fuzz-response${NORMAL}?)")) if(fuzz_request and fuzz_response): print(term.render("${YELLOW}\nWARNING! WARNING!\n${BOLD}Fuzzing BOTH the request and response is probably a bad idea, ensure this is what you want to do!${NORMAL}${YELLOW}\nWARNING! WARNING!\n${NORMAL}")) # host, db, username, passwd if logging_enabled: logger = postgresLogger("postgreshost", "dbname", "dbuser", "dbpass") logger.log_run_info("CompanyName", "ProjectName-v1.2.3", run_additional_info) # create object that spawns reciever/sender pairs upon connection fwdr = forwarder(options.local_addr,options.local_port,options.remote_addr,options.remote_port) print("Listener running...") #asyncore.loop() # A quick hack to be able to control fuzz on/off while running # separate asyncore.loop into its own thread so we can have terminal control asyncThread = Thread(target=asyncore.loop) asyncThread.start() # start a console (ipython) from IPython.terminal.interactiveshell import TerminalInteractiveShell shell = TerminalInteractiveShell(user_ns=globals()) shell.mainloop() # cleanup otherwise thread wont die and program hangs fwdr.close() #asyncore.close_all() asyncThread._Thread__stop()
try: return __import__(module, fromlist=[needed_module]) except ImportError: count -= 1 if count == 0: raise try: # IPython 5.0 and newer from IPython.terminal.debugger import TerminalPdb as Pdb from IPython.core.debugger import BdbQuit_excepthook from IPython.terminal.interactiveshell import TerminalInteractiveShell # Let IPython decide about which debugger class to use # This is especially important for tools that fiddle with stdout debugger_cls = TerminalInteractiveShell().debugger_cls except ImportError: from IPython.core.debugger import Pdb, BdbQuit_excepthook debugger_cls = Pdb possible_modules = [ 'IPython.terminal.ipapp', # Newer IPython 'IPython.frontend.terminal.ipapp' ] # Older IPython app = import_module(possible_modules, "TerminalIPythonApp") TerminalIPythonApp = app.TerminalIPythonApp possible_modules = [ 'IPython.terminal.embed', # Newer IPython 'IPython.frontend.terminal.embed'
def main(): # pylint: disable=too-many-statements # Set up a simple argument parser. parser = binhoArgumentParser( description="Convenience shell for working with Binho host adapters.") parser.add_argument( "-e", "--exec", metavar="code", type=str, help="Executes the provided code as though it were passed " + "to a Binho host adapter shell, and then terminates.", dest="code", ) parser.add_argument( "-E", "--pre-exec", metavar="code", type=str, help="Executes the provided code as though it were passed " + "to a Binho host adapter shell, but does not explicitly terminate.", dest="prelude", ) parser.add_argument( "-f", "--file", metavar="file", type=str, help="Executes the relevant file before starting the given shell.", ) parser.add_argument( "-M", "--automagic", dest="automagic", action="store_true", help="Enable automagic, so lazy developers don't have to type %%.", ) parser.add_argument( "-P", "--avoid-parens", dest="avoidparens", action="store_true", help= "Enable full autocall, so bare methods are executed, rather than printed.", ) parser.add_argument( "-A", "--autoreload", dest="autoreload", action="store_true", help= "Attempts to reload python modules automatically as they change; so current objects import new \ functionality. This may sometimes break your shell.", ) parser.add_argument( "-S", "--singleton", dest="singleton", action="store_true", help= "Connect via a singleton that persists across device reconnects. Note: device state is not preserved.", ) args = parser.parse_args() if args.singleton: connect_function = parser.get_singleton_for_specified_device else: connect_function = parser.find_specified_device binho = connect_function() if binho.inBootloaderMode: print( "{} found on {}, but it cannot be used now because it's in DFU mode" .format(binho.productName, binho.commPort)) sys.exit(errno.ENODEV) elif binho.inDAPLinkMode: print( "{} found on {}, but it cannot be used now because it's in DAPlink mode" .format(binho.productName, binho.commPort)) print("Tip: Exit DAPLink mode using 'binho daplink -q' command") sys.exit(errno.ENODEV) # Break into IPython for the shell. if not args.code: print( "Spawning an IPython shell for easy access to your Binho host adapter." ) print( "Like normal python, you can use help(object) to get help for that object.\n" ) print( "Try help(binho.gpio) to see the documentation for the Binho host adapter GPIO;" ) print( "try dir(binho) to see a list of properties on the Binho Host Adapter object, and" ) print( "try binho.available_interfaces() and binho.available_programmers() to see" ) print( "the interfaces you can work with, and the programmers you can create.\n" ) singleton_text = "singleton " if args.singleton else "" print( "A Binho host adapter {}object has been created for you as 'binho'. Have fun!\n" .format(singleton_text)) # Create a new shell, and give it access to our created Binho object. shell = TerminalInteractiveShell() shell.push("binho") # Create nice aliases for our primary interfaces. # pylint: disable=unused-variable i2c = binho.i2c spi = binho.spi dac = binho.dac adc = binho.adc oneWire = binho.oneWire # uart = binho.uart gpio = binho.gpio # shell.push(('i2c', 'spi', 'adc', 'uart', 'gpio',)) shell.push(("i2c", "spi", "gpio", "dac", "adc", "oneWire")) # pylint: enable=unused-variable # Make the autoreload extension available. shell.extension_manager.load_extension("autoreload") # Add our magic commands, to make execution more 'fun'. shell.register_magics(binhoShellMagics) # If the user has requested automagic, let them have their automagic. if args.automagic: shell.automagic = True # If we're in avoid parenthesis mode if args.avoidparens: shell.autocall = 2 # If we're using autoreload, enable that. if args.autoreload: shell.run_cell("%autoreload 2") print( "Heads up: you've enabled autoreload. Things make break in unexpected ways as your code changes." ) print( "You can fix this by adjusting your expectations regarding breakage.\n" ) # Handle any inline execution requested. if args.code or args.prelude: # Replace any ;'s with newlines, so we can execute more than one # statement. code = args.code or args.prelude code = re.sub(r";\s*", "\n", code) lines = code.split("\n") # If we're in execute-and-quit mode, do so. for line in lines: shell.run_cell(line, shell_futures=True) # If we're to exit after running the relevant code, do so. if args.code: sys.exit(0) # If we have a file to execute, execute it. if args.file: shell.safe_execfile_ipy(args.file, shell_futures=True, raise_exceptions=True) # Run the shell itself. shell.connect_function = connect_function shell.mainloop() # close the connection to the device binho.close()
def mock_get_ipython(): return TerminalInteractiveShell()
def _get_debugger_cls(): if ipython_version < (5, 0, 0): from IPython.core.debugger import Pdb return Pdb return TerminalInteractiveShell().debugger_cls
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)
def main(): # Set up a simple argument parser. parser = GreatFETArgumentParser( description="Convenience shell for working with GreatFET devices.") parser.add_argument( '-e', '--exec', metavar="code", type=str, help="Executes the provided code as though it were passed " + "to a greatfet shell, and then terminates.", dest="code") parser.add_argument( '-E', '--pre-exec', metavar="code", type=str, help="Executes the provided code as though it were passed " + "to a greatfet shell, but does not explicitly terminate.", dest="prelude") parser.add_argument( '-f', '--file', metavar="file", type=str, help="Executes the relevant file before starting the given shell.") parser.add_argument( '-M', '--automagic', dest="automagic", action='store_true', help="Enable automagic, so lazy developers don't have to type %%.") parser.add_argument( '-P', '--avoid-parens', dest="avoidparens", action='store_true', help= "Enable full autocall, so bare methods are executed, rather than printed." ) parser.add_argument( '-A', '--autoreload', dest="autoreload", action='store_true', help= "Attempts to reload python modules automatically as they change; so current objects import new functionality. This may sometimes break your shell." ) parser.add_argument( '-S', '--singleton', dest="singleton", action='store_true', help= "Connect via a singleton that persists across device reconnects. Note: device state is not preserved." ) args = parser.parse_args() if args.singleton: connect_function = parser.get_singleton_for_specified_device else: connect_function = parser.find_specified_device gf = connect_function() # Break into IPython for the shell. if not args.code: print( "Spawning an IPython shell for easy access to your GreatFET board." ) print( "Like normal python, you can use help(object) to get help for that object.\n" ) print( "Try help(gf.gpio) to see the documentation for the GreatFET GPIO;" ) print( "try dir(gf) to see a list of properties on the GreatFET object, and" ) print( "try gf.available_interfaces() and gf.available_programmers() to see" ) print( "the interfaces you can work with, and the programmers you can create.\n" ) print( "This GreatFET shell is *magical*. Try some of our IPython magics:\n" ) print("\t %dmesg -- prints the GreatFET's debug ring (log)") print("\t %reconnect -- tries to reconnect to the current GreatFET") print( "\t %makeflash -- when run from a firmware build dir, builds and flashes your GreatFET" ) print( "\t %reload -- tries to reload your host python code; useful with $PYTHONPATH" ) print( "\t %refet -- (not %reset) resets and reconnects to the current GreatFET" ) print("\t [hey, %reset was taken!]\n\n") singleton_text = "singleton " if args.singleton else "" print( "A GreatFET {}object has been created for you as 'gf'. Have fun!\n" .format(singleton_text)) # Create a new shell, and give it access to our created GreatFET object. shell = TerminalInteractiveShell() shell.push('gf') # Create nice aliases for our primary interfaces. i2c = gf.i2c spi = gf.spi adc = gf.adc uart = gf.uart gpio = gf.gpio shell.push(( 'i2c', 'spi', 'adc', 'uart', 'gpio', )) # Make the autoreload extension available. shell.extension_manager.load_extension('autoreload') # Add our magic commands, to make execution more 'fun'. shell.register_magics(GreatFETShellMagics) # If the user has requested automagic, let them have their automagic. if args.automagic: shell.automagic = True # If we're in avoid parenthesis mode if args.avoidparens: shell.autocall = 2 # If we're using autoreload, enable that. if args.autoreload: shell.run_cell('%autoreload 2') print( "Heads up: you've enabled autoreload. Things make break in unexpected ways as your code changes." ) print( "You can fix this by adjusting your expectations regarding breakage.\n" ) # Handle any inline execution requested. if args.code or args.prelude: # Replace any ;'s with newlines, so we can execute more than one statement. code = args.code or args.prelude code = re.sub(r";\s*", "\n", code) lines = code.split("\n") # If we're in execute-and-quit mode, do so. for line in lines: shell.run_cell(line, shell_futures=True) # If we're to exit after running the relevant code, do so. if args.code: sys.exit(0) # If we have a file to execute, execute it. if args.file: shell.safe_execfile_ipy(args.file, shell_futures=True, raise_exceptions=True) # Run the shell itself. shell.connect_function = connect_function shell.mainloop()
def timeit_magic(n, setup, statement): """Create a `%timeit` magic function with fixed `n`, more setup code and the statement to be timed. """ return TerminalInteractiveShell().run_cell_magic( 'timeit', '-o -q n = {n}; '.format(n=n) + setup, statement)
def start_test_ip(): from IPython.terminal.interactiveshell import TerminalInteractiveShell return TerminalInteractiveShell()