id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
176,871
import sys import time import signal import OpenGL.GLUT as glut import OpenGL.platform as platform from timeit import default_timer as clock def glut_display(): # Dummy display function pass
null
176,872
import sys import time import signal import OpenGL.GLUT as glut import OpenGL.platform as platform from timeit import default_timer as clock def glut_idle(): # Dummy idle function pass
null
176,873
import sys import time import signal import OpenGL.GLUT as glut import OpenGL.platform as platform from timeit import default_timer as clock glutMainLoopEvent = None glut.glutInit( sys.argv ) glut.glutInitDisplayMode( glut_display_mode ) glut.glutCreateWindow( b'ipython' ) glut.glutReshapeWindow( 1, 1 ) glut.glutHideWindow( ) glut.glutWMCloseFunc( glut_close ) glut.glutDisplayFunc( glut_display ) glut.glutIdleFunc( glut_idle ) def glut_close(): # Close function only hides the current window glut.glutHideWindow() glutMainLoopEvent()
null
176,874
import sys import time import signal import OpenGL.GLUT as glut import OpenGL.platform as platform from timeit import default_timer as clock glutMainLoopEvent = None def glut_int_handler(signum, frame): # Catch sigint and print the defaultipyt message signal.signal(signal.SIGINT, signal.default_int_handler) print('\nKeyboardInterrupt') # Need to reprint the prompt at this stage glut.glutInit( sys.argv ) glut.glutInitDisplayMode( glut_display_mode ) glut.glutCreateWindow( b'ipython' ) glut.glutReshapeWindow( 1, 1 ) glut.glutHideWindow( ) glut.glutWMCloseFunc( glut_close ) glut.glutDisplayFunc( glut_display ) glut.glutIdleFunc( glut_idle ) The provided code snippet includes necessary dependencies for implementing the `inputhook` function. Write a Python function `def inputhook(context)` to solve the following problem: Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. Here is the function: def inputhook(context): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. signal.signal(signal.SIGINT, glut_int_handler) try: t = clock() # Make sure the default window is set after a window has been closed if glut.glutGetWindow() == 0: glut.glutSetWindow( 1 ) glutMainLoopEvent() return 0 while not context.input_is_ready(): glutMainLoopEvent() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass
Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance.
176,875
import gtk, gobject gtk.gdk.threads_init() import gtk, gobject gtk.gdk.threads_init() The provided code snippet includes necessary dependencies for implementing the `inputhook` function. Write a Python function `def inputhook(context)` to solve the following problem: When the eventloop of prompt-toolkit is idle, call this inputhook. This will run the GTK main loop until the file descriptor `context.fileno()` becomes ready. :param context: An `InputHookContext` instance. Here is the function: def inputhook(context): """ When the eventloop of prompt-toolkit is idle, call this inputhook. This will run the GTK main loop until the file descriptor `context.fileno()` becomes ready. :param context: An `InputHookContext` instance. """ def _main_quit(*a, **kw): gtk.main_quit() return False gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit) gtk.main()
When the eventloop of prompt-toolkit is idle, call this inputhook. This will run the GTK main loop until the file descriptor `context.fileno()` becomes ready. :param context: An `InputHookContext` instance.
176,876
import ctypes import ctypes.util from threading import Event objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc")) void_p = ctypes.c_void_p objc.objc_getClass.restype = void_p objc.sel_registerName.restype = void_p objc.objc_msgSend.restype = void_p objc.objc_msgSend.argtypes = [void_p, void_p] msg = objc.objc_msgSend def n(name): """create a selector name (for ObjC methods)""" return objc.sel_registerName(_utf8(name)) CFRelease = CoreFoundation.CFRelease CFRelease.restype = None CFRelease.argtypes = [void_p] CFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate CFFileDescriptorInvalidate.restype = None CFFileDescriptorInvalidate.argtypes = [void_p] def _NSApp(): """Return the global NSApplication instance (NSApp)""" objc.objc_msgSend.argtypes = [void_p, void_p] return msg(C('NSApplication'), n('sharedApplication')) def _wake(NSApp): """Wake the Application""" objc.objc_msgSend.argtypes = [ void_p, void_p, void_p, void_p, void_p, void_p, void_p, void_p, void_p, void_p, void_p, ] event = msg( C("NSEvent"), n( "otherEventWithType:location:modifierFlags:" "timestamp:windowNumber:context:subtype:data1:data2:" ), 15, # Type 0, # location 0, # flags 0, # timestamp 0, # window None, # context 0, # subtype 0, # data1 0, # data2 ) objc.objc_msgSend.argtypes = [void_p, void_p, void_p, void_p] msg(NSApp, n('postEvent:atStart:'), void_p(event), True) _triggered = Event() The provided code snippet includes necessary dependencies for implementing the `_input_callback` function. Write a Python function `def _input_callback(fdref, flags, info)` to solve the following problem: Callback to fire when there's input to be read Here is the function: def _input_callback(fdref, flags, info): """Callback to fire when there's input to be read""" _triggered.set() CFFileDescriptorInvalidate(fdref) CFRelease(fdref) NSApp = _NSApp() objc.objc_msgSend.argtypes = [void_p, void_p, void_p] msg(NSApp, n('stop:'), NSApp) _wake(NSApp)
Callback to fire when there's input to be read
176,877
import ctypes import ctypes.util from threading import Event objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc")) void_p = ctypes.c_void_p objc.objc_getClass.restype = void_p objc.sel_registerName.restype = void_p objc.objc_msgSend.restype = void_p objc.objc_msgSend.argtypes = [void_p, void_p] msg = objc.objc_msgSend def n(name): """create a selector name (for ObjC methods)""" return objc.sel_registerName(_utf8(name)) CoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library("CoreFoundation")) def _NSApp(): """Return the global NSApplication instance (NSApp)""" objc.objc_msgSend.argtypes = [void_p, void_p] return msg(C('NSApplication'), n('sharedApplication')) _triggered = Event() def _stop_on_read(fd): """Register callback to stop eventloop when there's data on fd""" _triggered.clear() fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None) CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack) source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0) loop = CFRunLoopGetCurrent() CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes) CFRelease(source) The provided code snippet includes necessary dependencies for implementing the `inputhook` function. Write a Python function `def inputhook(context)` to solve the following problem: Inputhook for Cocoa (NSApp) Here is the function: def inputhook(context): """Inputhook for Cocoa (NSApp)""" NSApp = _NSApp() _stop_on_read(context.fileno()) objc.objc_msgSend.argtypes = [void_p, void_p] msg(NSApp, n('run')) if not _triggered.is_set(): # app closed without firing callback, # probably due to last window being closed. # Run the loop manually in this case, # since there may be events still to process (#9734) CoreFoundation.CFRunLoopRun()
Inputhook for Cocoa (NSApp)
176,878
from gi.repository import Gtk, GLib def _main_quit(*args, **kwargs): Gtk.main_quit() return False def inputhook(context): GLib.io_add_watch(context.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN, _main_quit) Gtk.main()
null
176,879
import sys import warnings from IPython.core import ultratb, compilerop from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic from IPython.core.interactiveshell import DummyMod, InteractiveShell from IPython.terminal.interactiveshell import TerminalInteractiveShell from IPython.terminal.ipapp import load_default_config from traitlets import Bool, CBool, Unicode from IPython.utils.io import ask_yes_no from typing import Set class InteractiveShellEmbed(TerminalInteractiveShell): dummy_mode = Bool(False) exit_msg = Unicode('') embedded = CBool(True) should_raise = CBool(False) # Like the base class display_banner is not configurable, but here it # is True by default. display_banner = CBool(True) exit_msg = Unicode() # When embedding, by default we don't change the terminal title term_title = Bool(False, help="Automatically set the terminal title" ).tag(config=True) _inactive_locations: Set[str] = set() def _disable_init_location(self): """Disable the current Instance creation location""" InteractiveShellEmbed._inactive_locations.add(self._init_location_id) def embedded_active(self): return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) def embedded_active(self, value): if value: InteractiveShellEmbed._inactive_locations.discard( self._call_location_id) InteractiveShellEmbed._inactive_locations.discard( self._init_location_id) else: InteractiveShellEmbed._inactive_locations.add( self._call_location_id) def __init__(self, **kw): assert ( "user_global_ns" not in kw ), "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0." clid = kw.pop('_init_location_id', None) if not clid: frame = sys._getframe(1) clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) self._init_location_id = clid super(InteractiveShellEmbed,self).__init__(**kw) # don't use the ipython crash handler so that user exceptions aren't # trapped sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, mode=self.xmode, call_pdb=self.pdb) def init_sys_modules(self): """ Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. """ pass def init_magics(self): super(InteractiveShellEmbed, self).init_magics() self.register_magics(EmbeddedMagics) def __call__( self, header="", local_ns=None, module=None, dummy=None, stack_depth=1, compile_flags=None, **kw ): """Activate the interactive interpreter. __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start the interpreter shell with the given local and global namespaces, and optionally print a header string at startup. The shell can be globally activated/deactivated using the dummy_mode attribute. This allows you to turn off a shell used for debugging globally. However, *each* time you call the shell you can override the current state of dummy_mode with the optional keyword parameter 'dummy'. For example, if you set dummy mode on with IPShell.dummy_mode = True, you can still have a specific call work by making it as IPShell(dummy=False). """ # we are called, set the underlying interactiveshell not to exit. self.keep_running = True # If the user has turned it off, go away clid = kw.pop('_call_location_id', None) if not clid: frame = sys._getframe(1) clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) self._call_location_id = clid if not self.embedded_active: return # Normal exits from interactive mode set this flag, so the shell can't # re-enter (it checks this variable at the start of interactive mode). self.exit_now = False # Allow the dummy parameter to override the global __dummy_mode if dummy or (dummy != 0 and self.dummy_mode): return # self.banner is auto computed if header: self.old_banner2 = self.banner2 self.banner2 = self.banner2 + '\n' + header + '\n' else: self.old_banner2 = '' if self.display_banner: self.show_banner() # Call the embedding code with a stack depth of 1 so it can skip over # our call and get the original caller's namespaces. self.mainloop( local_ns, module, stack_depth=stack_depth, compile_flags=compile_flags ) self.banner2 = self.old_banner2 if self.exit_msg is not None: print(self.exit_msg) if self.should_raise: raise KillEmbedded('Embedded IPython raising error, as user requested.') def mainloop( self, local_ns=None, module=None, stack_depth=0, compile_flags=None, ): """Embeds IPython into a running python program. Parameters ---------- local_ns, module Working local namespace (a dict) and module (a module or similar object). If given as None, they are automatically taken from the scope where the shell was called, so that program variables become visible. stack_depth : int How many levels in the stack to go to looking for namespaces (when local_ns or module is None). This allows an intermediate caller to make sure that this function gets the namespace from the intended level in the stack. By default (0) it will get its locals and globals from the immediate caller. compile_flags A bit field identifying the __future__ features that are enabled, as passed to the builtin :func:`compile` function. If given as None, they are automatically taken from the scope where the shell was called. """ # Get locals and globals from caller if ((local_ns is None or module is None or compile_flags is None) and self.default_user_namespaces): call_frame = sys._getframe(stack_depth).f_back if local_ns is None: local_ns = call_frame.f_locals if module is None: global_ns = call_frame.f_globals try: module = sys.modules[global_ns['__name__']] except KeyError: warnings.warn("Failed to get module %s" % \ global_ns.get('__name__', 'unknown module') ) module = DummyMod() module.__dict__ = global_ns if compile_flags is None: compile_flags = (call_frame.f_code.co_flags & compilerop.PyCF_MASK) # Save original namespace and module so we can restore them after # embedding; otherwise the shell doesn't shut down correctly. orig_user_module = self.user_module orig_user_ns = self.user_ns orig_compile_flags = self.compile.flags # Update namespaces and fire up interpreter # The global one is easy, we can just throw it in if module is not None: self.user_module = module # But the user/local one is tricky: ipython needs it to store internal # data, but we also need the locals. We'll throw our hidden variables # like _ih and get_ipython() into the local namespace, but delete them # later. if local_ns is not None: reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} self.user_ns = reentrant_local_ns self.init_user_ns() # Compiler flags if compile_flags is not None: self.compile.flags = compile_flags # make sure the tab-completer has the correct frame information, so it # actually completes using the frame's locals/globals self.set_completer_frame() with self.builtin_trap, self.display_trap: self.interact() # now, purge out the local namespace of IPython's hidden variables. if local_ns is not None: local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) # Restore original namespace so shell can shut down when we exit. self.user_module = orig_user_module self.user_ns = orig_user_ns self.compile.flags = orig_compile_flags class InteractiveShell(SingletonConfigurable): """An enhanced, interactive shell for Python.""" _instance = None ast_transformers = List([], help= """ A list of ast.NodeTransformer subclass instances, which will be applied to user input before code is run. """ ).tag(config=True) autocall = Enum((0,1,2), default_value=0, help= """ Make IPython automatically call any callable object even if you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. The value can be '0' to disable the feature, '1' for 'smart' autocall, where it is not applied if there are no more arguments on the line, and '2' for 'full' autocall, where all callable objects are automatically called (even if no arguments are present). """ ).tag(config=True) autoindent = Bool(True, help= """ Autoindent IPython code entered interactively. """ ).tag(config=True) autoawait = Bool(True, help= """ Automatically run await statement in the top level repl. """ ).tag(config=True) loop_runner_map ={ 'asyncio':(_asyncio_runner, True), 'curio':(_curio_runner, True), 'trio':(_trio_runner, True), 'sync': (_pseudo_sync_runner, False) } loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner", allow_none=True, help="""Select the loop runner that will be used to execute top-level asynchronous code""" ).tag(config=True) def _default_loop_runner(self): return import_item("IPython.core.interactiveshell._asyncio_runner") def _import_runner(self, proposal): if isinstance(proposal.value, str): if proposal.value in self.loop_runner_map: runner, autoawait = self.loop_runner_map[proposal.value] self.autoawait = autoawait return runner runner = import_item(proposal.value) if not callable(runner): raise ValueError('loop_runner must be callable') return runner if not callable(proposal.value): raise ValueError('loop_runner must be callable') return proposal.value automagic = Bool(True, help= """ Enable magic commands to be called without the leading %. """ ).tag(config=True) banner1 = Unicode(default_banner, help="""The part of the banner to be printed before the profile""" ).tag(config=True) banner2 = Unicode('', help="""The part of the banner to be printed after the profile""" ).tag(config=True) cache_size = Integer(1000, help= """ Set the size of the output cache. The default is 1000, you can change it permanently in your config file. Setting it to 0 completely disables the caching system, and the minimum value accepted is 3 (if you provide a value less than 3, it is reset to 0 and a warning is issued). This limit is defined because otherwise you'll spend more time re-flushing a too small cache than working """ ).tag(config=True) color_info = Bool(True, help= """ Use colors for displaying information about objects. Because this information is passed through a pager (like 'less'), and some pagers get confused with color codes, this capability can be turned off. """ ).tag(config=True) colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), default_value='Neutral', help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." ).tag(config=True) debug = Bool(False).tag(config=True) disable_failing_post_execute = Bool(False, help="Don't call post-execute functions that have failed in the past." ).tag(config=True) display_formatter = Instance(DisplayFormatter, allow_none=True) displayhook_class = Type(DisplayHook) display_pub_class = Type(DisplayPublisher) compiler_class = Type(CachingCompiler) inspector_class = Type( oinspect.Inspector, help="Class to use to instantiate the shell inspector" ).tag(config=True) sphinxify_docstring = Bool(False, help= """ Enables rich html representation of docstrings. (This requires the docrepr module). """).tag(config=True) def _sphinxify_docstring_changed(self, change): if change['new']: warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) enable_html_pager = Bool(False, help= """ (Provisional API) enables html representation in mime bundles sent to pagers. """).tag(config=True) def _enable_html_pager_changed(self, change): if change['new']: warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) data_pub_class = None exit_now = Bool(False) exiter = Instance(ExitAutocall) def _exiter_default(self): return ExitAutocall(self) # Monotonically increasing execution counter execution_count = Integer(1) filename = Unicode("<ipython console>") ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ # Used to transform cells before running them, and check whether code is complete input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager', ()) def input_transformers_cleanup(self): return self.input_transformer_manager.cleanup_transforms input_transformers_post = List([], help="A list of string input transformers, to be applied after IPython's " "own input transformations." ) def input_splitter(self): """Make this available for backward compatibility (pre-7.0 release) with existing code. For example, ipykernel ipykernel currently uses `shell.input_splitter.check_complete` """ from warnings import warn warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.", DeprecationWarning, stacklevel=2 ) return self.input_transformer_manager logstart = Bool(False, help= """ Start logging to the default log file in overwrite mode. Use `logappend` to specify a log file to **append** logs to. """ ).tag(config=True) logfile = Unicode('', help= """ The name of the logfile to use. """ ).tag(config=True) logappend = Unicode('', help= """ Start logging to the given file in append mode. Use `logfile` to specify a log file to **overwrite** logs to. """ ).tag(config=True) object_info_string_level = Enum((0,1,2), default_value=0, ).tag(config=True) pdb = Bool(False, help= """ Automatically call the pdb debugger after every exception. """ ).tag(config=True) display_page = Bool(False, help="""If True, anything that would be passed to the pager will be displayed as regular output instead.""" ).tag(config=True) show_rewritten_input = Bool(True, help="Show rewritten input, e.g. for autocall." ).tag(config=True) quiet = Bool(False).tag(config=True) history_length = Integer(10000, help='Total length of command history' ).tag(config=True) history_load_length = Integer(1000, help= """ The number of saved history entries to be loaded into the history buffer at startup. """ ).tag(config=True) ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'], default_value='last_expr', help=""" 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying which nodes should be run interactively (displaying output from expressions). """ ).tag(config=True) warn_venv = Bool( True, help="Warn if running in a virtual environment with no IPython installed (so IPython from the global environment is used).", ).tag(config=True) # TODO: this part of prompt management should be moved to the frontends. # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' separate_in = SeparateUnicode('\n').tag(config=True) separate_out = SeparateUnicode('').tag(config=True) separate_out2 = SeparateUnicode('').tag(config=True) wildcards_case_sensitive = Bool(True).tag(config=True) xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'), default_value='Context', help="Switch modes for the IPython exception handlers." ).tag(config=True) # Subcomponents of InteractiveShell alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) def profile(self): if self.profile_dir is not None: name = os.path.basename(self.profile_dir.location) return name.replace('profile_','') # Private interface _post_execute = Dict() # Tracks any GUI loop loaded for pylab pylab_gui_select = None last_execution_succeeded = Bool(True, help='Did last executed command succeeded') last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True) def __init__(self, ipython_dir=None, profile_dir=None, user_module=None, user_ns=None, custom_exceptions=((), None), **kwargs): # This is where traits with a config_key argument are updated # from the values on config. super(InteractiveShell, self).__init__(**kwargs) if 'PromptManager' in self.config: warn('As of IPython 5.0 `PromptManager` config will have no effect' ' and has been replaced by TerminalInteractiveShell.prompts_class') self.configurables = [self] # These are relatively independent and stateless self.init_ipython_dir(ipython_dir) self.init_profile_dir(profile_dir) self.init_instance_attrs() self.init_environment() # Check if we're in a virtualenv, and set up sys.path. self.init_virtualenv() # Create namespaces (user_ns, user_global_ns, etc.) self.init_create_namespaces(user_module, user_ns) # This has to be done after init_create_namespaces because it uses # something in self.user_ns, but before init_sys_modules, which # is the first thing to modify sys. # TODO: When we override sys.stdout and sys.stderr before this class # is created, we are saving the overridden ones here. Not sure if this # is what we want to do. self.save_sys_module_state() self.init_sys_modules() # While we're trying to have each part of the code directly access what # it needs without keeping redundant references to objects, we have too # much legacy code that expects ip.db to exist. self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) self.init_history() self.init_encoding() self.init_prefilter() self.init_syntax_highlighting() self.init_hooks() self.init_events() self.init_pushd_popd_magic() self.init_user_ns() self.init_logger() self.init_builtins() # The following was in post_config_initialization self.init_inspector() self.raw_input_original = input self.init_completer() # TODO: init_io() needs to happen before init_traceback handlers # because the traceback handlers hardcode the stdout/stderr streams. # This logic in in debugger.Pdb and should eventually be changed. self.init_io() self.init_traceback_handlers(custom_exceptions) self.init_prompts() self.init_display_formatter() self.init_display_pub() self.init_data_pub() self.init_displayhook() self.init_magics() self.init_alias() self.init_logstart() self.init_pdb() self.init_extension_manager() self.init_payload() self.events.trigger('shell_initialized', self) atexit.register(self.atexit_operations) # The trio runner is used for running Trio in the foreground thread. It # is different from `_trio_runner(async_fn)` in `async_helpers.py` # which calls `trio.run()` for every cell. This runner runs all cells # inside a single Trio event loop. If used, it is set from # `ipykernel.kernelapp`. self.trio_runner = None def get_ipython(self): """Return the currently running IPython instance.""" return self #------------------------------------------------------------------------- # Trait changed handlers #------------------------------------------------------------------------- def _ipython_dir_changed(self, change): ensure_dir_exists(change['new']) def set_autoindent(self,value=None): """Set the autoindent flag. If called with no arguments, it acts as a toggle.""" if value is None: self.autoindent = not self.autoindent else: self.autoindent = value def set_trio_runner(self, tr): self.trio_runner = tr #------------------------------------------------------------------------- # init_* methods called by __init__ #------------------------------------------------------------------------- def init_ipython_dir(self, ipython_dir): if ipython_dir is not None: self.ipython_dir = ipython_dir return self.ipython_dir = get_ipython_dir() def init_profile_dir(self, profile_dir): if profile_dir is not None: self.profile_dir = profile_dir return self.profile_dir = ProfileDir.create_profile_dir_by_name( self.ipython_dir, "default" ) def init_instance_attrs(self): self.more = False # command compiler self.compile = self.compiler_class() # Make an empty namespace, which extension writers can rely on both # existing and NEVER being used by ipython itself. This gives them a # convenient location for storing additional information and state # their extensions may require, without fear of collisions with other # ipython names that may develop later. self.meta = Struct() # Temporary files used for various purposes. Deleted at exit. # The files here are stored with Path from Pathlib self.tempfiles = [] self.tempdirs = [] # keep track of where we started running (mainly for crash post-mortem) # This is not being used anywhere currently. self.starting_dir = os.getcwd() # Indentation management self.indent_current_nsp = 0 # Dict to track post-execution functions that have been registered self._post_execute = {} def init_environment(self): """Any changes we need to make to the user's environment.""" pass def init_encoding(self): # Get system encoding at startup time. Certain terminals (like Emacs # under Win32 have it set to None, and we need to have a known valid # encoding to use in the raw_input() method try: self.stdin_encoding = sys.stdin.encoding or 'ascii' except AttributeError: self.stdin_encoding = 'ascii' def init_syntax_highlighting(self, changes=None): # Python source parser/formatter for syntax highlighting pyformat = PyColorize.Parser(style=self.colors, parent=self).format self.pycolorize = lambda src: pyformat(src,'str') def refresh_style(self): # No-op here, used in subclass pass def init_pushd_popd_magic(self): # for pushd/popd management self.home_dir = get_home_dir() self.dir_stack = [] def init_logger(self): self.logger = Logger(self.home_dir, logfname='ipython_log.py', logmode='rotate') def init_logstart(self): """Initialize logging in case it was requested at the command line. """ if self.logappend: self.magic('logstart %s append' % self.logappend) elif self.logfile: self.magic('logstart %s' % self.logfile) elif self.logstart: self.magic('logstart') def init_builtins(self): # A single, static flag that we set to True. Its presence indicates # that an IPython shell has been created, and we make no attempts at # removing on exit or representing the existence of more than one # IPython at a time. builtin_mod.__dict__['__IPYTHON__'] = True builtin_mod.__dict__['display'] = display self.builtin_trap = BuiltinTrap(shell=self) def init_inspector(self, changes=None): # Object inspector self.inspector = self.inspector_class( oinspect.InspectColors, PyColorize.ANSICodeColors, self.colors, self.object_info_string_level, ) def init_io(self): # implemented in subclasses, TerminalInteractiveShell does call # colorama.init(). pass def init_prompts(self): # Set system prompts, so that scripts can decide if they are running # interactively. sys.ps1 = 'In : ' sys.ps2 = '...: ' sys.ps3 = 'Out: ' def init_display_formatter(self): self.display_formatter = DisplayFormatter(parent=self) self.configurables.append(self.display_formatter) def init_display_pub(self): self.display_pub = self.display_pub_class(parent=self, shell=self) self.configurables.append(self.display_pub) def init_data_pub(self): if not self.data_pub_class: self.data_pub = None return self.data_pub = self.data_pub_class(parent=self) self.configurables.append(self.data_pub) def init_displayhook(self): # Initialize displayhook, set in/out prompts and printing system self.displayhook = self.displayhook_class( parent=self, shell=self, cache_size=self.cache_size, ) self.configurables.append(self.displayhook) # This is a context manager that installs/revmoes the displayhook at # the appropriate time. self.display_trap = DisplayTrap(hook=self.displayhook) def get_path_links(p: Path): """Gets path links including all symlinks Examples -------- In [1]: from IPython.core.interactiveshell import InteractiveShell In [2]: import sys, pathlib In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable)) In [4]: len(paths) == len(set(paths)) Out[4]: True In [5]: bool(paths) Out[5]: True """ paths = [p] while p.is_symlink(): new_path = Path(os.readlink(p)) if not new_path.is_absolute(): new_path = p.parent / new_path p = new_path paths.append(p) return paths def init_virtualenv(self): """Add the current virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough. Adapted from code snippets online. http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv """ if 'VIRTUAL_ENV' not in os.environ: # Not in a virtualenv return elif os.environ["VIRTUAL_ENV"] == "": warn("Virtual env path set to '', please check if this is intended.") return p = Path(sys.executable) p_venv = Path(os.environ["VIRTUAL_ENV"]) # fallback venv detection: # stdlib venv may symlink sys.executable, so we can't use realpath. # but others can symlink *to* the venv Python, so we can't just use sys.executable. # So we just check every item in the symlink tree (generally <= 3) paths = self.get_path_links(p) # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible if p_venv.parts[1] == "cygdrive": drive_name = p_venv.parts[2] p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:]) if any(p_venv == p.parents[1] for p in paths): # Our exe is inside or has access to the virtualenv, don't need to do anything. return if sys.platform == "win32": virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages")) else: virtual_env_path = Path( os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages" ) p_ver = sys.version_info[:2] # Predict version from py[thon]-x.x in the $VIRTUAL_ENV re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"]) if re_m: predicted_path = Path(str(virtual_env_path).format(*re_m.groups())) if predicted_path.exists(): p_ver = re_m.groups() virtual_env = str(virtual_env_path).format(*p_ver) if self.warn_venv: warn( "Attempting to work in a virtualenv. If you encounter problems, " "please install IPython inside the virtualenv." ) import site sys.path.insert(0, virtual_env) site.addsitedir(virtual_env) #------------------------------------------------------------------------- # Things related to injections into the sys module #------------------------------------------------------------------------- def save_sys_module_state(self): """Save the state of hooks in the sys module. This has to be called after self.user_module is created. """ self._orig_sys_module_state = {'stdin': sys.stdin, 'stdout': sys.stdout, 'stderr': sys.stderr, 'excepthook': sys.excepthook} self._orig_sys_modules_main_name = self.user_module.__name__ self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) def restore_sys_module_state(self): """Restore the state of the sys module.""" try: for k, v in self._orig_sys_module_state.items(): setattr(sys, k, v) except AttributeError: pass # Reset what what done in self.init_sys_modules if self._orig_sys_modules_main_mod is not None: sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod #------------------------------------------------------------------------- # Things related to the banner #------------------------------------------------------------------------- def banner(self): banner = self.banner1 if self.profile and self.profile != 'default': banner += '\nIPython profile: %s\n' % self.profile if self.banner2: banner += '\n' + self.banner2 return banner def show_banner(self, banner=None): if banner is None: banner = self.banner sys.stdout.write(banner) #------------------------------------------------------------------------- # Things related to hooks #------------------------------------------------------------------------- def init_hooks(self): # hooks holds pointers used for user-side customizations self.hooks = Struct() self.strdispatchers = {} # Set all default hooks, defined in the IPython.hooks module. hooks = IPython.core.hooks for hook_name in hooks.__all__: # default hooks have priority 100, i.e. low; user hooks should have # 0-100 priority self.set_hook(hook_name, getattr(hooks, hook_name), 100) if self.display_page: self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) def set_hook(self, name, hook, priority=50, str_key=None, re_key=None): """set_hook(name,hook) -> sets an internal IPython hook. IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython's behavior to call at runtime your own routines.""" # At some point in the future, this should validate the hook before it # accepts it. Probably at least check that the hook takes the number # of args it's supposed to. f = types.MethodType(hook,self) # check if the hook is for strdispatcher first if str_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_s(str_key, f, priority ) self.strdispatchers[name] = sdp return if re_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_re(re.compile(re_key), f, priority ) self.strdispatchers[name] = sdp return dp = getattr(self.hooks, name, None) if name not in IPython.core.hooks.__all__: print("Warning! Hook '%s' is not one of %s" % \ (name, IPython.core.hooks.__all__ )) if name in IPython.core.hooks.deprecated: alternative = IPython.core.hooks.deprecated[name] raise ValueError( "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format( name, alternative ) ) if not dp: dp = IPython.core.hooks.CommandChainDispatcher() try: dp.add(f,priority) except AttributeError: # it was not commandchain, plain old func - replace dp = f setattr(self.hooks,name, dp) #------------------------------------------------------------------------- # Things related to events #------------------------------------------------------------------------- def init_events(self): self.events = EventManager(self, available_events) self.events.register("pre_execute", self._clear_warning_registry) def register_post_execute(self, func): """DEPRECATED: Use ip.events.register('post_run_cell', func) Register a function for calling after code execution. """ raise ValueError( "ip.register_post_execute is deprecated since IPython 1.0, use " "ip.events.register('post_run_cell', func) instead." ) def _clear_warning_registry(self): # clear the warning registry, so that different code blocks with # overlapping line number ranges don't cause spurious suppression of # warnings (see gh-6611 for details) if "__warningregistry__" in self.user_global_ns: del self.user_global_ns["__warningregistry__"] #------------------------------------------------------------------------- # Things related to the "main" module #------------------------------------------------------------------------- def new_main_mod(self, filename, modname): """Return a new 'main' module object for user code execution. ``filename`` should be the path of the script which will be run in the module. Requests with the same filename will get the same module, with its namespace cleared. ``modname`` should be the module name - normally either '__main__' or the basename of the file without the extension. When scripts are executed via %run, we must keep a reference to their __main__ module around so that Python doesn't clear it, rendering references to module globals useless. This method keeps said reference in a private dict, keyed by the absolute path of the script. This way, for multiple executions of the same script we only keep one copy of the namespace (the last one), thus preventing memory leaks from old references while allowing the objects from the last execution to be accessible. """ filename = os.path.abspath(filename) try: main_mod = self._main_mod_cache[filename] except KeyError: main_mod = self._main_mod_cache[filename] = types.ModuleType( modname, doc="Module created for script run in IPython") else: main_mod.__dict__.clear() main_mod.__name__ = modname main_mod.__file__ = filename # It seems pydoc (and perhaps others) needs any module instance to # implement a __nonzero__ method main_mod.__nonzero__ = lambda : True return main_mod def clear_main_mod_cache(self): """Clear the cache of main modules. Mainly for use by utilities like %reset. Examples -------- In [15]: import IPython In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') In [17]: len(_ip._main_mod_cache) > 0 Out[17]: True In [18]: _ip.clear_main_mod_cache() In [19]: len(_ip._main_mod_cache) == 0 Out[19]: True """ self._main_mod_cache.clear() #------------------------------------------------------------------------- # Things related to debugging #------------------------------------------------------------------------- def init_pdb(self): # Set calling of pdb on exceptions # self.call_pdb is a property self.call_pdb = self.pdb def _get_call_pdb(self): return self._call_pdb def _set_call_pdb(self,val): if val not in (0,1,False,True): raise ValueError('new call_pdb value must be boolean') # store value in instance self._call_pdb = val # notify the actual exception handlers self.InteractiveTB.call_pdb = val call_pdb = property(_get_call_pdb,_set_call_pdb,None, 'Control auto-activation of pdb at exceptions') def debugger(self,force=False): """Call the pdb debugger. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false. """ if not (force or self.call_pdb): return if not hasattr(sys,'last_traceback'): error('No traceback has been produced, nothing to debug.') return self.InteractiveTB.debugger(force=True) #------------------------------------------------------------------------- # Things related to IPython's various namespaces #------------------------------------------------------------------------- default_user_namespaces = True def init_create_namespaces(self, user_module=None, user_ns=None): # Create the namespace where the user will operate. user_ns is # normally the only one used, and it is passed to the exec calls as # the locals argument. But we do carry a user_global_ns namespace # given as the exec 'globals' argument, This is useful in embedding # situations where the ipython shell opens in a context where the # distinction between locals and globals is meaningful. For # non-embedded contexts, it is just the same object as the user_ns dict. # FIXME. For some strange reason, __builtins__ is showing up at user # level as a dict instead of a module. This is a manual fix, but I # should really track down where the problem is coming from. Alex # Schmolck reported this problem first. # A useful post by Alex Martelli on this topic: # Re: inconsistent value from __builtins__ # Von: Alex Martelli <aleaxit@yahoo.com> # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends # Gruppen: comp.lang.python # Michael Hohn <hohn@hooknose.lbl.gov> wrote: # > >>> print type(builtin_check.get_global_binding('__builtins__')) # > <type 'dict'> # > >>> print type(__builtins__) # > <type 'module'> # > Is this difference in return value intentional? # Well, it's documented that '__builtins__' can be either a dictionary # or a module, and it's been that way for a long time. Whether it's # intentional (or sensible), I don't know. In any case, the idea is # that if you need to access the built-in namespace directly, you # should start with "import __builtin__" (note, no 's') which will # definitely give you a module. Yeah, it's somewhat confusing:-(. # These routines return a properly built module and dict as needed by # the rest of the code, and can also be used by extension writers to # generate properly initialized namespaces. if (user_ns is not None) or (user_module is not None): self.default_user_namespaces = False self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) # A record of hidden variables we have added to the user namespace, so # we can list later only variables defined in actual interactive use. self.user_ns_hidden = {} # Now that FakeModule produces a real module, we've run into a nasty # problem: after script execution (via %run), the module where the user # code ran is deleted. Now that this object is a true module (needed # so doctest and other tools work correctly), the Python module # teardown mechanism runs over it, and sets to None every variable # present in that module. Top-level references to objects from the # script survive, because the user_ns is updated with them. However, # calling functions defined in the script that use other things from # the script will fail, because the function's closure had references # to the original objects, which are now all None. So we must protect # these modules from deletion by keeping a cache. # # To avoid keeping stale modules around (we only need the one from the # last run), we use a dict keyed with the full path to the script, so # only the last version of the module is held in the cache. Note, # however, that we must cache the module *namespace contents* (their # __dict__). Because if we try to cache the actual modules, old ones # (uncached) could be destroyed while still holding references (such as # those held by GUI objects that tend to be long-lived)> # # The %reset command will flush this cache. See the cache_main_mod() # and clear_main_mod_cache() methods for details on use. # This is the cache used for 'main' namespaces self._main_mod_cache = {} # A table holding all the namespaces IPython deals with, so that # introspection facilities can search easily. self.ns_table = {'user_global':self.user_module.__dict__, 'user_local':self.user_ns, 'builtin':builtin_mod.__dict__ } def user_global_ns(self): return self.user_module.__dict__ def prepare_user_module(self, user_module=None, user_ns=None): """Prepare the module and namespace in which user code will be run. When IPython is started normally, both parameters are None: a new module is created automatically, and its __dict__ used as the namespace. If only user_module is provided, its __dict__ is used as the namespace. If only user_ns is provided, a dummy module is created, and user_ns becomes the global namespace. If both are provided (as they may be when embedding), user_ns is the local namespace, and user_module provides the global namespace. Parameters ---------- user_module : module, optional The current user module in which IPython is being run. If None, a clean module will be created. user_ns : dict, optional A namespace in which to run interactive commands. Returns ------- A tuple of user_module and user_ns, each properly initialised. """ if user_module is None and user_ns is not None: user_ns.setdefault("__name__", "__main__") user_module = DummyMod() user_module.__dict__ = user_ns if user_module is None: user_module = types.ModuleType("__main__", doc="Automatically created module for IPython interactive environment") # We must ensure that __builtin__ (without the final 's') is always # available and pointing to the __builtin__ *module*. For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html user_module.__dict__.setdefault('__builtin__', builtin_mod) user_module.__dict__.setdefault('__builtins__', builtin_mod) if user_ns is None: user_ns = user_module.__dict__ return user_module, user_ns def init_sys_modules(self): # We need to insert into sys.modules something that looks like a # module but which accesses the IPython namespace, for shelve and # pickle to work interactively. Normally they rely on getting # everything out of __main__, but for embedding purposes each IPython # instance has its own private namespace, so we can't go shoving # everything into __main__. # note, however, that we should only do this for non-embedded # ipythons, which really mimic the __main__.__dict__ with their own # namespace. Embedded instances, on the other hand, should not do # this because they need to manage the user local/global namespaces # only, but they live within a 'normal' __main__ (meaning, they # shouldn't overtake the execution environment of the script they're # embedded in). # This is overridden in the InteractiveShellEmbed subclass to a no-op. main_name = self.user_module.__name__ sys.modules[main_name] = self.user_module def init_user_ns(self): """Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this method. If they were not empty before, data will simply be added to them. """ # This function works in two parts: first we put a few things in # user_ns, and we sync that contents into user_ns_hidden so that these # initial variables aren't shown by %who. After the sync, we add the # rest of what we *do* want the user to see with %who even on a new # session (probably nothing, so they really only see their own stuff) # The user dict must *always* have a __builtin__ reference to the # Python standard __builtin__ namespace, which must be imported. # This is so that certain operations in prompt evaluation can be # reliably executed with builtins. Note that we can NOT use # __builtins__ (note the 's'), because that can either be a dict or a # module, and can even mutate at runtime, depending on the context # (Python makes no guarantees on it). In contrast, __builtin__ is # always a module object, though it must be explicitly imported. # For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html ns = {} # make global variables for user access to the histories ns['_ih'] = self.history_manager.input_hist_parsed ns['_oh'] = self.history_manager.output_hist ns['_dh'] = self.history_manager.dir_hist # user aliases to input and output histories. These shouldn't show up # in %who, as they can have very large reprs. ns['In'] = self.history_manager.input_hist_parsed ns['Out'] = self.history_manager.output_hist # Store myself as the public api!!! ns['get_ipython'] = self.get_ipython ns['exit'] = self.exiter ns['quit'] = self.exiter ns["open"] = _modified_open # Sync what we've added so far to user_ns_hidden so these aren't seen # by %who self.user_ns_hidden.update(ns) # Anything put into ns now would show up in %who. Think twice before # putting anything here, as we really want %who to show the user their # stuff, not our variables. # Finally, update the real user's namespace self.user_ns.update(ns) def all_ns_refs(self): """Get a list of references to all the namespace dictionaries in which IPython might store a user-created object. Note that this does not include the displayhook, which also caches objects from the output.""" return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ [m.__dict__ for m in self._main_mod_cache.values()] def reset(self, new_session=True, aggressive=False): """Clear all internal namespaces, and attempt to release references to user objects. If new_session is True, a new history session will be opened. """ # Clear histories self.history_manager.reset(new_session) # Reset counter used to index all histories if new_session: self.execution_count = 1 # Reset last execution result self.last_execution_succeeded = True self.last_execution_result = None # Flush cached output items if self.displayhook.do_full_cache: self.displayhook.flush() # The main execution namespaces must be cleared very carefully, # skipping the deletion of the builtin-related keys, because doing so # would cause errors in many object's __del__ methods. if self.user_ns is not self.user_global_ns: self.user_ns.clear() ns = self.user_global_ns drop_keys = set(ns.keys()) drop_keys.discard('__builtin__') drop_keys.discard('__builtins__') drop_keys.discard('__name__') for k in drop_keys: del ns[k] self.user_ns_hidden.clear() # Restore the user namespaces to minimal usability self.init_user_ns() if aggressive and not hasattr(self, "_sys_modules_keys"): print("Cannot restore sys.module, no snapshot") elif aggressive: print("culling sys module...") current_keys = set(sys.modules.keys()) for k in current_keys - self._sys_modules_keys: if k.startswith("multiprocessing"): continue del sys.modules[k] # Restore the default and user aliases self.alias_manager.clear_aliases() self.alias_manager.init_aliases() # Now define aliases that only make sense on the terminal, because they # need direct access to the console in a way that we can't emulate in # GUI or web frontend if os.name == 'posix': for cmd in ('clear', 'more', 'less', 'man'): if cmd not in self.magics_manager.magics['line']: self.alias_manager.soft_define_alias(cmd, cmd) # Flush the private list of module references kept for script # execution protection self.clear_main_mod_cache() def del_var(self, varname, by_name=False): """Delete a variable from the various namespaces, so that, as far as possible, we're not keeping any hidden references to it. Parameters ---------- varname : str The name of the variable to delete. by_name : bool If True, delete variables with the given name in each namespace. If False (default), find the variable in the user namespace, and delete references to it. """ if varname in ('__builtin__', '__builtins__'): raise ValueError("Refusing to delete %s" % varname) ns_refs = self.all_ns_refs if by_name: # Delete by name for ns in ns_refs: try: del ns[varname] except KeyError: pass else: # Delete by object try: obj = self.user_ns[varname] except KeyError as e: raise NameError("name '%s' is not defined" % varname) from e # Also check in output history ns_refs.append(self.history_manager.output_hist) for ns in ns_refs: to_delete = [n for n, o in ns.items() if o is obj] for name in to_delete: del ns[name] # Ensure it is removed from the last execution result if self.last_execution_result.result is obj: self.last_execution_result = None # displayhook keeps extra references, but not in a dictionary for name in ('_', '__', '___'): if getattr(self.displayhook, name) is obj: setattr(self.displayhook, name, None) def reset_selective(self, regex=None): """Clear selective variables from internal namespaces based on a specified regular expression. Parameters ---------- regex : string or compiled pattern, optional A regular expression pattern that will be used in searching variable names in the users namespaces. """ if regex is not None: try: m = re.compile(regex) except TypeError as e: raise TypeError('regex must be a string or compiled pattern') from e # Search for keys in each namespace that match the given regex # If a match is found, delete the key/value pair. for ns in self.all_ns_refs: for var in ns: if m.search(var): del ns[var] def push(self, variables, interactive=True): """Inject a group of variables into the IPython user namespace. Parameters ---------- variables : dict, str or list/tuple of str The variables to inject into the user's namespace. If a dict, a simple update is done. If a str, the string is assumed to have variable names separated by spaces. A list/tuple of str can also be used to give the variable names. If just the variable names are give (list/tuple/str) then the variable values looked up in the callers frame. interactive : bool If True (default), the variables will be listed with the ``who`` magic. """ vdict = None # We need a dict of name/value pairs to do namespace updates. if isinstance(variables, dict): vdict = variables elif isinstance(variables, (str, list, tuple)): if isinstance(variables, str): vlist = variables.split() else: vlist = variables vdict = {} cf = sys._getframe(1) for name in vlist: try: vdict[name] = eval(name, cf.f_globals, cf.f_locals) except: print('Could not get variable %s from %s' % (name,cf.f_code.co_name)) else: raise ValueError('variables must be a dict/str/list/tuple') # Propagate variables to user namespace self.user_ns.update(vdict) # And configure interactive visibility user_ns_hidden = self.user_ns_hidden if interactive: for name in vdict: user_ns_hidden.pop(name, None) else: user_ns_hidden.update(vdict) def drop_by_id(self, variables): """Remove a dict of variables from the user namespace, if they are the same as the values in the dictionary. This is intended for use by extensions: variables that they've added can be taken back out if they are unloaded, without removing any that the user has overwritten. Parameters ---------- variables : dict A dictionary mapping object names (as strings) to the objects. """ for name, obj in variables.items(): if name in self.user_ns and self.user_ns[name] is obj: del self.user_ns[name] self.user_ns_hidden.pop(name, None) #------------------------------------------------------------------------- # Things related to object introspection #------------------------------------------------------------------------- def _find_parts(oname: str) -> Tuple[bool, ListType[str]]: """ Given an object name, return a list of parts of this object name. Basically split on docs when using attribute access, and extract the value when using square bracket. For example foo.bar[3].baz[x] -> foo, bar, 3, baz, x Returns ------- parts_ok: bool wether we were properly able to parse parts. parts: list of str extracted parts """ raw_parts = oname.split(".") parts = [] parts_ok = True for p in raw_parts: if p.endswith("]"): var, *indices = p.split("[") if not var.isidentifier(): parts_ok = False break parts.append(var) for ind in indices: if ind[-1] != "]" and not is_integer_string(ind[:-1]): parts_ok = False break parts.append(ind[:-1]) continue if not p.isidentifier(): parts_ok = False parts.append(p) return parts_ok, parts def _ofind( self, oname: str, namespaces: Optional[Sequence[Tuple[str, AnyType]]] = None ) -> OInfo: """Find an object in the available namespaces. Returns ------- OInfo with fields: - ismagic - isalias - found - obj - namespac - parent Has special code to detect magic functions. """ oname = oname.strip() parts_ok, parts = self._find_parts(oname) if ( not oname.startswith(ESC_MAGIC) and not oname.startswith(ESC_MAGIC2) and not parts_ok ): return OInfo( ismagic=False, isalias=False, found=False, obj=None, namespace=None, parent=None, ) if namespaces is None: # Namespaces to search in: # Put them in a list. The order is important so that we # find things in the same order that Python finds them. namespaces = [ ('Interactive', self.user_ns), ('Interactive (global)', self.user_global_ns), ('Python builtin', builtin_mod.__dict__), ] ismagic = False isalias = False found = False ospace = None parent = None obj = None # Look for the given name by splitting it in parts. If the head is # found, then we look for all the remaining parts as members, and only # declare success if we can find them all. oname_parts = parts oname_head, oname_rest = oname_parts[0],oname_parts[1:] for nsname,ns in namespaces: try: obj = ns[oname_head] except KeyError: continue else: for idx, part in enumerate(oname_rest): try: parent = obj # The last part is looked up in a special way to avoid # descriptor invocation as it may raise or have side # effects. if idx == len(oname_rest) - 1: obj = self._getattr_property(obj, part) else: if is_integer_string(part): obj = obj[int(part)] else: obj = getattr(obj, part) except: # Blanket except b/c some badly implemented objects # allow __getattr__ to raise exceptions other than # AttributeError, which then crashes IPython. break else: # If we finish the for loop (no break), we got all members found = True ospace = nsname break # namespace loop # Try to see if it's magic if not found: obj = None if oname.startswith(ESC_MAGIC2): oname = oname.lstrip(ESC_MAGIC2) obj = self.find_cell_magic(oname) elif oname.startswith(ESC_MAGIC): oname = oname.lstrip(ESC_MAGIC) obj = self.find_line_magic(oname) else: # search without prefix, so run? will find %run? obj = self.find_line_magic(oname) if obj is None: obj = self.find_cell_magic(oname) if obj is not None: found = True ospace = 'IPython internal' ismagic = True isalias = isinstance(obj, Alias) # Last try: special-case some literals like '', [], {}, etc: if not found and oname_head in ["''",'""','[]','{}','()']: obj = eval(oname_head) found = True ospace = 'Interactive' return OInfo( obj=obj, found=found, parent=parent, ismagic=ismagic, isalias=isalias, namespace=ospace, ) def _getattr_property(obj, attrname): """Property-aware getattr to use in object finding. If attrname represents a property, return it unevaluated (in case it has side effects or raises an error. """ if not isinstance(obj, type): try: # `getattr(type(obj), attrname)` is not guaranteed to return # `obj`, but does so for property: # # property.__get__(self, None, cls) -> self # # The universal alternative is to traverse the mro manually # searching for attrname in class dicts. if is_integer_string(attrname): return obj[int(attrname)] else: attr = getattr(type(obj), attrname) except AttributeError: pass else: # This relies on the fact that data descriptors (with both # __get__ & __set__ magic methods) take precedence over # instance-level attributes: # # class A(object): # @property # def foobar(self): return 123 # a = A() # a.__dict__['foobar'] = 345 # a.foobar # == 123 # # So, a property may be returned right away. if isinstance(attr, property): return attr # Nothing helped, fall back. return getattr(obj, attrname) def _object_find(self, oname, namespaces=None) -> OInfo: """Find an object and return a struct with info about it.""" return self._ofind(oname, namespaces) def _inspect(self, meth, oname, namespaces=None, **kw): """Generic interface to the inspector system. This function is meant to be called by pdef, pdoc & friends. """ info: OInfo = self._object_find(oname, namespaces) docformat = ( sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None ) if info.found or hasattr(info.parent, oinspect.HOOK_NAME): pmethod = getattr(self.inspector, meth) # TODO: only apply format_screen to the plain/text repr of the mime # bundle. formatter = format_screen if info.ismagic else docformat if meth == 'pdoc': pmethod(info.obj, oname, formatter) elif meth == 'pinfo': pmethod( info.obj, oname, formatter, info, enable_html_pager=self.enable_html_pager, **kw, ) else: pmethod(info.obj, oname) else: print('Object `%s` not found.' % oname) return 'not found' # so callers can take other action def object_inspect(self, oname, detail_level=0): """Get object info about oname""" with self.builtin_trap: info = self._object_find(oname) if info.found: return self.inspector.info(info.obj, oname, info=info, detail_level=detail_level ) else: return oinspect.object_info(name=oname, found=False) def object_inspect_text(self, oname, detail_level=0): """Get object info as formatted text""" return self.object_inspect_mime(oname, detail_level)['text/plain'] def object_inspect_mime(self, oname, detail_level=0, omit_sections=()): """Get object info as a mimebundle of formatted representations. A mimebundle is a dictionary, keyed by mime-type. It must always have the key `'text/plain'`. """ with self.builtin_trap: info = self._object_find(oname) if info.found: docformat = ( sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None ) return self.inspector._get_info( info.obj, oname, info=info, detail_level=detail_level, formatter=docformat, omit_sections=omit_sections, ) else: raise KeyError(oname) #------------------------------------------------------------------------- # Things related to history management #------------------------------------------------------------------------- def init_history(self): """Sets up the command history, and starts regular autosaves.""" self.history_manager = HistoryManager(shell=self, parent=self) self.configurables.append(self.history_manager) #------------------------------------------------------------------------- # Things related to exception handling and tracebacks (not debugging) #------------------------------------------------------------------------- debugger_cls = InterruptiblePdb def init_traceback_handlers(self, custom_exceptions): # Syntax error handler. self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) # The interactive one is initialized with an offset, meaning we always # want to remove the topmost item in the traceback, which is our own # internal code. Valid modes: ['Plain','Context','Verbose','Minimal'] self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', color_scheme='NoColor', tb_offset = 1, debugger_cls=self.debugger_cls, parent=self) # The instance will store a pointer to the system-wide exception hook, # so that runtime code (such as magics) can access it. This is because # during the read-eval loop, it may get temporarily overwritten. self.sys_excepthook = sys.excepthook # and add any custom exception handlers the user may have specified self.set_custom_exc(*custom_exceptions) # Set the exception mode self.InteractiveTB.set_mode(mode=self.xmode) def set_custom_exc(self, exc_tuple, handler): """set_custom_exc(exc_tuple, handler) Set a custom exception handler, which will be called if any of the exceptions in exc_tuple occur in the mainloop (specifically, in the run_code() method). Parameters ---------- exc_tuple : tuple of exception classes A *tuple* of exception classes, for which to call the defined handler. It is very important that you use a tuple, and NOT A LIST here, because of the way Python's except statement works. If you only want to trap a single exception, use a singleton tuple:: exc_tuple == (MyCustomException,) handler : callable handler must have the following signature:: def my_handler(self, etype, value, tb, tb_offset=None): ... return structured_traceback Your handler must return a structured traceback (a list of strings), or None. This will be made into an instance method (via types.MethodType) of IPython itself, and it will be called if any of the exceptions listed in the exc_tuple are caught. If the handler is None, an internal basic one is used, which just prints basic info. To protect IPython from crashes, if your handler ever raises an exception or returns an invalid result, it will be immediately disabled. Notes ----- WARNING: by putting in your own exception handler into IPython's main execution loop, you run a very good chance of nasty crashes. This facility should only be used if you really know what you are doing. """ if not isinstance(exc_tuple, tuple): raise TypeError("The custom exceptions must be given as a tuple.") def dummy_handler(self, etype, value, tb, tb_offset=None): print('*** Simple custom exception handler ***') print('Exception type :', etype) print('Exception value:', value) print('Traceback :', tb) def validate_stb(stb): """validate structured traceback return type return type of CustomTB *should* be a list of strings, but allow single strings or None, which are harmless. This function will *always* return a list of strings, and will raise a TypeError if stb is inappropriate. """ msg = "CustomTB must return list of strings, not %r" % stb if stb is None: return [] elif isinstance(stb, str): return [stb] elif not isinstance(stb, list): raise TypeError(msg) # it's a list for line in stb: # check every element if not isinstance(line, str): raise TypeError(msg) return stb if handler is None: wrapped = dummy_handler else: def wrapped(self,etype,value,tb,tb_offset=None): """wrap CustomTB handler, to protect IPython from user code This makes it harder (but not impossible) for custom exception handlers to crash IPython. """ try: stb = handler(self,etype,value,tb,tb_offset=tb_offset) return validate_stb(stb) except: # clear custom handler immediately self.set_custom_exc((), None) print("Custom TB Handler failed, unregistering", file=sys.stderr) # show the exception in handler first stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) print(self.InteractiveTB.stb2text(stb)) print("The original exception:") stb = self.InteractiveTB.structured_traceback( (etype,value,tb), tb_offset=tb_offset ) return stb self.CustomTB = types.MethodType(wrapped,self) self.custom_exceptions = exc_tuple def excepthook(self, etype, value, tb): """One more defense for GUI apps that call sys.excepthook. GUI frameworks like wxPython trap exceptions and call sys.excepthook themselves. I guess this is a feature that enables them to keep running after exceptions that would otherwise kill their mainloop. This is a bother for IPython which expects to catch all of the program exceptions with a try: except: statement. Normally, IPython sets sys.excepthook to a CrashHandler instance, so if any app directly invokes sys.excepthook, it will look to the user like IPython crashed. In order to work around this, we can disable the CrashHandler and replace it with this excepthook instead, which prints a regular traceback using our InteractiveTB. In this fashion, apps which call sys.excepthook will generate a regular-looking exception from IPython, and the CrashHandler will only be triggered by real IPython crashes. This hook should be used sparingly, only in places which are not likely to be true IPython errors. """ self.showtraceback((etype, value, tb), tb_offset=0) def _get_exc_info(self, exc_tuple=None): """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. raises ValueError if none of these contain any information """ if exc_tuple is None: etype, value, tb = sys.exc_info() else: etype, value, tb = exc_tuple if etype is None: if hasattr(sys, 'last_type'): etype, value, tb = sys.last_type, sys.last_value, \ sys.last_traceback if etype is None: raise ValueError("No exception to find") # Now store the exception info in sys.last_type etc. # WARNING: these variables are somewhat deprecated and not # necessarily safe to use in a threaded environment, but tools # like pdb depend on their existence, so let's set them. If we # find problems in the field, we'll need to revisit their use. sys.last_type = etype sys.last_value = value sys.last_traceback = tb return etype, value, tb def show_usage_error(self, exc): """Show a short message for UsageErrors These are special exceptions that shouldn't show a traceback. """ print("UsageError: %s" % exc, file=sys.stderr) def get_exception_only(self, exc_tuple=None): """ Return as a string (ending with a newline) the exception that just occurred, without any traceback. """ etype, value, tb = self._get_exc_info(exc_tuple) msg = traceback.format_exception_only(etype, value) return ''.join(msg) def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, exception_only=False, running_compiled_code=False): """Display the exception that just occurred. If nothing is known about the exception, this is the method which should be used throughout the code for presenting user tracebacks, rather than directly invoking the InteractiveTB object. A specific showsyntaxerror() also exists, but this method can take care of calling it if needed, so unless you are explicitly catching a SyntaxError exception, don't try to analyze the stack manually and simply call this method.""" try: try: etype, value, tb = self._get_exc_info(exc_tuple) except ValueError: print('No traceback available to show.', file=sys.stderr) return if issubclass(etype, SyntaxError): # Though this won't be called by syntax errors in the input # line, there may be SyntaxError cases with imported code. self.showsyntaxerror(filename, running_compiled_code) elif etype is UsageError: self.show_usage_error(value) else: if exception_only: stb = ['An exception has occurred, use %tb to see ' 'the full traceback.\n'] stb.extend(self.InteractiveTB.get_exception_only(etype, value)) else: try: # Exception classes can customise their traceback - we # use this in IPython.parallel for exceptions occurring # in the engines. This should return a list of strings. if hasattr(value, "_render_traceback_"): stb = value._render_traceback_() else: stb = self.InteractiveTB.structured_traceback( etype, value, tb, tb_offset=tb_offset ) except Exception: print( "Unexpected exception formatting exception. Falling back to standard exception" ) traceback.print_exc() return None self._showtraceback(etype, value, stb) if self.call_pdb: # drop into debugger self.debugger(force=True) return # Actually show the traceback self._showtraceback(etype, value, stb) except KeyboardInterrupt: print('\n' + self.get_exception_only(), file=sys.stderr) def _showtraceback(self, etype, evalue, stb: str): """Actually show a traceback. Subclasses may override this method to put the traceback on a different place, like a side channel. """ val = self.InteractiveTB.stb2text(stb) try: print(val) except UnicodeEncodeError: print(val.encode("utf-8", "backslashreplace").decode()) def showsyntaxerror(self, filename=None, running_compiled_code=False): """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). If the syntax error occurred when running a compiled code (i.e. running_compile_code=True), longer stack trace will be displayed. """ etype, value, last_traceback = self._get_exc_info() if filename and issubclass(etype, SyntaxError): try: value.filename = filename except: # Not the format we expect; leave it alone pass # If the error occurred when executing compiled code, we should provide full stacktrace. elist = traceback.extract_tb(last_traceback) if running_compiled_code else [] stb = self.SyntaxTB.structured_traceback(etype, value, elist) self._showtraceback(etype, value, stb) # This is overridden in TerminalInteractiveShell to show a message about # the %paste magic. def showindentationerror(self): """Called by _run_cell when there's an IndentationError in code entered at the prompt. This is overridden in TerminalInteractiveShell to show a message about the %paste magic.""" self.showsyntaxerror() def set_next_input(self, s, replace=False): """ Sets the 'default' input string for the next command line. Example:: In [1]: _ip.set_next_input("Hello Word") In [2]: Hello Word_ # cursor is here """ self.rl_next_input = s def _indent_current_str(self): """return the current level of indentation as a string""" return self.input_splitter.get_indent_spaces() * ' ' #------------------------------------------------------------------------- # Things related to text completion #------------------------------------------------------------------------- def init_completer(self): """Initialize the completion machinery. This creates completion machinery that can be used by client code, either interactively in-process (typically triggered by the readline library), programmatically (such as in test suites) or out-of-process (typically over the network by remote frontends). """ from IPython.core.completer import IPCompleter from IPython.core.completerlib import ( cd_completer, magic_run_completer, module_completer, reset_completer, ) self.Completer = IPCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, parent=self, ) self.configurables.append(self.Completer) # Add custom completers to the basic ones built into IPCompleter sdisp = self.strdispatchers.get('complete_command', StrDispatch()) self.strdispatchers['complete_command'] = sdisp self.Completer.custom_completers = sdisp self.set_hook('complete_command', module_completer, str_key = 'import') self.set_hook('complete_command', module_completer, str_key = 'from') self.set_hook('complete_command', module_completer, str_key = '%aimport') self.set_hook('complete_command', magic_run_completer, str_key = '%run') self.set_hook('complete_command', cd_completer, str_key = '%cd') self.set_hook('complete_command', reset_completer, str_key = '%reset') def complete(self, text, line=None, cursor_pos=None): """Return the completed text and a list of completions. Parameters ---------- text : string A string of text to be completed on. It can be given as empty and instead a line/position pair are given. In this case, the completer itself will split the line like readline does. line : string, optional The complete line that text is part of. cursor_pos : int, optional The position of the cursor on the input line. Returns ------- text : string The actual text that was completed. matches : list A sorted list with all possible completions. Notes ----- The optional arguments allow the completion to take more context into account, and are part of the low-level completion API. This is a wrapper around the completion mechanism, similar to what readline does at the command line when the TAB key is hit. By exposing it as a method, it can be used by other non-readline environments (such as GUIs) for text completion. Examples -------- In [1]: x = 'hello' In [2]: _ip.complete('x.l') Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) """ # Inject names into __builtin__ so we can complete on the added names. with self.builtin_trap: return self.Completer.complete(text, line, cursor_pos) def set_custom_completer(self, completer, pos=0) -> None: """Adds a new custom completer function. The position argument (defaults to 0) is the index in the completers list where you want the completer to be inserted. `completer` should have the following signature:: def completion(self: Completer, text: string) -> List[str]: raise NotImplementedError It will be bound to the current Completer instance and pass some text and return a list with current completions to suggest to the user. """ newcomp = types.MethodType(completer, self.Completer) self.Completer.custom_matchers.insert(pos,newcomp) def set_completer_frame(self, frame=None): """Set the frame of the completer.""" if frame: self.Completer.namespace = frame.f_locals self.Completer.global_namespace = frame.f_globals else: self.Completer.namespace = self.user_ns self.Completer.global_namespace = self.user_global_ns #------------------------------------------------------------------------- # Things related to magics #------------------------------------------------------------------------- def init_magics(self): from IPython.core import magics as m self.magics_manager = magic.MagicsManager(shell=self, parent=self, user_magics=m.UserMagics(self)) self.configurables.append(self.magics_manager) # Expose as public API from the magics manager self.register_magics = self.magics_manager.register self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, m.NamespaceMagics, m.OSMagics, m.PackagingMagics, m.PylabMagics, m.ScriptMagics, ) self.register_magics(m.AsyncMagics) # Register Magic Aliases mman = self.magics_manager # FIXME: magic aliases should be defined by the Magics classes # or in MagicsManager, not here mman.register_alias('ed', 'edit') mman.register_alias('hist', 'history') mman.register_alias('rep', 'recall') mman.register_alias('SVG', 'svg', 'cell') mman.register_alias('HTML', 'html', 'cell') mman.register_alias('file', 'writefile', 'cell') # FIXME: Move the color initialization to the DisplayHook, which # should be split into a prompt manager and displayhook. We probably # even need a centralize colors management object. self.run_line_magic('colors', self.colors) # Defined here so that it's included in the documentation def register_magic_function(self, func, magic_kind='line', magic_name=None): self.magics_manager.register_function( func, magic_kind=magic_kind, magic_name=magic_name ) def _find_with_lazy_load(self, /, type_, magic_name: str): """ Try to find a magic potentially lazy-loading it. Parameters ---------- type_: "line"|"cell" the type of magics we are trying to find/lazy load. magic_name: str The name of the magic we are trying to find/lazy load Note that this may have any side effects """ finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_] fn = finder(magic_name) if fn is not None: return fn lazy = self.magics_manager.lazy_magics.get(magic_name) if lazy is None: return None self.run_line_magic("load_ext", lazy) res = finder(magic_name) return res def run_line_magic(self, magic_name: str, line, _stack_depth=1): """Execute the given line magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the input line as a single string. _stack_depth : int If run_line_magic() is called from magic() then _stack_depth=2. This is added to ensure backward compatibility for use of 'get_ipython().magic()' """ fn = self._find_with_lazy_load("line", magic_name) if fn is None: lazy = self.magics_manager.lazy_magics.get(magic_name) if lazy: self.run_line_magic("load_ext", lazy) fn = self.find_line_magic(magic_name) if fn is None: cm = self.find_cell_magic(magic_name) etpl = "Line magic function `%%%s` not found%s." extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' 'did you mean that instead?)' % magic_name ) raise UsageError(etpl % (magic_name, extra)) else: # Note: this is the distance in the stack to the user's frame. # This will need to be updated if the internal calling logic gets # refactored, or else we'll be expanding the wrong variables. # Determine stack_depth depending on where run_line_magic() has been called stack_depth = _stack_depth if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): # magic has opted out of var_expand magic_arg_s = line else: magic_arg_s = self.var_expand(line, stack_depth) # Put magic args in a list so we can call with f(*a) syntax args = [magic_arg_s] kwargs = {} # Grab local namespace if we need it: if getattr(fn, "needs_local_scope", False): kwargs['local_ns'] = self.get_local_scope(stack_depth) with self.builtin_trap: result = fn(*args, **kwargs) # The code below prevents the output from being displayed # when using magics with decodator @output_can_be_silenced # when the last Python token in the expression is a ';'. if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): if DisplayHook.semicolon_at_end_of_expression(magic_arg_s): return None return result def get_local_scope(self, stack_depth): """Get local scope at given stack depth. Parameters ---------- stack_depth : int Depth relative to calling frame """ return sys._getframe(stack_depth + 1).f_locals def run_cell_magic(self, magic_name, line, cell): """Execute the given cell magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the first input line as a single string. cell : str The body of the cell as a (possibly multiline) string. """ fn = self._find_with_lazy_load("cell", magic_name) if fn is None: lm = self.find_line_magic(magic_name) etpl = "Cell magic `%%{0}` not found{1}." extra = '' if lm is None else (' (But line magic `%{0}` exists, ' 'did you mean that instead?)'.format(magic_name)) raise UsageError(etpl.format(magic_name, extra)) elif cell == '': message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) if self.find_line_magic(magic_name) is not None: message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) raise UsageError(message) else: # Note: this is the distance in the stack to the user's frame. # This will need to be updated if the internal calling logic gets # refactored, or else we'll be expanding the wrong variables. stack_depth = 2 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): # magic has opted out of var_expand magic_arg_s = line else: magic_arg_s = self.var_expand(line, stack_depth) kwargs = {} if getattr(fn, "needs_local_scope", False): kwargs['local_ns'] = self.user_ns with self.builtin_trap: args = (magic_arg_s, cell) result = fn(*args, **kwargs) # The code below prevents the output from being displayed # when using magics with decodator @output_can_be_silenced # when the last Python token in the expression is a ';'. if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): if DisplayHook.semicolon_at_end_of_expression(cell): return None return result def find_line_magic(self, magic_name): """Find and return a line magic by name. Returns None if the magic isn't found.""" return self.magics_manager.magics['line'].get(magic_name) def find_cell_magic(self, magic_name): """Find and return a cell magic by name. Returns None if the magic isn't found.""" return self.magics_manager.magics['cell'].get(magic_name) def find_magic(self, magic_name, magic_kind='line'): """Find and return a magic of the given type by name. Returns None if the magic isn't found.""" return self.magics_manager.magics[magic_kind].get(magic_name) def magic(self, arg_s): """ DEPRECATED Deprecated since IPython 0.13 (warning added in 8.1), use run_line_magic(magic_name, parameter_s). Call a magic function by name. Input: a string containing the name of the magic function to call and any additional arguments to be passed to the magic. magic('name -opt foo bar') is equivalent to typing at the ipython prompt: In[1]: %name -opt foo bar To call a magic without arguments, simply use magic('name'). This provides a proper Python function to call IPython's magics in any valid Python code you can type at the interpreter, including loops and compound statements. """ warnings.warn( "`magic(...)` is deprecated since IPython 0.13 (warning added in " "8.1), use run_line_magic(magic_name, parameter_s).", DeprecationWarning, stacklevel=2, ) # TODO: should we issue a loud deprecation warning here? magic_name, _, magic_arg_s = arg_s.partition(' ') magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) #------------------------------------------------------------------------- # Things related to macros #------------------------------------------------------------------------- def define_macro(self, name, themacro): """Define a new macro Parameters ---------- name : str The name of the macro. themacro : str or Macro The action to do upon invoking the macro. If a string, a new Macro object is created by passing the string to it. """ from IPython.core import macro if isinstance(themacro, str): themacro = macro.Macro(themacro) if not isinstance(themacro, macro.Macro): raise ValueError('A macro must be a string or a Macro instance.') self.user_ns[name] = themacro #------------------------------------------------------------------------- # Things related to the running of system commands #------------------------------------------------------------------------- def system_piped(self, cmd): """Call the given cmd in a subprocess, piping stdout/err Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. Should not be a command that expects input other than simple text. """ if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test # We do not support backgrounding processes because we either use # pexpect or pipes to read from. Users can always just call # os.system() or use ip.system=ip.system_raw # if they really want a background process. raise OSError("Background processes not supported.") # we explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) def system_raw(self, cmd): """Call the given cmd in a subprocess using os.system on Windows or subprocess.call using the system shell on other platforms. Parameters ---------- cmd : str Command to execute. """ cmd = self.var_expand(cmd, depth=1) # warn if there is an IPython magic alternative. main_cmd = cmd.split()[0] has_magic_alternatives = ("pip", "conda", "cd") if main_cmd in has_magic_alternatives: warnings.warn( ( "You executed the system command !{0} which may not work " "as expected. Try the IPython magic %{0} instead." ).format(main_cmd) ) # protect os.system from UNC paths on Windows, which it can't handle: if sys.platform == 'win32': from IPython.utils._process_win32 import AvoidUNCPath with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) try: ec = os.system(cmd) except KeyboardInterrupt: print('\n' + self.get_exception_only(), file=sys.stderr) ec = -2 else: # For posix the result of the subprocess.call() below is an exit # code, which by convention is zero for success, positive for # program failure. Exit codes above 128 are reserved for signals, # and the formula for converting a signal to an exit code is usually # signal_number+128. To more easily differentiate between exit # codes and signals, ipython uses negative numbers. For instance # since control-c is signal 2 but exit code 130, ipython's # _exit_code variable will read -2. Note that some shells like # csh and fish don't follow sh/bash conventions for exit codes. executable = os.environ.get('SHELL', None) try: # Use env shell instead of default /bin/sh ec = subprocess.call(cmd, shell=True, executable=executable) except KeyboardInterrupt: # intercept control-C; a long traceback is not useful here print('\n' + self.get_exception_only(), file=sys.stderr) ec = 130 if ec > 128: ec = -(ec - 128) # We explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. Note the semantics # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, # but raising SystemExit(_exit_code) will give status 254! self.user_ns['_exit_code'] = ec # use piped system by default, because it is better behaved system = system_piped def getoutput(self, cmd, split=True, depth=0): """Get output (possibly including stderr) from a subprocess. Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. split : bool, optional If True, split the output into an IPython SList. Otherwise, an IPython LSString is returned. These are objects similar to normal lists and strings, with a few convenience attributes for easier manipulation of line-based output. You can use '?' on them for details. depth : int, optional How many frames above the caller are the local variables which should be expanded in the command string? The default (0) assumes that the expansion variables are in the stack frame calling this function. """ if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test raise OSError("Background processes not supported.") out = getoutput(self.var_expand(cmd, depth=depth+1)) if split: out = SList(out.splitlines()) else: out = LSString(out) return out #------------------------------------------------------------------------- # Things related to aliases #------------------------------------------------------------------------- def init_alias(self): self.alias_manager = AliasManager(shell=self, parent=self) self.configurables.append(self.alias_manager) #------------------------------------------------------------------------- # Things related to extensions #------------------------------------------------------------------------- def init_extension_manager(self): self.extension_manager = ExtensionManager(shell=self, parent=self) self.configurables.append(self.extension_manager) #------------------------------------------------------------------------- # Things related to payloads #------------------------------------------------------------------------- def init_payload(self): self.payload_manager = PayloadManager(parent=self) self.configurables.append(self.payload_manager) #------------------------------------------------------------------------- # Things related to the prefilter #------------------------------------------------------------------------- def init_prefilter(self): self.prefilter_manager = PrefilterManager(shell=self, parent=self) self.configurables.append(self.prefilter_manager) # Ultimately this will be refactored in the new interpreter code, but # for now, we should expose the main prefilter method (there's legacy # code out there that may rely on this). self.prefilter = self.prefilter_manager.prefilter_lines def auto_rewrite_input(self, cmd): """Print to the screen the rewritten form of the user's command. This shows visual feedback by rewriting input lines that cause automatic calling to kick in, like:: /f x into:: ------> f(x) after the user's input prompt. This helps the user understand that the input line was transformed automatically by IPython. """ if not self.show_rewritten_input: return # This is overridden in TerminalInteractiveShell to use fancy prompts print("------> " + cmd) #------------------------------------------------------------------------- # Things related to extracting values/expressions from kernel and user_ns #------------------------------------------------------------------------- def _user_obj_error(self): """return simple exception dict for use in user_expressions """ etype, evalue, tb = self._get_exc_info() stb = self.InteractiveTB.get_exception_only(etype, evalue) exc_info = { "status": "error", "traceback": stb, "ename": etype.__name__, "evalue": py3compat.safe_unicode(evalue), } return exc_info def _format_user_obj(self, obj): """format a user object to display dict for use in user_expressions """ data, md = self.display_formatter.format(obj) value = { 'status' : 'ok', 'data' : data, 'metadata' : md, } return value def user_expressions(self, expressions): """Evaluate a dict of expressions in the user's namespace. Parameters ---------- expressions : dict A dict with string keys and string values. The expression values should be valid Python expressions, each of which will be evaluated in the user namespace. Returns ------- A dict, keyed like the input expressions dict, with the rich mime-typed display_data of each value. """ out = {} user_ns = self.user_ns global_ns = self.user_global_ns for key, expr in expressions.items(): try: value = self._format_user_obj(eval(expr, global_ns, user_ns)) except: value = self._user_obj_error() out[key] = value return out #------------------------------------------------------------------------- # Things related to the running of code #------------------------------------------------------------------------- def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec(cmd, self.user_global_ns, self.user_ns) def ev(self, expr): """Evaluate python expression expr in user namespace. Returns the result of evaluation """ with self.builtin_trap: return eval(expr, self.user_global_ns, self.user_ns) def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False): """A safe version of the builtin execfile(). This version will never throw an exception, but instead print helpful error messages to the screen. This only works on pure Python files with the .py extension. Parameters ---------- fname : string The name of the file to be executed. *where : tuple One or two namespaces, passed to execfile() as (globals,locals). If only one is given, it is passed as both. exit_ignore : bool (False) If True, then silence SystemExit for non-zero status (it is always silenced for zero status, as it is so common). raise_exceptions : bool (False) If True raise exceptions everywhere. Meant for testing. shell_futures : bool (False) If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. """ fname = Path(fname).expanduser().resolve() # Make sure we can open the file try: with fname.open("rb"): pass except: warn('Could not open file <%s> for safe execution.' % fname) return # Find things also in current directory. This is needed to mimic the # behavior of running a script from the system command line, where # Python inserts the script's directory into sys.path dname = str(fname.parent) with prepended_to_syspath(dname), self.builtin_trap: try: glob, loc = (where + (None, ))[:2] py3compat.execfile( fname, glob, loc, self.compile if shell_futures else None) except SystemExit as status: # If the call was made with 0 or None exit status (sys.exit(0) # or sys.exit() ), don't bother showing a traceback, as both of # these are considered normal by the OS: # > python -c'import sys;sys.exit(0)'; echo $? # 0 # > python -c'import sys;sys.exit()'; echo $? # 0 # For other exit status, we show the exception unless # explicitly silenced, but only in short form. if status.code: if raise_exceptions: raise if not exit_ignore: self.showtraceback(exception_only=True) except: if raise_exceptions: raise # tb offset is 2 because we wrap execfile self.showtraceback(tb_offset=2) def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. Parameters ---------- fname : str The name of the file to execute. The filename must have a .ipy or .ipynb extension. shell_futures : bool (False) If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. raise_exceptions : bool (False) If True raise exceptions everywhere. Meant for testing. """ fname = Path(fname).expanduser().resolve() # Make sure we can open the file try: with fname.open("rb"): pass except: warn('Could not open file <%s> for safe execution.' % fname) return # Find things also in current directory. This is needed to mimic the # behavior of running a script from the system command line, where # Python inserts the script's directory into sys.path dname = str(fname.parent) def get_cells(): """generator for sequence of code blocks to run""" if fname.suffix == ".ipynb": from nbformat import read nb = read(fname, as_version=4) if not nb.cells: return for cell in nb.cells: if cell.cell_type == 'code': yield cell.source else: yield fname.read_text(encoding="utf-8") with prepended_to_syspath(dname): try: for cell in get_cells(): result = self.run_cell(cell, silent=True, shell_futures=shell_futures) if raise_exceptions: result.raise_error() elif not result.success: break except: if raise_exceptions: raise self.showtraceback() warn('Unknown failure executing file: <%s>' % fname) def safe_run_module(self, mod_name, where): """A safe version of runpy.run_module(). This version will never throw an exception, but instead print helpful error messages to the screen. `SystemExit` exceptions with status code 0 or None are ignored. Parameters ---------- mod_name : string The name of the module to be executed. where : dict The globals namespace. """ try: try: where.update( runpy.run_module(str(mod_name), run_name="__main__", alter_sys=True) ) except SystemExit as status: if status.code: raise except: self.showtraceback() warn('Unknown failure executing module: <%s>' % mod_name) def run_cell( self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None, ): """Run a complete IPython cell. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back into IPython's machinery, this should be set to False. silent : bool If True, avoid side-effects, such as implicit displayhooks and and logging. silent=True forces store_history=False. shell_futures : bool If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. Returns ------- result : :class:`ExecutionResult` """ result = None try: result = self._run_cell( raw_cell, store_history, silent, shell_futures, cell_id ) finally: self.events.trigger('post_execute') if not silent: self.events.trigger('post_run_cell', result) return result def _run_cell( self, raw_cell: str, store_history: bool, silent: bool, shell_futures: bool, cell_id: str, ) -> ExecutionResult: """Internal method to run a complete IPython cell.""" # we need to avoid calling self.transform_cell multiple time on the same thing # so we need to store some results: preprocessing_exc_tuple = None try: transformed_cell = self.transform_cell(raw_cell) except Exception: transformed_cell = raw_cell preprocessing_exc_tuple = sys.exc_info() assert transformed_cell is not None coro = self.run_cell_async( raw_cell, store_history=store_history, silent=silent, shell_futures=shell_futures, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple, cell_id=cell_id, ) # run_cell_async is async, but may not actually need an eventloop. # when this is the case, we want to run it using the pseudo_sync_runner # so that code can invoke eventloops (for example via the %run , and # `%paste` magic. if self.trio_runner: runner = self.trio_runner elif self.should_run_async( raw_cell, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple, ): runner = self.loop_runner else: runner = _pseudo_sync_runner try: result = runner(coro) except BaseException as e: info = ExecutionInfo( raw_cell, store_history, silent, shell_futures, cell_id ) result = ExecutionResult(info) result.error_in_exec = e self.showtraceback(running_compiled_code=True) finally: return result def should_run_async( self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None ) -> bool: """Return whether a cell should be run asynchronously via a coroutine runner Parameters ---------- raw_cell : str The code to be executed Returns ------- result: bool Whether the code needs to be run with a coroutine runner or not .. versionadded:: 7.0 """ if not self.autoawait: return False if preprocessing_exc_tuple is not None: return False assert preprocessing_exc_tuple is None if transformed_cell is None: warnings.warn( "`should_run_async` will not call `transform_cell`" " automatically in the future. Please pass the result to" " `transformed_cell` argument and any exception that happen" " during the" "transform in `preprocessing_exc_tuple` in" " IPython 7.17 and above.", DeprecationWarning, stacklevel=2, ) try: cell = self.transform_cell(raw_cell) except Exception: # any exception during transform will be raised # prior to execution return False else: cell = transformed_cell return _should_be_async(cell) async def run_cell_async( self, raw_cell: str, store_history=False, silent=False, shell_futures=True, *, transformed_cell: Optional[str] = None, preprocessing_exc_tuple: Optional[AnyType] = None, cell_id=None, ) -> ExecutionResult: """Run a complete IPython cell asynchronously. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back into IPython's machinery, this should be set to False. silent : bool If True, avoid side-effects, such as implicit displayhooks and and logging. silent=True forces store_history=False. shell_futures : bool If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. transformed_cell: str cell that was passed through transformers preprocessing_exc_tuple: trace if the transformation failed. Returns ------- result : :class:`ExecutionResult` .. versionadded:: 7.0 """ info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id) result = ExecutionResult(info) if (not raw_cell) or raw_cell.isspace(): self.last_execution_succeeded = True self.last_execution_result = result return result if silent: store_history = False if store_history: result.execution_count = self.execution_count def error_before_exec(value): if store_history: self.execution_count += 1 result.error_before_exec = value self.last_execution_succeeded = False self.last_execution_result = result return result self.events.trigger('pre_execute') if not silent: self.events.trigger('pre_run_cell', info) if transformed_cell is None: warnings.warn( "`run_cell_async` will not call `transform_cell`" " automatically in the future. Please pass the result to" " `transformed_cell` argument and any exception that happen" " during the" "transform in `preprocessing_exc_tuple` in" " IPython 7.17 and above.", DeprecationWarning, stacklevel=2, ) # If any of our input transformation (input_transformer_manager or # prefilter_manager) raises an exception, we store it in this variable # so that we can display the error after logging the input and storing # it in the history. try: cell = self.transform_cell(raw_cell) except Exception: preprocessing_exc_tuple = sys.exc_info() cell = raw_cell # cell has to exist so it can be stored/logged else: preprocessing_exc_tuple = None else: if preprocessing_exc_tuple is None: cell = transformed_cell else: cell = raw_cell # Do NOT store paste/cpaste magic history if "get_ipython().run_line_magic(" in cell and "paste" in cell: store_history = False # Store raw and processed history if store_history: self.history_manager.store_inputs(self.execution_count, cell, raw_cell) if not silent: self.logger.log(cell, raw_cell) # Display the exception if input processing failed. if preprocessing_exc_tuple is not None: self.showtraceback(preprocessing_exc_tuple) if store_history: self.execution_count += 1 return error_before_exec(preprocessing_exc_tuple[1]) # Our own compiler remembers the __future__ environment. If we want to # run code with a separate __future__ environment, use the default # compiler compiler = self.compile if shell_futures else self.compiler_class() _run_async = False with self.builtin_trap: cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell) with self.display_trap: # Compile to bytecode try: code_ast = compiler.ast_parse(cell, filename=cell_name) except self.custom_exceptions as e: etype, value, tb = sys.exc_info() self.CustomTB(etype, value, tb) return error_before_exec(e) except IndentationError as e: self.showindentationerror() return error_before_exec(e) except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError) as e: self.showsyntaxerror() return error_before_exec(e) # Apply AST transformations try: code_ast = self.transform_ast(code_ast) except InputRejected as e: self.showtraceback() return error_before_exec(e) # Give the displayhook a reference to our ExecutionResult so it # can fill in the output value. self.displayhook.exec_result = result # Execute the user code interactivity = "none" if silent else self.ast_node_interactivity has_raised = await self.run_ast_nodes(code_ast.body, cell_name, interactivity=interactivity, compiler=compiler, result=result) self.last_execution_succeeded = not has_raised self.last_execution_result = result # Reset this so later displayed values do not modify the # ExecutionResult self.displayhook.exec_result = None if store_history: # Write output to the database. Does nothing unless # history output logging is enabled. self.history_manager.store_output(self.execution_count) # Each cell is a *single* input, regardless of how many lines it has self.execution_count += 1 return result def transform_cell(self, raw_cell): """Transform an input cell before parsing it. Static transformations, implemented in IPython.core.inputtransformer2, deal with things like ``%magic`` and ``!system`` commands. These run on all input. Dynamic transformations, for things like unescaped magics and the exit autocall, depend on the state of the interpreter. These only apply to single line inputs. These string-based transformations are followed by AST transformations; see :meth:`transform_ast`. """ # Static input transformations cell = self.input_transformer_manager.transform_cell(raw_cell) if len(cell.splitlines()) == 1: # Dynamic transformations - only applied for single line commands with self.builtin_trap: # use prefilter_lines to handle trailing newlines # restore trailing newline for ast.parse cell = self.prefilter_manager.prefilter_lines(cell) + '\n' lines = cell.splitlines(keepends=True) for transform in self.input_transformers_post: lines = transform(lines) cell = ''.join(lines) return cell def transform_ast(self, node): """Apply the AST transformations from self.ast_transformers Parameters ---------- node : ast.Node The root node to be transformed. Typically called with the ast.Module produced by parsing user input. Returns ------- An ast.Node corresponding to the node it was called with. Note that it may also modify the passed object, so don't rely on references to the original AST. """ for transformer in self.ast_transformers: try: node = transformer.visit(node) except InputRejected: # User-supplied AST transformers can reject an input by raising # an InputRejected. Short-circuit in this case so that we # don't unregister the transform. raise except Exception: warn("AST transformer %r threw an error. It will be unregistered." % transformer) self.ast_transformers.remove(transformer) if self.ast_transformers: ast.fix_missing_locations(node) return node async def run_ast_nodes( self, nodelist: ListType[stmt], cell_name: str, interactivity="last_expr", compiler=compile, result=None, ): """Run a sequence of AST nodes. The execution mode depends on the interactivity parameter. Parameters ---------- nodelist : list A sequence of AST nodes to run. cell_name : str Will be passed to the compiler as the filename of the cell. Typically the value returned by ip.compile.cache(cell). interactivity : str 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none', specifying which nodes should be run interactively (displaying output from expressions). 'last_expr' will run the last node interactively only if it is an expression (i.e. expressions in loops or other blocks are not displayed) 'last_expr_or_assign' will run the last expression or the last assignment. Other values for this parameter will raise a ValueError. compiler : callable A function with the same interface as the built-in compile(), to turn the AST nodes into code objects. Default is the built-in compile(). result : ExecutionResult, optional An object to store exceptions that occur during execution. Returns ------- True if an exception occurred while running code, False if it finished running. """ if not nodelist: return if interactivity == 'last_expr_or_assign': if isinstance(nodelist[-1], _assign_nodes): asg = nodelist[-1] if isinstance(asg, ast.Assign) and len(asg.targets) == 1: target = asg.targets[0] elif isinstance(asg, _single_targets_nodes): target = asg.target else: target = None if isinstance(target, ast.Name): nnode = ast.Expr(ast.Name(target.id, ast.Load())) ast.fix_missing_locations(nnode) nodelist.append(nnode) interactivity = 'last_expr' _async = False if interactivity == 'last_expr': if isinstance(nodelist[-1], ast.Expr): interactivity = "last" else: interactivity = "none" if interactivity == 'none': to_run_exec, to_run_interactive = nodelist, [] elif interactivity == 'last': to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] elif interactivity == 'all': to_run_exec, to_run_interactive = [], nodelist else: raise ValueError("Interactivity was %r" % interactivity) try: def compare(code): is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE return is_async # refactor that to just change the mod constructor. to_run = [] for node in to_run_exec: to_run.append((node, "exec")) for node in to_run_interactive: to_run.append((node, "single")) for node, mode in to_run: if mode == "exec": mod = Module([node], []) elif mode == "single": mod = ast.Interactive([node]) # type: ignore with compiler.extra_flags( getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0) if self.autoawait else 0x0 ): code = compiler(mod, cell_name, mode) asy = compare(code) if await self.run_code(code, result, async_=asy): return True # Flush softspace if softspace(sys.stdout, 0): print() except: # It's possible to have exceptions raised here, typically by # compilation of odd code (such as a naked 'return' outside a # function) that did parse but isn't valid. Typically the exception # is a SyntaxError, but it's safest just to catch anything and show # the user a traceback. # We do only one try/except outside the loop to minimize the impact # on runtime, and also because if any node in the node list is # broken, we should stop execution completely. if result: result.error_before_exec = sys.exc_info()[1] self.showtraceback() return True return False async def run_code(self, code_obj, result=None, *, async_=False): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. Parameters ---------- code_obj : code object A compiled code object, to be executed result : ExecutionResult, optional An object to store exceptions that occur during execution. async_ : Bool (Experimental) Attempt to run top-level asynchronous code in a default loop. Returns ------- False : successful execution. True : an error occurred. """ # special value to say that anything above is IPython and should be # hidden. __tracebackhide__ = "__ipython_bottom__" # Set our own excepthook in case the user code tries to call it # directly, so that the IPython crash handler doesn't get triggered old_excepthook, sys.excepthook = sys.excepthook, self.excepthook # we save the original sys.excepthook in the instance, in case config # code (such as magics) needs access to it. self.sys_excepthook = old_excepthook outflag = True # happens in more places, so it's easier as default try: try: if async_: await eval(code_obj, self.user_global_ns, self.user_ns) else: exec(code_obj, self.user_global_ns, self.user_ns) finally: # Reset our crash handler in place sys.excepthook = old_excepthook except SystemExit as e: if result is not None: result.error_in_exec = e self.showtraceback(exception_only=True) warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) except bdb.BdbQuit: etype, value, tb = sys.exc_info() if result is not None: result.error_in_exec = value # the BdbQuit stops here except self.custom_exceptions: etype, value, tb = sys.exc_info() if result is not None: result.error_in_exec = value self.CustomTB(etype, value, tb) except: if result is not None: result.error_in_exec = sys.exc_info()[1] self.showtraceback(running_compiled_code=True) else: outflag = False return outflag # For backwards compatibility runcode = run_code def check_complete(self, code: str) -> Tuple[str, str]: """Return whether a block of code is ready to execute, or should be continued Parameters ---------- code : string Python input code, which can be multiline. Returns ------- status : str One of 'complete', 'incomplete', or 'invalid' if source is not a prefix of valid code. indent : str When status is 'incomplete', this is some whitespace to insert on the next line of the prompt. """ status, nspaces = self.input_transformer_manager.check_complete(code) return status, ' ' * (nspaces or 0) #------------------------------------------------------------------------- # Things related to GUI support and pylab #------------------------------------------------------------------------- active_eventloop = None def enable_gui(self, gui=None): raise NotImplementedError('Implement enable_gui in a subclass') def enable_matplotlib(self, gui=None): """Enable interactive matplotlib and inline figure support. This takes the following steps: 1. select the appropriate eventloop and matplotlib backend 2. set up matplotlib for interactive use with that backend 3. configure formatters for inline figure display 4. enable the selected gui eventloop Parameters ---------- gui : optional, string If given, dictates the choice of matplotlib GUI backend to use (should be one of IPython's supported backends, 'qt', 'osx', 'tk', 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by matplotlib (as dictated by the matplotlib build-time options plus the user's matplotlibrc configuration file). Note that not all backends make sense in all contexts, for example a terminal ipython can't display figures inline. """ from matplotlib_inline.backend_inline import configure_inline_support from IPython.core import pylabtools as pt gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) if gui != 'inline': # If we have our first gui selection, store it if self.pylab_gui_select is None: self.pylab_gui_select = gui # Otherwise if they are different elif gui != self.pylab_gui_select: print('Warning: Cannot change to a different GUI toolkit: %s.' ' Using %s instead.' % (gui, self.pylab_gui_select)) gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) pt.activate_matplotlib(backend) configure_inline_support(self, backend) # Now we must activate the gui pylab wants to use, and fix %run to take # plot updates into account self.enable_gui(gui) self.magics_manager.registry['ExecutionMagics'].default_runner = \ pt.mpl_runner(self.safe_execfile) return gui, backend def enable_pylab(self, gui=None, import_all=True, welcome_message=False): """Activate pylab support at runtime. This turns on support for matplotlib, preloads into the interactive namespace all of numpy and pylab, and configures IPython to correctly interact with the GUI event loop. The GUI backend to be used can be optionally selected with the optional ``gui`` argument. This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. Parameters ---------- gui : optional, string If given, dictates the choice of matplotlib GUI backend to use (should be one of IPython's supported backends, 'qt', 'osx', 'tk', 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by matplotlib (as dictated by the matplotlib build-time options plus the user's matplotlibrc configuration file). Note that not all backends make sense in all contexts, for example a terminal ipython can't display figures inline. import_all : optional, bool, default: True Whether to do `from numpy import *` and `from pylab import *` in addition to module imports. welcome_message : deprecated This argument is ignored, no welcome message will be displayed. """ from IPython.core.pylabtools import import_pylab gui, backend = self.enable_matplotlib(gui) # We want to prevent the loading of pylab to pollute the user's # namespace as shown by the %who* magics, so we execute the activation # code in an empty namespace, and we update *both* user_ns and # user_ns_hidden with this information. ns = {} import_pylab(ns, import_all) # warn about clobbered names ignored = {"__builtins__"} both = set(ns).intersection(self.user_ns).difference(ignored) clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] self.user_ns.update(ns) self.user_ns_hidden.update(ns) return gui, backend, clobbered #------------------------------------------------------------------------- # Utilities #------------------------------------------------------------------------- def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): """Expand python variables in a string. The depth argument indicates how many frames above the caller should be walked to look for the local namespace where to expand variables. The global namespace for expansion is always the user's interactive namespace. """ ns = self.user_ns.copy() try: frame = sys._getframe(depth+1) except ValueError: # This is thrown if there aren't that many frames on the stack, # e.g. if a script called run_line_magic() directly. pass else: ns.update(frame.f_locals) try: # We have to use .vformat() here, because 'self' is a valid and common # name, and expanding **ns for .format() would make it collide with # the 'self' argument of the method. cmd = formatter.vformat(cmd, args=[], kwargs=ns) except Exception: # if formatter couldn't format, just let it go untransformed pass return cmd def mktempfile(self, data=None, prefix='ipython_edit_'): """Make a new tempfile and return its filename. This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), but it registers the created filename internally so ipython cleans it up at exit time. Optional inputs: - data(None): if data is given, it gets written out to the temp file immediately, and the file is closed again.""" dir_path = Path(tempfile.mkdtemp(prefix=prefix)) self.tempdirs.append(dir_path) handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path)) os.close(handle) # On Windows, there can only be one open handle on a file file_path = Path(filename) self.tempfiles.append(file_path) if data: file_path.write_text(data, encoding="utf-8") return filename def ask_yes_no(self, prompt, default=None, interrupt=None): if self.quiet: return True return ask_yes_no(prompt,default,interrupt) def show_usage(self): """Show a usage message""" page.page(IPython.core.usage.interactive_usage) def extract_input_lines(self, range_str, raw=False): """Return as a string a set of input history slices. Parameters ---------- range_str : str The set of slices is given as a string, like "~5/6-~4/2 4:8 9", since this function is for use by magic functions which get their arguments as strings. The number before the / is the session number: ~n goes n back from the current session. If empty string is given, returns history of current session without the last input. raw : bool, optional By default, the processed input is used. If this is true, the raw input history is used instead. Notes ----- Slices can be described with two notations: * ``N:M`` -> standard python form, means including items N...(M-1). * ``N-M`` -> include items N..M (closed endpoint). """ lines = self.history_manager.get_range_by_str(range_str, raw=raw) text = "\n".join(x for _, _, x in lines) # Skip the last line, as it's probably the magic that called this if not range_str: if "\n" not in text: text = "" else: text = text[: text.rfind("\n")] return text def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): """Get a code string from history, file, url, or a string or macro. This is mainly used by magic functions. Parameters ---------- target : str A string specifying code to retrieve. This will be tried respectively as: ranges of input history (see %history for syntax), url, corresponding .py file, filename, or an expression evaluating to a string or Macro in the user namespace. If empty string is given, returns complete history of current session, without the last line. raw : bool If true (default), retrieve raw history. Has no effect on the other retrieval mechanisms. py_only : bool (default False) Only try to fetch python code, do not try alternative methods to decode file if unicode fails. Returns ------- A string of code. ValueError is raised if nothing is found, and TypeError if it evaluates to an object of another type. In each case, .args[0] is a printable message. """ code = self.extract_input_lines(target, raw=raw) # Grab history if code: return code try: if target.startswith(('http://', 'https://')): return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) except UnicodeDecodeError as e: if not py_only : # Deferred import from urllib.request import urlopen response = urlopen(target) return response.read().decode('latin1') raise ValueError(("'%s' seem to be unreadable.") % target) from e potential_target = [target] try : potential_target.insert(0,get_py_filename(target)) except IOError: pass for tgt in potential_target : if os.path.isfile(tgt): # Read file try : return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) except UnicodeDecodeError as e: if not py_only : with io_open(tgt,'r', encoding='latin1') as f : return f.read() raise ValueError(("'%s' seem to be unreadable.") % target) from e elif os.path.isdir(os.path.expanduser(tgt)): raise ValueError("'%s' is a directory, not a regular file." % target) if search_ns: # Inspect namespace to load object source object_info = self.object_inspect(target, detail_level=1) if object_info['found'] and object_info['source']: return object_info['source'] try: # User namespace codeobj = eval(target, self.user_ns) except Exception as e: raise ValueError(("'%s' was not found in history, as a file, url, " "nor in the user namespace.") % target) from e if isinstance(codeobj, str): return codeobj elif isinstance(codeobj, Macro): return codeobj.value raise TypeError("%s is neither a string nor a macro." % target, codeobj) def _atexit_once(self): """ At exist operation that need to be called at most once. Second call to this function per instance will do nothing. """ if not getattr(self, "_atexit_once_called", False): self._atexit_once_called = True # Clear all user namespaces to release all references cleanly. self.reset(new_session=False) # Close the history session (this stores the end time and line count) # this must be *before* the tempfile cleanup, in case of temporary # history db self.history_manager.end_session() self.history_manager = None #------------------------------------------------------------------------- # Things related to IPython exiting #------------------------------------------------------------------------- def atexit_operations(self): """This will be executed at the time of exit. Cleanup operations and saving of persistent data that is done unconditionally by IPython should be performed here. For things that may depend on startup flags or platform specifics (such as having readline or not), register a separate atexit function in the code that has the appropriate information, rather than trying to clutter """ self._atexit_once() # Cleanup all tempfiles and folders left around for tfile in self.tempfiles: try: tfile.unlink() self.tempfiles.remove(tfile) except FileNotFoundError: pass del self.tempfiles for tdir in self.tempdirs: try: tdir.rmdir() self.tempdirs.remove(tdir) except FileNotFoundError: pass del self.tempdirs # Restore user's cursor if hasattr(self, "editing_mode") and self.editing_mode == "vi": sys.stdout.write("\x1b[0 q") sys.stdout.flush() def cleanup(self): self.restore_sys_module_state() # Overridden in terminal subclass to change prompts def switch_doctest_mode(self, mode): pass class TerminalInteractiveShell(InteractiveShell): mime_renderers = Dict().tag(config=True) space_for_menu = Integer(6, help='Number of line at the bottom of the screen ' 'to reserve for the tab completion menu, ' 'search history, ...etc, the height of ' 'these menus will at most this value. ' 'Increase it is you prefer long and skinny ' 'menus, decrease for short and wide.' ).tag(config=True) pt_app: UnionType[PromptSession, None] = None auto_suggest: UnionType[ AutoSuggestFromHistory, NavigableAutoSuggestFromHistory, None ] = None debugger_history = None debugger_history_file = Unicode( "~/.pdbhistory", help="File in which to store and read history" ).tag(config=True) simple_prompt = Bool(_use_simple_prompt, help="""Use `raw_input` for the REPL, without completion and prompt colors. Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are: IPython own testing machinery, and emacs inferior-shell integration through elpy. This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT` environment variable is set, or the current terminal is not a tty.""" ).tag(config=True) def debugger_cls(self): return Pdb if self.simple_prompt else TerminalPdb confirm_exit = Bool(True, help=""" Set to confirm when you try to exit IPython with an EOF (Control-D in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', you can force a direct exit without any confirmation.""", ).tag(config=True) editing_mode = Unicode('emacs', help="Shortcut style to use at the prompt. 'vi' or 'emacs'.", ).tag(config=True) emacs_bindings_in_vi_insert_mode = Bool( True, help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.", ).tag(config=True) modal_cursor = Bool( True, help=""" Cursor shape changes depending on vi mode: beam in vi insert mode, block in nav mode, underscore in replace mode.""", ).tag(config=True) ttimeoutlen = Float( 0.01, help="""The time in milliseconds that is waited for a key code to complete.""", ).tag(config=True) timeoutlen = Float( 0.5, help="""The time in milliseconds that is waited for a mapped key sequence to complete.""", ).tag(config=True) autoformatter = Unicode( None, help="Autoformatter to reformat Terminal code. Can be `'black'`, `'yapf'` or `None`", allow_none=True ).tag(config=True) auto_match = Bool( False, help=""" Automatically add/delete closing bracket or quote when opening bracket or quote is entered/deleted. Brackets: (), [], {} Quotes: '', \"\" """, ).tag(config=True) mouse_support = Bool(False, help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)" ).tag(config=True) # We don't load the list of styles for the help string, because loading # Pygments plugins takes time and can cause unexpected errors. highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], help="""The name or class of a Pygments style to use for syntax highlighting. To see available styles, run `pygmentize -L styles`.""" ).tag(config=True) def _validate_editing_mode(self, proposal): if proposal['value'].lower() == 'vim': proposal['value']= 'vi' elif proposal['value'].lower() == 'default': proposal['value']= 'emacs' if hasattr(EditingMode, proposal['value'].upper()): return proposal['value'].lower() return self.editing_mode def _editing_mode(self, change): if self.pt_app: self.pt_app.editing_mode = getattr(EditingMode, change.new.upper()) def _set_formatter(self, formatter): if formatter is None: self.reformat_handler = lambda x:x elif formatter == 'black': self.reformat_handler = black_reformat_handler elif formatter == "yapf": self.reformat_handler = yapf_reformat_handler else: raise ValueError def _autoformatter_changed(self, change): formatter = change.new self._set_formatter(formatter) def _highlighting_style_changed(self, change): self.refresh_style() def refresh_style(self): self._style = self._make_style_from_name_or_cls(self.highlighting_style) highlighting_style_overrides = Dict( help="Override highlighting format for specific tokens" ).tag(config=True) true_color = Bool(False, help="""Use 24bit colors instead of 256 colors in prompt highlighting. If your terminal supports true color, the following command should print ``TRUECOLOR`` in orange:: printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\" """, ).tag(config=True) editor = Unicode(get_default_editor(), help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." ).tag(config=True) prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True) prompts = Instance(Prompts) def _prompts_default(self): return self.prompts_class(self) # @observe('prompts') # def _(self, change): # self._update_layout() def _displayhook_class_default(self): return RichPromptDisplayHook term_title = Bool(True, help="Automatically set the terminal title" ).tag(config=True) term_title_format = Unicode("IPython: {cwd}", help="Customize the terminal title format. This is a python format string. " + "Available substitutions are: {cwd}." ).tag(config=True) display_completions = Enum(('column', 'multicolumn','readlinelike'), help= ( "Options for displaying tab completions, 'column', 'multicolumn', and " "'readlinelike'. These options are for `prompt_toolkit`, see " "`prompt_toolkit` documentation for more information." ), default_value='multicolumn').tag(config=True) highlight_matching_brackets = Bool(True, help="Highlight matching brackets.", ).tag(config=True) extra_open_editor_shortcuts = Bool(False, help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. " "This is in addition to the F2 binding, which is always enabled." ).tag(config=True) handle_return = Any(None, help="Provide an alternative handler to be called when the user presses " "Return. This is an advanced option intended for debugging, which " "may be changed or removed in later releases." ).tag(config=True) enable_history_search = Bool(True, help="Allows to enable/disable the prompt toolkit history search" ).tag(config=True) autosuggestions_provider = Unicode( "NavigableAutoSuggestFromHistory", help="Specifies from which source automatic suggestions are provided. " "Can be set to ``'NavigableAutoSuggestFromHistory'`` (:kbd:`up` and " ":kbd:`down` swap suggestions), ``'AutoSuggestFromHistory'``, " " or ``None`` to disable automatic suggestions. " "Default is `'NavigableAutoSuggestFromHistory`'.", allow_none=True, ).tag(config=True) def _set_autosuggestions(self, provider): # disconnect old handler if self.auto_suggest and isinstance( self.auto_suggest, NavigableAutoSuggestFromHistory ): self.auto_suggest.disconnect() if provider is None: self.auto_suggest = None elif provider == "AutoSuggestFromHistory": self.auto_suggest = AutoSuggestFromHistory() elif provider == "NavigableAutoSuggestFromHistory": self.auto_suggest = NavigableAutoSuggestFromHistory() else: raise ValueError("No valid provider.") if self.pt_app: self.pt_app.auto_suggest = self.auto_suggest def _autosuggestions_provider_changed(self, change): provider = change.new self._set_autosuggestions(provider) shortcuts = List( trait=Dict( key_trait=Enum( [ "command", "match_keys", "match_filter", "new_keys", "new_filter", "create", ] ), per_key_traits={ "command": Unicode(), "match_keys": List(Unicode()), "match_filter": Unicode(), "new_keys": List(Unicode()), "new_filter": Unicode(), "create": Bool(False), }, ), help="""Add, disable or modifying shortcuts. Each entry on the list should be a dictionary with ``command`` key identifying the target function executed by the shortcut and at least one of the following: - ``match_keys``: list of keys used to match an existing shortcut, - ``match_filter``: shortcut filter used to match an existing shortcut, - ``new_keys``: list of keys to set, - ``new_filter``: a new shortcut filter to set The filters have to be composed of pre-defined verbs and joined by one of the following conjunctions: ``&`` (and), ``|`` (or), ``~`` (not). The pre-defined verbs are: {} To disable a shortcut set ``new_keys`` to an empty list. To add a shortcut add key ``create`` with value ``True``. When modifying/disabling shortcuts, ``match_keys``/``match_filter`` can be omitted if the provided specification uniquely identifies a shortcut to be modified/disabled. When modifying a shortcut ``new_filter`` or ``new_keys`` can be omitted which will result in reuse of the existing filter/keys. Only shortcuts defined in IPython (and not default prompt-toolkit shortcuts) can be modified or disabled. The full list of shortcuts, command identifiers and filters is available under :ref:`terminal-shortcuts-list`. """.format( "\n ".join([f"- `{k}`" for k in KEYBINDING_FILTERS]) ), ).tag(config=True) def _shortcuts_changed(self, change): if self.pt_app: self.pt_app.key_bindings = self._merge_shortcuts(user_shortcuts=change.new) def _merge_shortcuts(self, user_shortcuts): # rebuild the bindings list from scratch key_bindings = create_ipython_shortcuts(self) # for now we only allow adding shortcuts for commands which are already # registered; this is a security precaution. known_commands = { create_identifier(binding.command): binding.command for binding in KEY_BINDINGS } shortcuts_to_skip = [] shortcuts_to_add = [] for shortcut in user_shortcuts: command_id = shortcut["command"] if command_id not in known_commands: allowed_commands = "\n - ".join(known_commands) raise ValueError( f"{command_id} is not a known shortcut command." f" Allowed commands are: \n - {allowed_commands}" ) old_keys = shortcut.get("match_keys", None) old_filter = ( filter_from_string(shortcut["match_filter"]) if "match_filter" in shortcut else None ) matching = [ binding for binding in KEY_BINDINGS if ( (old_filter is None or binding.filter == old_filter) and (old_keys is None or [k for k in binding.keys] == old_keys) and create_identifier(binding.command) == command_id ) ] new_keys = shortcut.get("new_keys", None) new_filter = shortcut.get("new_filter", None) command = known_commands[command_id] creating_new = shortcut.get("create", False) modifying_existing = not creating_new and ( new_keys is not None or new_filter ) if creating_new and new_keys == []: raise ValueError("Cannot add a shortcut without keys") if modifying_existing: specification = { key: shortcut[key] for key in ["command", "filter"] if key in shortcut } if len(matching) == 0: raise ValueError( f"No shortcuts matching {specification} found in {KEY_BINDINGS}" ) elif len(matching) > 1: raise ValueError( f"Multiple shortcuts matching {specification} found," f" please add keys/filter to select one of: {matching}" ) matched = matching[0] old_filter = matched.filter old_keys = list(matched.keys) shortcuts_to_skip.append( RuntimeBinding( command, keys=old_keys, filter=old_filter, ) ) if new_keys != []: shortcuts_to_add.append( RuntimeBinding( command, keys=new_keys or old_keys, filter=filter_from_string(new_filter) if new_filter is not None else ( old_filter if old_filter is not None else filter_from_string("always") ), ) ) # rebuild the bindings list from scratch key_bindings = create_ipython_shortcuts(self, skip=shortcuts_to_skip) for binding in shortcuts_to_add: add_binding(key_bindings, binding) return key_bindings prompt_includes_vi_mode = Bool(True, help="Display the current vi mode (when using vi editing mode)." ).tag(config=True) def init_term_title(self, change=None): # Enable or disable the terminal title. if self.term_title and _is_tty: toggle_set_term_title(True) set_term_title(self.term_title_format.format(cwd=abbrev_cwd())) else: toggle_set_term_title(False) def restore_term_title(self): if self.term_title and _is_tty: restore_term_title() def init_display_formatter(self): super(TerminalInteractiveShell, self).init_display_formatter() # terminal only supports plain text self.display_formatter.active_types = ["text/plain"] def init_prompt_toolkit_cli(self): if self.simple_prompt: # Fall back to plain non-interactive output for tests. # This is very limited. def prompt(): prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) lines = [input(prompt_text)] prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) while self.check_complete('\n'.join(lines))[0] == 'incomplete': lines.append( input(prompt_continuation) ) return '\n'.join(lines) self.prompt_for_code = prompt return # Set up keyboard shortcuts key_bindings = self._merge_shortcuts(user_shortcuts=self.shortcuts) # Pre-populate history from IPython's history database history = PtkHistoryAdapter(self) self._style = self._make_style_from_name_or_cls(self.highlighting_style) self.style = DynamicStyle(lambda: self._style) editing_mode = getattr(EditingMode, self.editing_mode.upper()) self.pt_loop = asyncio.new_event_loop() self.pt_app = PromptSession( auto_suggest=self.auto_suggest, editing_mode=editing_mode, key_bindings=key_bindings, history=history, completer=IPythonPTCompleter(shell=self), enable_history_search=self.enable_history_search, style=self.style, include_default_pygments_style=False, mouse_support=self.mouse_support, enable_open_in_editor=self.extra_open_editor_shortcuts, color_depth=self.color_depth, tempfile_suffix=".py", **self._extra_prompt_options(), ) if isinstance(self.auto_suggest, NavigableAutoSuggestFromHistory): self.auto_suggest.connect(self.pt_app) def _make_style_from_name_or_cls(self, name_or_cls): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_overrides = {} if name_or_cls == 'legacy': legacy = self.colors.lower() if legacy == 'linux': style_cls = get_style_by_name('monokai') style_overrides = _style_overrides_linux elif legacy == 'lightbg': style_overrides = _style_overrides_light_bg style_cls = get_style_by_name('pastie') elif legacy == 'neutral': # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_cls = get_style_by_name('default') style_overrides.update({ Token.Number: '#ansigreen', Token.Operator: 'noinherit', Token.String: '#ansiyellow', Token.Name.Function: '#ansiblue', Token.Name.Class: 'bold #ansiblue', Token.Name.Namespace: 'bold #ansiblue', Token.Name.Variable.Magic: '#ansiblue', Token.Prompt: '#ansigreen', Token.PromptNum: '#ansibrightgreen bold', Token.OutPrompt: '#ansired', Token.OutPromptNum: '#ansibrightred bold', }) # Hack: Due to limited color support on the Windows console # the prompt colors will be wrong without this if os.name == 'nt': style_overrides.update({ Token.Prompt: '#ansidarkgreen', Token.PromptNum: '#ansigreen bold', Token.OutPrompt: '#ansidarkred', Token.OutPromptNum: '#ansired bold', }) elif legacy =='nocolor': style_cls=_NoStyle style_overrides = {} else : raise ValueError('Got unknown colors: ', legacy) else : if isinstance(name_or_cls, str): style_cls = get_style_by_name(name_or_cls) else: style_cls = name_or_cls style_overrides = { Token.Prompt: '#ansigreen', Token.PromptNum: '#ansibrightgreen bold', Token.OutPrompt: '#ansired', Token.OutPromptNum: '#ansibrightred bold', } style_overrides.update(self.highlighting_style_overrides) style = merge_styles([ style_from_pygments_cls(style_cls), style_from_pygments_dict(style_overrides), ]) return style def pt_complete_style(self): return { 'multicolumn': CompleteStyle.MULTI_COLUMN, 'column': CompleteStyle.COLUMN, 'readlinelike': CompleteStyle.READLINE_LIKE, }[self.display_completions] def color_depth(self): return (ColorDepth.TRUE_COLOR if self.true_color else None) def _extra_prompt_options(self): """ Return the current layout option for the current Terminal InteractiveShell """ def get_message(): return PygmentsTokens(self.prompts.in_prompt_tokens()) if self.editing_mode == 'emacs': # with emacs mode the prompt is (usually) static, so we call only # the function once. With VI mode it can toggle between [ins] and # [nor] so we can't precompute. # here I'm going to favor the default keybinding which almost # everybody uses to decrease CPU usage. # if we have issues with users with custom Prompts we can see how to # work around this. get_message = get_message() options = { "complete_in_thread": False, "lexer": IPythonPTLexer(), "reserve_space_for_menu": self.space_for_menu, "message": get_message, "prompt_continuation": ( lambda width, lineno, is_soft_wrap: PygmentsTokens( self.prompts.continuation_prompt_tokens(width) ) ), "multiline": True, "complete_style": self.pt_complete_style, "input_processors": [ # Highlight matching brackets, but only when this setting is # enabled, and only when the DEFAULT_BUFFER has the focus. ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars="[](){}"), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() & Condition(lambda: self.highlight_matching_brackets), ), # Show auto-suggestion in lines other than the last line. ConditionalProcessor( processor=AppendAutoSuggestionInAnyLine(), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() & Condition( lambda: isinstance( self.auto_suggest, NavigableAutoSuggestFromHistory ) ), ), ], } if not PTK3: options['inputhook'] = self.inputhook return options def prompt_for_code(self): if self.rl_next_input: default = self.rl_next_input self.rl_next_input = None else: default = '' # In order to make sure that asyncio code written in the # interactive shell doesn't interfere with the prompt, we run the # prompt in a different event loop. # If we don't do this, people could spawn coroutine with a # while/true inside which will freeze the prompt. policy = asyncio.get_event_loop_policy() old_loop = get_asyncio_loop() # FIXME: prompt_toolkit is using the deprecated `asyncio.get_event_loop` # to get the current event loop. # This will probably be replaced by an attribute or input argument, # at which point we can stop calling the soon-to-be-deprecated `set_event_loop` here. if old_loop is not self.pt_loop: policy.set_event_loop(self.pt_loop) try: with patch_stdout(raw=True): text = self.pt_app.prompt( default=default, **self._extra_prompt_options()) finally: # Restore the original event loop. if old_loop is not None and old_loop is not self.pt_loop: policy.set_event_loop(old_loop) return text def enable_win_unicode_console(self): # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows # console by default, so WUC shouldn't be needed. warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future", DeprecationWarning, stacklevel=2) def init_io(self): if sys.platform not in {'win32', 'cli'}: return import colorama colorama.init() def init_magics(self): super(TerminalInteractiveShell, self).init_magics() self.register_magics(TerminalMagics) def init_alias(self): # The parent class defines aliases that can be safely used with any # frontend. super(TerminalInteractiveShell, self).init_alias() # Now define aliases that only make sense on the terminal, because they # need direct access to the console in a way that we can't emulate in # GUI or web frontend if os.name == 'posix': for cmd in ('clear', 'more', 'less', 'man'): self.alias_manager.soft_define_alias(cmd, cmd) def __init__(self, *args, **kwargs) -> None: super(TerminalInteractiveShell, self).__init__(*args, **kwargs) self._set_autosuggestions(self.autosuggestions_provider) self.init_prompt_toolkit_cli() self.init_term_title() self.keep_running = True self._set_formatter(self.autoformatter) def ask_exit(self): self.keep_running = False rl_next_input = None def interact(self): self.keep_running = True while self.keep_running: print(self.separate_in, end='') try: code = self.prompt_for_code() except EOFError: if (not self.confirm_exit) \ or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): self.ask_exit() else: if code: self.run_cell(code, store_history=True) def mainloop(self): # An extra layer of protection in case someone mashing Ctrl-C breaks # out of our internal code. while True: try: self.interact() break except KeyboardInterrupt as e: print("\n%s escaped interact()\n" % type(e).__name__) finally: # An interrupt during the eventloop will mess up the # internal state of the prompt_toolkit library. # Stopping the eventloop fixes this, see # https://github.com/ipython/ipython/pull/9867 if hasattr(self, '_eventloop'): self._eventloop.stop() self.restore_term_title() # try to call some at-exit operation optimistically as some things can't # be done during interpreter shutdown. this is technically inaccurate as # this make mainlool not re-callable, but that should be a rare if not # in existent use case. self._atexit_once() _inputhook = None def inputhook(self, context): if self._inputhook is not None: self._inputhook(context) active_eventloop = None def enable_gui(self, gui=None): if self._inputhook is None and gui is None: print("No event loop hook running.") return if self._inputhook is not None and gui is not None: print( f"Shell is already running a gui event loop for {self.active_eventloop}. " "Call with no arguments to disable the current loop." ) return if self._inputhook is not None and gui is None: self.active_eventloop = self._inputhook = None if gui and (gui not in {"inline", "webagg"}): # This hook runs with each cycle of the `prompt_toolkit`'s event loop. self.active_eventloop, self._inputhook = get_inputhook_name_and_func(gui) else: self.active_eventloop = self._inputhook = None # For prompt_toolkit 3.0. We have to create an asyncio event loop with # this inputhook. if PTK3: import asyncio from prompt_toolkit.eventloop import new_eventloop_with_inputhook if gui == 'asyncio': # When we integrate the asyncio event loop, run the UI in the # same event loop as the rest of the code. don't use an actual # input hook. (Asyncio is not made for nesting event loops.) self.pt_loop = get_asyncio_loop() print("Installed asyncio event loop hook.") elif self._inputhook: # If an inputhook was set, create a new asyncio event loop with # this inputhook for the prompt. self.pt_loop = new_eventloop_with_inputhook(self._inputhook) print(f"Installed {self.active_eventloop} event loop hook.") else: # When there's no inputhook, run the prompt in a separate # asyncio event loop. self.pt_loop = asyncio.new_event_loop() print("GUI event loop hook disabled.") # Run !system commands directly, not through pipes, so terminal programs # work correctly. system = InteractiveShell.system_raw def auto_rewrite_input(self, cmd): """Overridden from the parent class to use fancy rewriting prompt""" if not self.show_rewritten_input: return tokens = self.prompts.rewrite_prompt_tokens() if self.pt_app: print_formatted_text(PygmentsTokens(tokens), end='', style=self.pt_app.app.style) print(cmd) else: prompt = ''.join(s for t, s in tokens) print(prompt, cmd, sep='') _prompts_before = None def switch_doctest_mode(self, mode): """Switch prompts to classic for %doctest_mode""" if mode: self._prompts_before = self.prompts self.prompts = ClassicPrompts(self) elif self._prompts_before: self.prompts = self._prompts_before self._prompts_before = None def load_default_config(ipython_dir=None): """Load the default config file from the default ipython_dir. This is useful for embedded shells. """ if ipython_dir is None: ipython_dir = get_ipython_dir() profile_dir = os.path.join(ipython_dir, 'profile_default') app = TerminalIPythonApp() app.config_file_paths.append(profile_dir) app.load_config_file() return app.config The provided code snippet includes necessary dependencies for implementing the `embed` function. Write a Python function `def embed(*, header="", compile_flags=None, **kwargs)` to solve the following problem: Call this to embed IPython at the current point in your program. The first invocation of this will create a :class:`terminal.embed.InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. If you don't want the kernel to initialize the namespace from the scope of the surrounding function, and/or you want to load full IPython configuration, you probably want `IPython.start_ipython()` instead. Here is a simple example:: from IPython import embed a = 10 b = 20 embed(header='First time') c = 30 d = 40 embed() Parameters ---------- header : str Optional header string to print at startup. compile_flags Passed to the `compile_flags` parameter of :py:meth:`terminal.embed.InteractiveShellEmbed.mainloop()`, which is called when the :class:`terminal.embed.InteractiveShellEmbed` instance is called. **kwargs : various, optional Any other kwargs will be passed to the :class:`terminal.embed.InteractiveShellEmbed` constructor. Full customization can be done by passing a traitlets :class:`Config` in as the `config` argument (see :ref:`configure_start_ipython` and :ref:`terminal_options`). Here is the function: def embed(*, header="", compile_flags=None, **kwargs): """Call this to embed IPython at the current point in your program. The first invocation of this will create a :class:`terminal.embed.InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. If you don't want the kernel to initialize the namespace from the scope of the surrounding function, and/or you want to load full IPython configuration, you probably want `IPython.start_ipython()` instead. Here is a simple example:: from IPython import embed a = 10 b = 20 embed(header='First time') c = 30 d = 40 embed() Parameters ---------- header : str Optional header string to print at startup. compile_flags Passed to the `compile_flags` parameter of :py:meth:`terminal.embed.InteractiveShellEmbed.mainloop()`, which is called when the :class:`terminal.embed.InteractiveShellEmbed` instance is called. **kwargs : various, optional Any other kwargs will be passed to the :class:`terminal.embed.InteractiveShellEmbed` constructor. Full customization can be done by passing a traitlets :class:`Config` in as the `config` argument (see :ref:`configure_start_ipython` and :ref:`terminal_options`). """ config = kwargs.get('config') if config is None: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs['config'] = config using = kwargs.get('using', 'sync') if using : kwargs['config'].update({'TerminalInteractiveShell':{'loop_runner':using, 'colors':'NoColor', 'autoawait': using!='sync'}}) #save ps1/ps2 if defined ps1 = None ps2 = None try: ps1 = sys.ps1 ps2 = sys.ps2 except AttributeError: pass #save previous instance saved_shell_instance = InteractiveShell._instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() frame = sys._getframe(1) shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( frame.f_code.co_filename, frame.f_lineno), **kwargs) shell(header=header, stack_depth=2, compile_flags=compile_flags, _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) InteractiveShellEmbed.clear_instance() #restore previous instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() for subclass in cls._walk_mro(): subclass._instance = saved_shell_instance if ps1 is not None: sys.ps1 = ps1 sys.ps2 = ps2
Call this to embed IPython at the current point in your program. The first invocation of this will create a :class:`terminal.embed.InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. If you don't want the kernel to initialize the namespace from the scope of the surrounding function, and/or you want to load full IPython configuration, you probably want `IPython.start_ipython()` instead. Here is a simple example:: from IPython import embed a = 10 b = 20 embed(header='First time') c = 30 d = 40 embed() Parameters ---------- header : str Optional header string to print at startup. compile_flags Passed to the `compile_flags` parameter of :py:meth:`terminal.embed.InteractiveShellEmbed.mainloop()`, which is called when the :class:`terminal.embed.InteractiveShellEmbed` instance is called. **kwargs : various, optional Any other kwargs will be passed to the :class:`terminal.embed.InteractiveShellEmbed` constructor. Full customization can be done by passing a traitlets :class:`Config` in as the `config` argument (see :ref:`configure_start_ipython` and :ref:`terminal_options`).
176,880
from logging import error import os import sys from IPython.core.error import TryNext, UsageError from IPython.core.magic import Magics, magics_class, line_magic from IPython.lib.clipboard import ClipboardEmpty from IPython.testing.skipdoctest import skip_doctest from IPython.utils.text import SList, strip_email_quotes from IPython.utils import py3compat The provided code snippet includes necessary dependencies for implementing the `get_pasted_lines` function. Write a Python function `def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False)` to solve the following problem: Yield pasted lines until the user enters the given sentinel value. Here is the function: def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): """ Yield pasted lines until the user enters the given sentinel value. """ if not quiet: print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ % sentinel) prompt = ":" else: prompt = "" while True: try: l = l_input(prompt) if l == sentinel: return else: yield l except EOFError: print('<EOF>') return
Yield pasted lines until the user enters the given sentinel value.
176,881
import importlib.abc import sys import os import types from functools import partial, lru_cache import operator QT_API_PYQT6 = "pyqt6" QT_API_PYSIDE6 = "pyside6" QT_API_PYQT5 = 'pyqt5' QT_API_PYSIDE2 = 'pyside2' QT_API_PYQT = "pyqt" QT_API_PYQTv1 = "pyqtv1" QT_API_PYSIDE = "pyside" QT_API_PYQT_DEFAULT = "pyqtdefault" def commit_api(api): """Commit to a particular API, and trigger ImportErrors on subsequent dangerous imports""" modules = set(api_to_module.values()) modules.remove(api_to_module[api]) for mod in modules: ID.forbid(mod) def loaded_api(): """Return which API is loaded, if any If this returns anything besides None, importing any other Qt binding is unsafe. Returns ------- None, 'pyside6', 'pyqt6', 'pyside2', 'pyside', 'pyqt', 'pyqt5', 'pyqtv1' """ if sys.modules.get("PyQt6.QtCore"): return QT_API_PYQT6 elif sys.modules.get("PySide6.QtCore"): return QT_API_PYSIDE6 elif sys.modules.get("PyQt5.QtCore"): return QT_API_PYQT5 elif sys.modules.get("PySide2.QtCore"): return QT_API_PYSIDE2 elif sys.modules.get("PyQt4.QtCore"): if qtapi_version() == 2: return QT_API_PYQT else: return QT_API_PYQTv1 elif sys.modules.get("PySide.QtCore"): return QT_API_PYSIDE return None def has_binding(api): """Safely check for PyQt4/5, PySide or PySide2, without importing submodules Parameters ---------- api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault'] Which module to check for Returns ------- True if the relevant module appears to be importable """ module_name = api_to_module[api] from importlib.util import find_spec required = ['QtCore', 'QtGui', 'QtSvg'] if api in (QT_API_PYQT5, QT_API_PYSIDE2, QT_API_PYQT6, QT_API_PYSIDE6): # QT5 requires QtWidgets too required.append('QtWidgets') for submod in required: try: spec = find_spec('%s.%s' % (module_name, submod)) except ImportError: # Package (e.g. PyQt5) not found return False else: if spec is None: # Submodule (e.g. PyQt5.QtCore) not found return False if api == QT_API_PYSIDE: # We can also safely check PySide version import PySide return PySide.__version_info__ >= (1, 0, 3) return True def can_import(api): """Safely query whether an API is importable, without importing it""" if not has_binding(api): return False current = loaded_api() if api == QT_API_PYQT_DEFAULT: return current in [QT_API_PYQT6, None] else: return current in [api, None] def import_pyqt4(version=2): """ Import PyQt4 Parameters ---------- version : 1, 2, or None Which QString/QVariant API to use. Set to None to use the system default ImportErrors raised within this function are non-recoverable """ # The new-style string API (version=2) automatically # converts QStrings to Unicode Python strings. Also, automatically unpacks # QVariants to their underlying objects. import sip if version is not None: sip.setapi('QString', version) sip.setapi('QVariant', version) from PyQt4 import QtGui, QtCore, QtSvg if QtCore.PYQT_VERSION < 0x040700: raise ImportError("IPython requires PyQt4 >= 4.7, found %s" % QtCore.PYQT_VERSION_STR) # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # query for the API version (in case version == None) version = sip.getapi('QString') api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT return QtCore, QtGui, QtSvg, api def import_pyqt5(): """ Import PyQt5 ImportErrors raised within this function are non-recoverable """ from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # Join QtGui and QtWidgets for Qt4 compatibility. QtGuiCompat = types.ModuleType('QtGuiCompat') QtGuiCompat.__dict__.update(QtGui.__dict__) QtGuiCompat.__dict__.update(QtWidgets.__dict__) api = QT_API_PYQT5 return QtCore, QtGuiCompat, QtSvg, api def import_pyqt6(): """ Import PyQt6 ImportErrors raised within this function are non-recoverable """ from PyQt6 import QtCore, QtSvg, QtWidgets, QtGui # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # Join QtGui and QtWidgets for Qt4 compatibility. QtGuiCompat = types.ModuleType("QtGuiCompat") QtGuiCompat.__dict__.update(QtGui.__dict__) QtGuiCompat.__dict__.update(QtWidgets.__dict__) api = QT_API_PYQT6 return QtCore, QtGuiCompat, QtSvg, api def import_pyside(): """ Import PySide ImportErrors raised within this function are non-recoverable """ from PySide import QtGui, QtCore, QtSvg return QtCore, QtGui, QtSvg, QT_API_PYSIDE def import_pyside2(): """ Import PySide2 ImportErrors raised within this function are non-recoverable """ from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport # Join QtGui and QtWidgets for Qt4 compatibility. QtGuiCompat = types.ModuleType('QtGuiCompat') QtGuiCompat.__dict__.update(QtGui.__dict__) QtGuiCompat.__dict__.update(QtWidgets.__dict__) QtGuiCompat.__dict__.update(QtPrintSupport.__dict__) return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2 def import_pyside6(): """ Import PySide6 ImportErrors raised within this function are non-recoverable """ from PySide6 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport # Join QtGui and QtWidgets for Qt4 compatibility. QtGuiCompat = types.ModuleType("QtGuiCompat") QtGuiCompat.__dict__.update(QtGui.__dict__) QtGuiCompat.__dict__.update(QtWidgets.__dict__) QtGuiCompat.__dict__.update(QtPrintSupport.__dict__) return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE6 class partial(Generic[_T]): func: Callable[..., _T] args: Tuple[Any, ...] keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... The provided code snippet includes necessary dependencies for implementing the `load_qt` function. Write a Python function `def load_qt(api_options)` to solve the following problem: Attempt to import Qt, given a preference list of permissible bindings It is safe to call this function multiple times. Parameters ---------- api_options : List of strings The order of APIs to try. Valid items are 'pyside', 'pyside2', 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault' Returns ------- A tuple of QtCore, QtGui, QtSvg, QT_API The first three are the Qt modules. The last is the string indicating which module was loaded. Raises ------ ImportError, if it isn't possible to import any requested bindings (either because they aren't installed, or because an incompatible library has already been installed) Here is the function: def load_qt(api_options): """ Attempt to import Qt, given a preference list of permissible bindings It is safe to call this function multiple times. Parameters ---------- api_options : List of strings The order of APIs to try. Valid items are 'pyside', 'pyside2', 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault' Returns ------- A tuple of QtCore, QtGui, QtSvg, QT_API The first three are the Qt modules. The last is the string indicating which module was loaded. Raises ------ ImportError, if it isn't possible to import any requested bindings (either because they aren't installed, or because an incompatible library has already been installed) """ loaders = { # Qt6 QT_API_PYQT6: import_pyqt6, QT_API_PYSIDE6: import_pyside6, # Qt5 QT_API_PYQT5: import_pyqt5, QT_API_PYSIDE2: import_pyside2, # Qt4 QT_API_PYSIDE: import_pyside, QT_API_PYQT: import_pyqt4, QT_API_PYQTv1: partial(import_pyqt4, version=1), # default QT_API_PYQT_DEFAULT: import_pyqt6, } for api in api_options: if api not in loaders: raise RuntimeError( "Invalid Qt API %r, valid values are: %s" % (api, ", ".join(["%r" % k for k in loaders.keys()]))) if not can_import(api): continue #cannot safely recover from an ImportError during this result = loaders[api]() api = result[-1] # changed if api = QT_API_PYQT_DEFAULT commit_api(api) return result else: # Clear the environment variable since it doesn't work. if "QT_API" in os.environ: del os.environ["QT_API"] raise ImportError( """ Could not load requested Qt binding. Please ensure that PyQt4 >= 4.7, PyQt5, PyQt6, PySide >= 1.0.3, PySide2, or PySide6 is available, and only one is imported per session. Currently-imported Qt library: %r PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s PyQt6 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s PySide2 installed: %s PySide6 installed: %s Tried to load: %r """ % ( loaded_api(), has_binding(QT_API_PYQT5), has_binding(QT_API_PYQT6), has_binding(QT_API_PYSIDE2), has_binding(QT_API_PYSIDE6), api_options, ) )
Attempt to import Qt, given a preference list of permissible bindings It is safe to call this function multiple times. Parameters ---------- api_options : List of strings The order of APIs to try. Valid items are 'pyside', 'pyside2', 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault' Returns ------- A tuple of QtCore, QtGui, QtSvg, QT_API The first three are the Qt modules. The last is the string indicating which module was loaded. Raises ------ ImportError, if it isn't possible to import any requested bindings (either because they aren't installed, or because an incompatible library has already been installed)
176,882
import importlib.abc import sys import os import types from functools import partial, lru_cache import operator QT_API_PYQT6 = "pyqt6" sys.meta_path.insert(0, ID) The provided code snippet includes necessary dependencies for implementing the `enum_factory` function. Write a Python function `def enum_factory(QT_API, QtCore)` to solve the following problem: Construct an enum helper to account for PyQt5 <-> PyQt6 changes. Here is the function: def enum_factory(QT_API, QtCore): """Construct an enum helper to account for PyQt5 <-> PyQt6 changes.""" @lru_cache(None) def _enum(name): # foo.bar.Enum.Entry (PyQt6) <=> foo.bar.Entry (non-PyQt6). return operator.attrgetter( name if QT_API == QT_API_PYQT6 else name.rpartition(".")[0] )(sys.modules[QtCore.__package__]) return _enum
Construct an enum helper to account for PyQt5 <-> PyQt6 changes.
176,883
import os import sys from IPython.external.qt_loaders import ( load_qt, loaded_api, enum_factory, # QT6 QT_API_PYQT6, QT_API_PYSIDE6, # QT5 QT_API_PYQT5, QT_API_PYSIDE2, # QT4 QT_API_PYQT, QT_API_PYSIDE, # default QT_API_PYQT_DEFAULT, ) _qt_apis = ( # QT6 QT_API_PYQT6, QT_API_PYSIDE6, # QT5 QT_API_PYQT5, QT_API_PYSIDE2, # default QT_API_PYQT_DEFAULT, ) def matplotlib_options(mpl): """Constraints placed on an imported matplotlib.""" if mpl is None: return backend = mpl.rcParams.get('backend', None) if backend == 'Qt4Agg': mpqt = mpl.rcParams.get('backend.qt4', None) if mpqt is None: return None if mpqt.lower() == 'pyside': return [QT_API_PYSIDE] elif mpqt.lower() == 'pyqt4': return [QT_API_PYQT_DEFAULT] elif mpqt.lower() == 'pyqt4v2': return [QT_API_PYQT] raise ImportError("unhandled value for backend.qt4 from matplotlib: %r" % mpqt) elif backend == 'Qt5Agg': mpqt = mpl.rcParams.get('backend.qt5', None) if mpqt is None: return None if mpqt.lower() == 'pyqt5': return [QT_API_PYQT5] raise ImportError("unhandled value for backend.qt5 from matplotlib: %r" % mpqt) QT_API_PYSIDE6 = "pyside6" QT_API_PYSIDE2 = 'pyside2' def loaded_api(): """Return which API is loaded, if any If this returns anything besides None, importing any other Qt binding is unsafe. Returns ------- None, 'pyside6', 'pyqt6', 'pyside2', 'pyside', 'pyqt', 'pyqt5', 'pyqtv1' """ if sys.modules.get("PyQt6.QtCore"): return QT_API_PYQT6 elif sys.modules.get("PySide6.QtCore"): return QT_API_PYSIDE6 elif sys.modules.get("PyQt5.QtCore"): return QT_API_PYQT5 elif sys.modules.get("PySide2.QtCore"): return QT_API_PYSIDE2 elif sys.modules.get("PyQt4.QtCore"): if qtapi_version() == 2: return QT_API_PYQT else: return QT_API_PYQTv1 elif sys.modules.get("PySide.QtCore"): return QT_API_PYSIDE return None The provided code snippet includes necessary dependencies for implementing the `get_options` function. Write a Python function `def get_options()` to solve the following problem: Return a list of acceptable QT APIs, in decreasing order of preference. Here is the function: def get_options(): """Return a list of acceptable QT APIs, in decreasing order of preference.""" #already imported Qt somewhere. Use that loaded = loaded_api() if loaded is not None: return [loaded] mpl = sys.modules.get("matplotlib", None) if mpl is not None and tuple(mpl.__version__.split(".")) < ("1", "0", "2"): # 1.0.1 only supports PyQt4 v1 return [QT_API_PYQT_DEFAULT] qt_api = os.environ.get('QT_API', None) if qt_api is None: #no ETS variable. Ask mpl, then use default fallback path return matplotlib_options(mpl) or [ QT_API_PYQT_DEFAULT, QT_API_PYQT6, QT_API_PYSIDE6, QT_API_PYQT5, QT_API_PYSIDE2, ] elif qt_api not in _qt_apis: raise RuntimeError("Invalid Qt API %r, valid values are: %r" % (qt_api, ', '.join(_qt_apis))) else: return [qt_api]
Return a list of acceptable QT APIs, in decreasing order of preference.
176,884
import inspect, os, sys, textwrap from IPython.core.error import UsageError from IPython.core.magic import Magics, magics_class, line_magic from IPython.testing.skipdoctest import skip_doctest from traitlets import Bool def restore_aliases(ip, alias=None): def refresh_variables(ip): def restore_dhist(ip): def restore_data(ip): refresh_variables(ip) restore_aliases(ip) restore_dhist(ip)
null
176,885
import inspect, os, sys, textwrap from IPython.core.error import UsageError from IPython.core.magic import Magics, magics_class, line_magic from IPython.testing.skipdoctest import skip_doctest from traitlets import Bool class StoreMagics(Magics): """Lightweight persistence for python variables. Provides the %store magic.""" autorestore = Bool(False, help= """If True, any %store-d variables will be automatically restored when IPython starts. """ ).tag(config=True) def __init__(self, shell): super(StoreMagics, self).__init__(shell=shell) self.shell.configurables.append(self) if self.autorestore: restore_data(self.shell) def store(self, parameter_s=''): """Lightweight persistence for python variables. Example:: In [1]: l = ['hello',10,'world'] In [2]: %store l Stored 'l' (list) In [3]: exit (IPython session is closed and started again...) ville@badger:~$ ipython In [1]: l NameError: name 'l' is not defined In [2]: %store -r In [3]: l Out[3]: ['hello', 10, 'world'] Usage: * ``%store`` - Show list of all variables and their current values * ``%store spam bar`` - Store the *current* value of the variables spam and bar to disk * ``%store -d spam`` - Remove the variable and its value from storage * ``%store -z`` - Remove all variables from storage * ``%store -r`` - Refresh all variables, aliases and directory history from store (overwrite current vals) * ``%store -r spam bar`` - Refresh specified variables and aliases from store (delete current val) * ``%store foo >a.txt`` - Store value of foo to new file a.txt * ``%store foo >>a.txt`` - Append value of foo to file a.txt It should be noted that if you change the value of a variable, you need to %store it again if you want to persist the new value. Note also that the variables will need to be pickleable; most basic python types can be safely %store'd. Also aliases can be %store'd across sessions. To remove an alias from the storage, use the %unalias magic. """ opts,argsl = self.parse_options(parameter_s,'drz',mode='string') args = argsl.split() ip = self.shell db = ip.db # delete if 'd' in opts: try: todel = args[0] except IndexError as e: raise UsageError('You must provide the variable to forget') from e else: try: del db['autorestore/' + todel] except BaseException as e: raise UsageError("Can't delete variable '%s'" % todel) from e # reset elif 'z' in opts: for k in db.keys('autorestore/*'): del db[k] elif 'r' in opts: if args: for arg in args: try: obj = db['autorestore/' + arg] except KeyError: try: restore_aliases(ip, alias=arg) except KeyError: print("no stored variable or alias %s" % arg) else: ip.user_ns[arg] = obj else: restore_data(ip) # run without arguments -> list variables & values elif not args: vars = db.keys('autorestore/*') vars.sort() if vars: size = max(map(len, vars)) else: size = 0 print('Stored variables and their in-db values:') fmt = '%-'+str(size)+'s -> %s' get = db.get for var in vars: justkey = os.path.basename(var) # print 30 first characters from every var print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50])) # default action - store the variable else: # %store foo >file.txt or >>file.txt if len(args) > 1 and args[1].startswith(">"): fnam = os.path.expanduser(args[1].lstrip(">").lstrip()) if args[1].startswith(">>"): fil = open(fnam, "a", encoding="utf-8") else: fil = open(fnam, "w", encoding="utf-8") with fil: obj = ip.ev(args[0]) print("Writing '%s' (%s) to file '%s'." % (args[0], obj.__class__.__name__, fnam)) if not isinstance (obj, str): from pprint import pprint pprint(obj, fil) else: fil.write(obj) if not obj.endswith('\n'): fil.write('\n') return # %store foo for arg in args: try: obj = ip.user_ns[arg] except KeyError: # it might be an alias name = arg try: cmd = ip.alias_manager.retrieve_alias(name) except ValueError as e: raise UsageError("Unknown variable '%s'" % name) from e staliases = db.get('stored_aliases',{}) staliases[name] = cmd db['stored_aliases'] = staliases print("Alias stored: %s (%s)" % (name, cmd)) return else: modname = getattr(inspect.getmodule(obj), '__name__', '') if modname == '__main__': print(textwrap.dedent("""\ Warning:%s is %s Proper storage of interactively declared classes (or instances of those classes) is not possible! Only instances of classes in real modules on file system can be %%store'd. """ % (arg, obj) )) return #pickled = pickle.dumps(obj) db[ 'autorestore/' + arg ] = obj print("Stored '%s' (%s)" % (arg, obj.__class__.__name__)) The provided code snippet includes necessary dependencies for implementing the `load_ipython_extension` function. Write a Python function `def load_ipython_extension(ip)` to solve the following problem: Load the extension in IPython. Here is the function: def load_ipython_extension(ip): """Load the extension in IPython.""" ip.register_magics(StoreMagics)
Load the extension in IPython.
176,886
from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic import os import sys import traceback import types import weakref import gc import logging from importlib import import_module, reload from importlib.util import source_from_cache func_attrs = [ "__code__", "__defaults__", "__doc__", "__closure__", "__globals__", "__dict__", ] def load_ipython_extension(ip): """Load the extension in IPython.""" auto_reload = AutoreloadMagics(ip) ip.register_magics(auto_reload) ip.events.register("pre_run_cell", auto_reload.pre_run_cell) ip.events.register("post_execute", auto_reload.post_execute_hook) The provided code snippet includes necessary dependencies for implementing the `update_function` function. Write a Python function `def update_function(old, new)` to solve the following problem: Upgrade the code object of a function Here is the function: def update_function(old, new): """Upgrade the code object of a function""" for name in func_attrs: try: setattr(old, name, getattr(new, name)) except (AttributeError, TypeError): pass
Upgrade the code object of a function
176,887
from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic import os import sys import traceback import types import weakref import gc import logging from importlib import import_module, reload from importlib.util import source_from_cache def update_instances(old, new): """Use garbage collector to find all instances that refer to the old class definition and update their __class__ to point to the new class definition""" refs = gc.get_referrers(old) for ref in refs: if type(ref) is old: object.__setattr__(ref, "__class__", new) def update_generic(a, b): for type_check, update in UPDATE_RULES: if type_check(a, b): update(a, b) return True return False def load_ipython_extension(ip): """Load the extension in IPython.""" auto_reload = AutoreloadMagics(ip) ip.register_magics(auto_reload) ip.events.register("pre_run_cell", auto_reload.pre_run_cell) ip.events.register("post_execute", auto_reload.post_execute_hook) The provided code snippet includes necessary dependencies for implementing the `update_class` function. Write a Python function `def update_class(old, new)` to solve the following problem: Replace stuff in the __dict__ of a class, and upgrade method code objects, and add new methods, if any Here is the function: def update_class(old, new): """Replace stuff in the __dict__ of a class, and upgrade method code objects, and add new methods, if any""" for key in list(old.__dict__.keys()): old_obj = getattr(old, key) try: new_obj = getattr(new, key) # explicitly checking that comparison returns True to handle # cases where `==` doesn't return a boolean. if (old_obj == new_obj) is True: continue except AttributeError: # obsolete attribute: remove it try: delattr(old, key) except (AttributeError, TypeError): pass continue except ValueError: # can't compare nested structures containing # numpy arrays using `==` pass if update_generic(old_obj, new_obj): continue try: setattr(old, key, getattr(new, key)) except (AttributeError, TypeError): pass # skip non-writable attributes for key in list(new.__dict__.keys()): if key not in list(old.__dict__.keys()): try: setattr(old, key, getattr(new, key)) except (AttributeError, TypeError): pass # skip non-writable attributes # update all instances of class update_instances(old, new)
Replace stuff in the __dict__ of a class, and upgrade method code objects, and add new methods, if any
176,888
from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic import os import sys import traceback import types import weakref import gc import logging from importlib import import_module, reload from importlib.util import source_from_cache def update_generic(a, b): for type_check, update in UPDATE_RULES: if type_check(a, b): update(a, b) return True return False def load_ipython_extension(ip): """Load the extension in IPython.""" auto_reload = AutoreloadMagics(ip) ip.register_magics(auto_reload) ip.events.register("pre_run_cell", auto_reload.pre_run_cell) ip.events.register("post_execute", auto_reload.post_execute_hook) The provided code snippet includes necessary dependencies for implementing the `update_property` function. Write a Python function `def update_property(old, new)` to solve the following problem: Replace get/set/del functions of a property Here is the function: def update_property(old, new): """Replace get/set/del functions of a property""" update_generic(old.fdel, new.fdel) update_generic(old.fget, new.fget) update_generic(old.fset, new.fset)
Replace get/set/del functions of a property
176,889
from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic import os import sys import traceback import types import weakref import gc import logging from importlib import import_module, reload from importlib.util import source_from_cache def load_ipython_extension(ip): def isinstance2(a, b, typ): return isinstance(a, typ) and isinstance(b, typ)
null
176,890
from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic import os import sys import traceback import types import weakref import gc import logging from importlib import import_module, reload from importlib.util import source_from_cache def update_generic(a, b): for type_check, update in UPDATE_RULES: if type_check(a, b): update(a, b) return True return False def append_obj(module, d, name, obj, autoload=False): in_module = hasattr(obj, "__module__") and obj.__module__ == module.__name__ if autoload: # check needed for module global built-ins if not in_module and name in mod_attrs: return False else: if not in_module: return False key = (module.__name__, name) try: d.setdefault(key, []).append(weakref.ref(obj)) except TypeError: pass return True ) "-l", "--log", action="store_true", default=False, help="Show autoreload activity using the logger", def load_ipython_extension(ip): """Load the extension in IPython.""" auto_reload = AutoreloadMagics(ip) ip.register_magics(auto_reload) ip.events.register("pre_run_cell", auto_reload.pre_run_cell) ip.events.register("post_execute", auto_reload.post_execute_hook) The provided code snippet includes necessary dependencies for implementing the `superreload` function. Write a Python function `def superreload(module, reload=reload, old_objects=None, shell=None)` to solve the following problem: Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading Here is the function: def superreload(module, reload=reload, old_objects=None, shell=None): """Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading """ if old_objects is None: old_objects = {} # collect old objects in the module for name, obj in list(module.__dict__.items()): if not append_obj(module, old_objects, name, obj): continue key = (module.__name__, name) try: old_objects.setdefault(key, []).append(weakref.ref(obj)) except TypeError: pass # reload module try: # clear namespace first from old cruft old_dict = module.__dict__.copy() old_name = module.__name__ module.__dict__.clear() module.__dict__["__name__"] = old_name module.__dict__["__loader__"] = old_dict["__loader__"] except (TypeError, AttributeError, KeyError): pass try: module = reload(module) except: # restore module dictionary on failed reload module.__dict__.update(old_dict) raise # iterate over all objects and update functions & classes for name, new_obj in list(module.__dict__.items()): key = (module.__name__, name) if key not in old_objects: # here 'shell' acts both as a flag and as an output var if ( shell is None or name == "Enum" or not append_obj(module, old_objects, name, new_obj, True) ): continue shell.user_ns[name] = new_obj new_refs = [] for old_ref in old_objects[key]: old_obj = old_ref() if old_obj is None: continue new_refs.append(old_ref) update_generic(old_obj, new_obj) if new_refs: old_objects[key] = new_refs else: del old_objects[key] return module
Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading
176,891
from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic __skip_doctest__ = True import os import sys import traceback import types import weakref import gc import logging from importlib import import_module, reload from importlib.util import source_from_cache func_attrs = [ "__code__", "__defaults__", "__doc__", "__closure__", "__globals__", "__dict__", ] UPDATE_RULES = [ (lambda a, b: isinstance2(a, b, type), update_class), (lambda a, b: isinstance2(a, b, types.FunctionType), update_function), (lambda a, b: isinstance2(a, b, property), update_property), ] UPDATE_RULES.extend( [ ( lambda a, b: isinstance2(a, b, types.MethodType), lambda a, b: update_function(a.__func__, b.__func__), ), ] ) mod_attrs = [ "__name__", "__doc__", "__package__", "__loader__", "__spec__", "__file__", "__cached__", "__builtins__", ] class AutoreloadMagics(Magics): def __init__(self, *a, **kw): super().__init__(*a, **kw) self._reloader = ModuleReloader(self.shell) self._reloader.check_all = False self._reloader.autoload_obj = False self.loaded_modules = set(sys.modules) "mode", type=str, default="now", nargs="?", help="""blank or 'now' - Reload all modules (except those excluded by %%aimport) automatically now. '0' or 'off' - Disable automatic reloading. '1' or 'explicit' - Reload only modules imported with %%aimport every time before executing the Python code typed. '2' or 'all' - Reload all modules (except those excluded by %%aimport) every time before executing the Python code typed. '3' or 'complete' - Same as 2/all, but also but also adds any new objects in the module. """, ) "-p", "--print", action="store_true", default=False, help="Show autoreload activity using `print` statements", ) "-l", "--log", action="store_true", default=False, help="Show autoreload activity using the logger", ) def pre_run_cell(self): if self._reloader.enabled: try: self._reloader.check() except: pass def post_execute_hook(self): """Cache the modification times of any modules imported in this execution""" newly_loaded_modules = set(sys.modules) - self.loaded_modules for modname in newly_loaded_modules: _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname]) if pymtime is not None: self._reloader.modules_mtimes[modname] = pymtime self.loaded_modules.update(newly_loaded_modules) def load_ipython_extension(ip): """Load the extension in IPython.""" auto_reload = AutoreloadMagics(ip) ip.register_magics(auto_reload) ip.events.register("pre_run_cell", auto_reload.pre_run_cell) ip.events.register("post_execute", auto_reload.post_execute_hook) The provided code snippet includes necessary dependencies for implementing the `load_ipython_extension` function. Write a Python function `def load_ipython_extension(ip)` to solve the following problem: Load the extension in IPython. Here is the function: def load_ipython_extension(ip): """Load the extension in IPython.""" auto_reload = AutoreloadMagics(ip) ip.register_magics(auto_reload) ip.events.register("pre_run_cell", auto_reload.pre_run_cell) ip.events.register("post_execute", auto_reload.post_execute_hook)
Load the extension in IPython.
176,892
from sphinx import highlighting from IPython.lib.lexers import IPyLexer The provided code snippet includes necessary dependencies for implementing the `setup` function. Write a Python function `def setup(app)` to solve the following problem: Setup as a sphinx extension. Here is the function: def setup(app): """Setup as a sphinx extension.""" # This is only a lexer, so adding it below to pygments appears sufficient. # But if somebody knows what the right API usage should be to do that via # sphinx, by all means fix it here. At least having this setup.py # suppresses the sphinx warning we'd get without it. metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata
Setup as a sphinx extension.
176,893
import atexit import errno import os import pathlib import re import sys import tempfile import ast import warnings import shutil from io import StringIO from docutils.parsers.rst import directives from docutils.parsers.rst import Directive from sphinx.util import logging from traitlets.config import Config from IPython import InteractiveShell from IPython.core.profiledir import ProfileDir COMMENT, INPUT, OUTPUT = range(3) PSEUDO_DECORATORS = ["suppress", "verbatim", "savefig", "doctest"] The provided code snippet includes necessary dependencies for implementing the `block_parser` function. Write a Python function `def block_parser(part, rgxin, rgxout, fmtin, fmtout)` to solve the following problem: part is a string of ipython text, comprised of at most one input, one output, comments, and blank lines. The block parser parses the text into a list of:: blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depending on the type of token:: COMMENT : the comment string INPUT: the (DECORATOR, INPUT_LINE, REST) where DECORATOR: the input decorator (or None) INPUT_LINE: the input as string (possibly multi-line) REST : any stdout generated by the input line (not OUTPUT) OUTPUT: the output string, possibly multi-line Here is the function: def block_parser(part, rgxin, rgxout, fmtin, fmtout): """ part is a string of ipython text, comprised of at most one input, one output, comments, and blank lines. The block parser parses the text into a list of:: blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depending on the type of token:: COMMENT : the comment string INPUT: the (DECORATOR, INPUT_LINE, REST) where DECORATOR: the input decorator (or None) INPUT_LINE: the input as string (possibly multi-line) REST : any stdout generated by the input line (not OUTPUT) OUTPUT: the output string, possibly multi-line """ block = [] lines = part.split('\n') N = len(lines) i = 0 decorator = None while 1: if i==N: # nothing left to parse -- the last line break line = lines[i] i += 1 line_stripped = line.strip() if line_stripped.startswith('#'): block.append((COMMENT, line)) continue if any( line_stripped.startswith("@" + pseudo_decorator) for pseudo_decorator in PSEUDO_DECORATORS ): if decorator: raise RuntimeError( "Applying multiple pseudo-decorators on one line is not supported" ) else: decorator = line_stripped continue # does this look like an input line? matchin = rgxin.match(line) if matchin: lineno, inputline = int(matchin.group(1)), matchin.group(2) # the ....: continuation string continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) Nc = len(continuation) # input lines can continue on for more than one line, if # we have a '\' line continuation char or a function call # echo line 'print'. The input line can only be # terminated by the end of the block or an output line, so # we parse out the rest of the input line if it is # multiline as well as any echo text rest = [] while i<N: # look ahead; if the next line is blank, or a comment, or # an output line, we're done nextline = lines[i] matchout = rgxout.match(nextline) #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation)) if matchout or nextline.startswith('#'): break elif nextline.startswith(continuation): # The default ipython_rgx* treat the space following the colon as optional. # However, If the space is there we must consume it or code # employing the cython_magic extension will fail to execute. # # This works with the default ipython_rgx* patterns, # If you modify them, YMMV. nextline = nextline[Nc:] if nextline and nextline[0] == ' ': nextline = nextline[1:] inputline += '\n' + nextline else: rest.append(nextline) i+= 1 block.append((INPUT, (decorator, inputline, '\n'.join(rest)))) continue # if it looks like an output line grab all the text to the end # of the block matchout = rgxout.match(line) if matchout: lineno, output = int(matchout.group(1)), matchout.group(2) if i<N-1: output = '\n'.join([output] + lines[i:]) block.append((OUTPUT, output)) break return block
part is a string of ipython text, comprised of at most one input, one output, comments, and blank lines. The block parser parses the text into a list of:: blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depending on the type of token:: COMMENT : the comment string INPUT: the (DECORATOR, INPUT_LINE, REST) where DECORATOR: the input decorator (or None) INPUT_LINE: the input as string (possibly multi-line) REST : any stdout generated by the input line (not OUTPUT) OUTPUT: the output string, possibly multi-line
176,894
import atexit import errno import os import pathlib import re import sys import tempfile import ast import warnings import shutil from io import StringIO from docutils.parsers.rst import directives from docutils.parsers.rst import Directive from sphinx.util import logging from traitlets.config import Config from IPython import InteractiveShell from IPython.core.profiledir import ProfileDir use_matplotlib = False class IPythonDirective(Directive): has_content = True required_arguments = 0 optional_arguments = 4 # python, suppress, verbatim, doctest final_argumuent_whitespace = True option_spec = { 'python': directives.unchanged, 'suppress' : directives.flag, 'verbatim' : directives.flag, 'doctest' : directives.flag, 'okexcept': directives.flag, 'okwarning': directives.flag } shell = None seen_docs = set() def get_config_options(self): # contains sphinx configuration variables config = self.state.document.settings.env.config # get config variables to set figure output directory savefig_dir = config.ipython_savefig_dir source_dir = self.state.document.settings.env.srcdir savefig_dir = os.path.join(source_dir, savefig_dir) # get regex and prompt stuff rgxin = config.ipython_rgxin rgxout = config.ipython_rgxout warning_is_error= config.ipython_warning_is_error promptin = config.ipython_promptin promptout = config.ipython_promptout mplbackend = config.ipython_mplbackend exec_lines = config.ipython_execlines hold_count = config.ipython_holdcount return (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout, mplbackend, exec_lines, hold_count, warning_is_error) def setup(self): # Get configuration values. (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout, mplbackend, exec_lines, hold_count, warning_is_error) = self.get_config_options() try: os.makedirs(savefig_dir) except OSError as e: if e.errno != errno.EEXIST: raise if self.shell is None: # We will be here many times. However, when the # EmbeddedSphinxShell is created, its interactive shell member # is the same for each instance. if mplbackend and 'matplotlib.backends' not in sys.modules and use_matplotlib: import matplotlib matplotlib.use(mplbackend) # Must be called after (potentially) importing matplotlib and # setting its backend since exec_lines might import pylab. self.shell = EmbeddedSphinxShell(exec_lines) # Store IPython directive to enable better error messages self.shell.directive = self # reset the execution count if we haven't processed this doc #NOTE: this may be borked if there are multiple seen_doc tmp files #check time stamp? if not self.state.document.current_source in self.seen_docs: self.shell.IP.history_manager.reset() self.shell.IP.execution_count = 1 self.seen_docs.add(self.state.document.current_source) # and attach to shell so we don't have to pass them around self.shell.rgxin = rgxin self.shell.rgxout = rgxout self.shell.promptin = promptin self.shell.promptout = promptout self.shell.savefig_dir = savefig_dir self.shell.source_dir = source_dir self.shell.hold_count = hold_count self.shell.warning_is_error = warning_is_error # setup bookmark for saving figures directory self.shell.process_input_line( 'bookmark ipy_savedir "%s"' % savefig_dir, store_history=False ) self.shell.clear_cout() return rgxin, rgxout, promptin, promptout def teardown(self): # delete last bookmark self.shell.process_input_line('bookmark -d ipy_savedir', store_history=False) self.shell.clear_cout() def run(self): debug = False #TODO, any reason block_parser can't be a method of embeddable shell # then we wouldn't have to carry these around rgxin, rgxout, promptin, promptout = self.setup() options = self.options self.shell.is_suppress = 'suppress' in options self.shell.is_doctest = 'doctest' in options self.shell.is_verbatim = 'verbatim' in options self.shell.is_okexcept = 'okexcept' in options self.shell.is_okwarning = 'okwarning' in options # handle pure python code if 'python' in self.arguments: content = self.content self.content = self.shell.process_pure_python(content) # parts consists of all text within the ipython-block. # Each part is an input/output block. parts = '\n'.join(self.content).split('\n\n') lines = ['.. code-block:: ipython', ''] figures = [] # Use sphinx logger for warnings logger = logging.getLogger(__name__) for part in parts: block = block_parser(part, rgxin, rgxout, promptin, promptout) if len(block): rows, figure = self.shell.process_block(block) for row in rows: lines.extend([' {0}'.format(line) for line in row.split('\n')]) if figure is not None: figures.append(figure) else: message = 'Code input with no code at {}, line {}'\ .format( self.state.document.current_source, self.state.document.current_line) if self.shell.warning_is_error: raise RuntimeError(message) else: logger.warning(message) for figure in figures: lines.append('') lines.extend(figure.split('\n')) lines.append('') if len(lines) > 2: if debug: print('\n'.join(lines)) else: # This has to do with input, not output. But if we comment # these lines out, then no IPython code will appear in the # final output. self.state_machine.insert_input( lines, self.state_machine.input_lines.source(0)) # cleanup self.teardown() return [] def setup(app): setup.app = app app.add_directive('ipython', IPythonDirective) app.add_config_value('ipython_savefig_dir', 'savefig', 'env') app.add_config_value('ipython_warning_is_error', True, 'env') app.add_config_value('ipython_rgxin', re.compile(r'In \[(\d+)\]:\s?(.*)\s*'), 'env') app.add_config_value('ipython_rgxout', re.compile(r'Out\[(\d+)\]:\s?(.*)\s*'), 'env') app.add_config_value('ipython_promptin', 'In [%d]:', 'env') app.add_config_value('ipython_promptout', 'Out[%d]:', 'env') # We could just let matplotlib pick whatever is specified as the default # backend in the matplotlibrc file, but this would cause issues if the # backend didn't work in headless environments. For this reason, 'agg' # is a good default backend choice. app.add_config_value('ipython_mplbackend', 'agg', 'env') # If the user sets this config value to `None`, then EmbeddedSphinxShell's # __init__ method will treat it as []. execlines = ['import numpy as np'] if use_matplotlib: execlines.append('import matplotlib.pyplot as plt') app.add_config_value('ipython_execlines', execlines, 'env') app.add_config_value('ipython_holdcount', True, 'env') metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata
null
176,895
from warnings import warn warn( "The `IPython.utils.version` module has been deprecated since IPython 8.0.", DeprecationWarning, ) The provided code snippet includes necessary dependencies for implementing the `check_version` function. Write a Python function `def check_version(v, check)` to solve the following problem: check version string v >= check If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. Here is the function: def check_version(v, check): """check version string v >= check If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. """ warn( "`check_version` function is deprecated as of IPython 8.0" "and will be removed in future versions.", DeprecationWarning, stacklevel=2, ) from distutils.version import LooseVersion try: return LooseVersion(v) >= LooseVersion(check) except TypeError: return True
check version string v >= check If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date.
176,896
import os from IPython.utils.ipstruct import Struct color_templates = ( # Dark colors ("Black" , "0;30"), ("Red" , "0;31"), ("Green" , "0;32"), ("Brown" , "0;33"), ("Blue" , "0;34"), ("Purple" , "0;35"), ("Cyan" , "0;36"), ("LightGray" , "0;37"), # Light colors ("DarkGray" , "1;30"), ("LightRed" , "1;31"), ("LightGreen" , "1;32"), ("Yellow" , "1;33"), ("LightBlue" , "1;34"), ("LightPurple" , "1;35"), ("LightCyan" , "1;36"), ("White" , "1;37"), # Blinking colors. Probably should not be used in anything serious. ("BlinkBlack" , "5;30"), ("BlinkRed" , "5;31"), ("BlinkGreen" , "5;32"), ("BlinkYellow" , "5;33"), ("BlinkBlue" , "5;34"), ("BlinkPurple" , "5;35"), ("BlinkCyan" , "5;36"), ("BlinkLightGray", "5;37"), ) for name, value in color_templates: setattr(NoColors, name, '') The provided code snippet includes necessary dependencies for implementing the `make_color_table` function. Write a Python function `def make_color_table(in_class)` to solve the following problem: Build a set of color attributes in a class. Helper function for building the :class:`TermColors` and :class`InputTermColors`. Here is the function: def make_color_table(in_class): """Build a set of color attributes in a class. Helper function for building the :class:`TermColors` and :class`InputTermColors`. """ for name,value in color_templates: setattr(in_class,name,in_class._base % value)
Build a set of color attributes in a class. Helper function for building the :class:`TermColors` and :class`InputTermColors`.
176,897
import os, sys, threading import ctypes, msvcrt from ctypes import POINTER from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \ ULONG, LPCWSTR class AvoidUNCPath(object): """A context manager to protect command execution from UNC paths. In the Win32 API, commands can't be invoked with the cwd being a UNC path. This context manager temporarily changes directory to the 'C:' drive on entering, and restores the original working directory on exit. The context manager returns the starting working directory *if* it made a change and None otherwise, so that users can apply the necessary adjustment to their system calls in the event of a change. Examples -------- :: cmd = 'dir' with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) os.system(cmd) """ def __enter__(self): self.path = os.getcwd() self.is_unc_path = self.path.startswith(r"\\") if self.is_unc_path: # change to c drive (as cmd.exe cannot handle UNC addresses) os.chdir("C:") return self.path else: # We return None to signal that there was no change in the working # directory return None def __exit__(self, exc_type, exc_value, traceback): if self.is_unc_path: os.chdir(self.path) class Win32ShellCommandController(object): """Runs a shell command in a 'with' context. This implementation is Win32-specific. Example: # Runs the command interactively with default console stdin/stdout with ShellCommandController('python -i') as scc: scc.run() # Runs the command using the provided functions for stdin/stdout def my_stdout_func(s): # print or save the string 's' write_to_stdout(s) def my_stdin_func(): # If input is available, return it as a string. if input_available(): return get_input() # If no input available, return None after a short delay to # keep from blocking. else: time.sleep(0.01) return None with ShellCommandController('python -i') as scc: scc.run(my_stdout_func, my_stdin_func) """ def __init__(self, cmd, mergeout = True): """Initializes the shell command controller. The cmd is the program to execute, and mergeout is whether to blend stdout and stderr into one output in stdout. Merging them together in this fashion more reliably keeps stdout and stderr in the correct order especially for interactive shell usage. """ self.cmd = cmd self.mergeout = mergeout def __enter__(self): cmd = self.cmd mergeout = self.mergeout self.hstdout, self.hstdin, self.hstderr = None, None, None self.piProcInfo = None try: p_hstdout, c_hstdout, p_hstderr, \ c_hstderr, p_hstdin, c_hstdin = [None]*6 # SECURITY_ATTRIBUTES with inherit handle set to True saAttr = SECURITY_ATTRIBUTES() saAttr.nLength = ctypes.sizeof(saAttr) saAttr.bInheritHandle = True saAttr.lpSecurityDescriptor = None def create_pipe(uninherit): """Creates a Windows pipe, which consists of two handles. The 'uninherit' parameter controls which handle is not inherited by the child process. """ handles = HANDLE(), HANDLE() if not CreatePipe(ctypes.byref(handles[0]), ctypes.byref(handles[1]), ctypes.byref(saAttr), 0): raise ctypes.WinError() if not SetHandleInformation(handles[uninherit], HANDLE_FLAG_INHERIT, 0): raise ctypes.WinError() return handles[0].value, handles[1].value p_hstdout, c_hstdout = create_pipe(uninherit=0) # 'mergeout' signals that stdout and stderr should be merged. # We do that by using one pipe for both of them. if mergeout: c_hstderr = HANDLE() if not DuplicateHandle(GetCurrentProcess(), c_hstdout, GetCurrentProcess(), ctypes.byref(c_hstderr), 0, True, DUPLICATE_SAME_ACCESS): raise ctypes.WinError() else: p_hstderr, c_hstderr = create_pipe(uninherit=0) c_hstdin, p_hstdin = create_pipe(uninherit=1) # Create the process object piProcInfo = PROCESS_INFORMATION() siStartInfo = STARTUPINFO() siStartInfo.cb = ctypes.sizeof(siStartInfo) siStartInfo.hStdInput = c_hstdin siStartInfo.hStdOutput = c_hstdout siStartInfo.hStdError = c_hstderr siStartInfo.dwFlags = STARTF_USESTDHANDLES dwCreationFlags = CREATE_SUSPENDED | CREATE_NO_WINDOW # | CREATE_NEW_CONSOLE if not CreateProcess(None, u"cmd.exe /c " + cmd, None, None, True, dwCreationFlags, None, None, ctypes.byref(siStartInfo), ctypes.byref(piProcInfo)): raise ctypes.WinError() # Close this process's versions of the child handles CloseHandle(c_hstdin) c_hstdin = None CloseHandle(c_hstdout) c_hstdout = None if c_hstderr is not None: CloseHandle(c_hstderr) c_hstderr = None # Transfer ownership of the parent handles to the object self.hstdin = p_hstdin p_hstdin = None self.hstdout = p_hstdout p_hstdout = None if not mergeout: self.hstderr = p_hstderr p_hstderr = None self.piProcInfo = piProcInfo finally: if p_hstdin: CloseHandle(p_hstdin) if c_hstdin: CloseHandle(c_hstdin) if p_hstdout: CloseHandle(p_hstdout) if c_hstdout: CloseHandle(c_hstdout) if p_hstderr: CloseHandle(p_hstderr) if c_hstderr: CloseHandle(c_hstderr) return self def _stdin_thread(self, handle, hprocess, func, stdout_func): exitCode = DWORD() bytesWritten = DWORD(0) while True: #print("stdin thread loop start") # Get the input string (may be bytes or unicode) data = func() # None signals to poll whether the process has exited if data is None: #print("checking for process completion") if not GetExitCodeProcess(hprocess, ctypes.byref(exitCode)): raise ctypes.WinError() if exitCode.value != STILL_ACTIVE: return # TESTING: Does zero-sized writefile help? if not WriteFile(handle, "", 0, ctypes.byref(bytesWritten), None): raise ctypes.WinError() continue #print("\nGot str %s\n" % repr(data), file=sys.stderr) # Encode the string to the console encoding if isinstance(data, unicode): #FIXME: Python3 data = data.encode('utf_8') # What we have now must be a string of bytes if not isinstance(data, str): #FIXME: Python3 raise RuntimeError("internal stdin function string error") # An empty string signals EOF if len(data) == 0: return # In a windows console, sometimes the input is echoed, # but sometimes not. How do we determine when to do this? stdout_func(data) # WriteFile may not accept all the data at once. # Loop until everything is processed while len(data) != 0: #print("Calling writefile") if not WriteFile(handle, data, len(data), ctypes.byref(bytesWritten), None): # This occurs at exit if GetLastError() == ERROR_NO_DATA: return raise ctypes.WinError() #print("Called writefile") data = data[bytesWritten.value:] def _stdout_thread(self, handle, func): # Allocate the output buffer data = ctypes.create_string_buffer(4096) while True: bytesRead = DWORD(0) if not ReadFile(handle, data, 4096, ctypes.byref(bytesRead), None): le = GetLastError() if le == ERROR_BROKEN_PIPE: return else: raise ctypes.WinError() # FIXME: Python3 s = data.value[0:bytesRead.value] #print("\nv: %s" % repr(s), file=sys.stderr) func(s.decode('utf_8', 'replace')) def run(self, stdout_func = None, stdin_func = None, stderr_func = None): """Runs the process, using the provided functions for I/O. The function stdin_func should return strings whenever a character or characters become available. The functions stdout_func and stderr_func are called whenever something is printed to stdout or stderr, respectively. These functions are called from different threads (but not concurrently, because of the GIL). """ if stdout_func is None and stdin_func is None and stderr_func is None: return self._run_stdio() if stderr_func is not None and self.mergeout: raise RuntimeError("Shell command was initiated with " "merged stdin/stdout, but a separate stderr_func " "was provided to the run() method") # Create a thread for each input/output handle stdin_thread = None threads = [] if stdin_func: stdin_thread = threading.Thread(target=self._stdin_thread, args=(self.hstdin, self.piProcInfo.hProcess, stdin_func, stdout_func)) threads.append(threading.Thread(target=self._stdout_thread, args=(self.hstdout, stdout_func))) if not self.mergeout: if stderr_func is None: stderr_func = stdout_func threads.append(threading.Thread(target=self._stdout_thread, args=(self.hstderr, stderr_func))) # Start the I/O threads and the process if ResumeThread(self.piProcInfo.hThread) == 0xFFFFFFFF: raise ctypes.WinError() if stdin_thread is not None: stdin_thread.start() for thread in threads: thread.start() # Wait for the process to complete if WaitForSingleObject(self.piProcInfo.hProcess, INFINITE) == \ WAIT_FAILED: raise ctypes.WinError() # Wait for the I/O threads to complete for thread in threads: thread.join() # Wait for the stdin thread to complete if stdin_thread is not None: stdin_thread.join() def _stdin_raw_nonblock(self): """Use the raw Win32 handle of sys.stdin to do non-blocking reads""" # WARNING: This is experimental, and produces inconsistent results. # It's possible for the handle not to be appropriate for use # with WaitForSingleObject, among other things. handle = msvcrt.get_osfhandle(sys.stdin.fileno()) result = WaitForSingleObject(handle, 100) if result == WAIT_FAILED: raise ctypes.WinError() elif result == WAIT_TIMEOUT: print(".", end='') return None else: data = ctypes.create_string_buffer(256) bytesRead = DWORD(0) print('?', end='') if not ReadFile(handle, data, 256, ctypes.byref(bytesRead), None): raise ctypes.WinError() # This ensures the non-blocking works with an actual console # Not checking the error, so the processing will still work with # other handle types FlushConsoleInputBuffer(handle) data = data.value data = data.replace('\r\n', '\n') data = data.replace('\r', '\n') print(repr(data) + " ", end='') return data def _stdin_raw_block(self): """Use a blocking stdin read""" # The big problem with the blocking read is that it doesn't # exit when it's supposed to in all contexts. An extra # key-press may be required to trigger the exit. try: data = sys.stdin.read(1) data = data.replace('\r', '\n') return data except WindowsError as we: if we.winerror == ERROR_NO_DATA: # This error occurs when the pipe is closed return None else: # Otherwise let the error propagate raise we def _stdout_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stdout) sys.stdout.flush() def _stderr_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stderr) sys.stderr.flush() def _run_stdio(self): """Runs the process using the system standard I/O. IMPORTANT: stdin needs to be asynchronous, so the Python sys.stdin object is not used. Instead, msvcrt.kbhit/getwch are used asynchronously. """ # Disable Line and Echo mode #lpMode = DWORD() #handle = msvcrt.get_osfhandle(sys.stdin.fileno()) #if GetConsoleMode(handle, ctypes.byref(lpMode)): # set_console_mode = True # if not SetConsoleMode(handle, lpMode.value & # ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)): # raise ctypes.WinError() if self.mergeout: return self.run(stdout_func = self._stdout_raw, stdin_func = self._stdin_raw_block) else: return self.run(stdout_func = self._stdout_raw, stdin_func = self._stdin_raw_block, stderr_func = self._stderr_raw) # Restore the previous console mode #if set_console_mode: # if not SetConsoleMode(handle, lpMode.value): # raise ctypes.WinError() def __exit__(self, exc_type, exc_value, traceback): if self.hstdin: CloseHandle(self.hstdin) self.hstdin = None if self.hstdout: CloseHandle(self.hstdout) self.hstdout = None if self.hstderr: CloseHandle(self.hstderr) self.hstderr = None if self.piProcInfo is not None: CloseHandle(self.piProcInfo.hProcess) CloseHandle(self.piProcInfo.hThread) self.piProcInfo = None The provided code snippet includes necessary dependencies for implementing the `system` function. Write a Python function `def system(cmd)` to solve the following problem: Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger : func:`sys.displayhook` calls. Here is the function: def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger : func:`sys.displayhook` calls. """ with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) with Win32ShellCommandController(cmd) as scc: scc.run()
Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger : func:`sys.displayhook` calls.
176,898
import sys import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `extract_vars` function. Write a Python function `def extract_vars(*names,**kw)` to solve the following problem: Extract a set of variables by name from another frame. Parameters ---------- *names : str One or more variable names which will be extracted from the caller's frame. **kw : integer, optional How many frames in the stack to walk when looking for your variables. The default is 0, which will use the frame where the call was made. Examples -------- :: In [2]: def func(x): ...: y = 1 ...: print(sorted(extract_vars('x','y').items())) ...: In [3]: func('hello') [('x', 'hello'), ('y', 1)] Here is the function: def extract_vars(*names,**kw): """Extract a set of variables by name from another frame. Parameters ---------- *names : str One or more variable names which will be extracted from the caller's frame. **kw : integer, optional How many frames in the stack to walk when looking for your variables. The default is 0, which will use the frame where the call was made. Examples -------- :: In [2]: def func(x): ...: y = 1 ...: print(sorted(extract_vars('x','y').items())) ...: In [3]: func('hello') [('x', 'hello'), ('y', 1)] """ depth = kw.get('depth',0) callerNS = sys._getframe(depth+1).f_locals return dict((k,callerNS[k]) for k in names)
Extract a set of variables by name from another frame. Parameters ---------- *names : str One or more variable names which will be extracted from the caller's frame. **kw : integer, optional How many frames in the stack to walk when looking for your variables. The default is 0, which will use the frame where the call was made. Examples -------- :: In [2]: def func(x): ...: y = 1 ...: print(sorted(extract_vars('x','y').items())) ...: In [3]: func('hello') [('x', 'hello'), ('y', 1)]
176,899
import sys import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `extract_vars_above` function. Write a Python function `def extract_vars_above(*names)` to solve the following problem: Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names are extracted exactly from above the caller. This is simply a convenience function so that the very common case (for us) of skipping exactly 1 frame doesn't have to construct a special dict for keyword passing. Here is the function: def extract_vars_above(*names): """Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names are extracted exactly from above the caller. This is simply a convenience function so that the very common case (for us) of skipping exactly 1 frame doesn't have to construct a special dict for keyword passing.""" callerNS = sys._getframe(2).f_locals return dict((k,callerNS[k]) for k in names)
Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names are extracted exactly from above the caller. This is simply a convenience function so that the very common case (for us) of skipping exactly 1 frame doesn't have to construct a special dict for keyword passing.
176,900
import sys import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `debugx` function. Write a Python function `def debugx(expr,pre_msg='')` to solve the following problem: Print the value of an expression from the caller's frame. Takes an expression, evaluates it in the caller's frame and prints both the given expression and the resulting value (as well as a debug mark indicating the name of the calling function. The input must be of a form suitable for eval(). An optional message can be passed, which will be prepended to the printed expr->value pair. Here is the function: def debugx(expr,pre_msg=''): """Print the value of an expression from the caller's frame. Takes an expression, evaluates it in the caller's frame and prints both the given expression and the resulting value (as well as a debug mark indicating the name of the calling function. The input must be of a form suitable for eval(). An optional message can be passed, which will be prepended to the printed expr->value pair.""" cf = sys._getframe(1) print('[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, eval(expr,cf.f_globals,cf.f_locals)))
Print the value of an expression from the caller's frame. Takes an expression, evaluates it in the caller's frame and prints both the given expression and the resulting value (as well as a debug mark indicating the name of the calling function. The input must be of a form suitable for eval(). An optional message can be passed, which will be prepended to the printed expr->value pair.
176,901
import time try: import resource except ImportError: resource = None if resource is not None and hasattr(resource, "getrusage"): else: # There is no distinction of user/system time under windows, so we just use # time.process_time() for everything... clocku = clocks = clock = time.process_time The provided code snippet includes necessary dependencies for implementing the `clocku` function. Write a Python function `def clocku()` to solve the following problem: clocku() -> floating point number Return the *USER* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock(). Here is the function: def clocku(): """clocku() -> floating point number Return the *USER* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock().""" return resource.getrusage(resource.RUSAGE_SELF)[0]
clocku() -> floating point number Return the *USER* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock().
176,902
import time try: import resource except ImportError: resource = None if resource is not None and hasattr(resource, "getrusage"): else: # There is no distinction of user/system time under windows, so we just use # time.process_time() for everything... clocku = clocks = clock = time.process_time The provided code snippet includes necessary dependencies for implementing the `clocks` function. Write a Python function `def clocks()` to solve the following problem: clocks() -> floating point number Return the *SYSTEM* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock(). Here is the function: def clocks(): """clocks() -> floating point number Return the *SYSTEM* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock().""" return resource.getrusage(resource.RUSAGE_SELF)[1]
clocks() -> floating point number Return the *SYSTEM* CPU time in seconds since the start of the process. This is done via a call to resource.getrusage, so it avoids the wraparound problems in time.clock().
176,903
import time try: import resource except ImportError: resource = None if resource is not None and hasattr(resource, "getrusage"): else: # There is no distinction of user/system time under windows, so we just use # time.process_time() for everything... clocku = clocks = clock = time.process_time The provided code snippet includes necessary dependencies for implementing the `clock2` function. Write a Python function `def clock2()` to solve the following problem: clock2() -> (t_user,t_system) Similar to clock(), but return a tuple of user/system times. Here is the function: def clock2(): """clock2() -> (t_user,t_system) Similar to clock(), but return a tuple of user/system times.""" return resource.getrusage(resource.RUSAGE_SELF)[:2]
clock2() -> (t_user,t_system) Similar to clock(), but return a tuple of user/system times.
176,904
import time The provided code snippet includes necessary dependencies for implementing the `clock2` function. Write a Python function `def clock2()` to solve the following problem: Under windows, system CPU time can't be measured. This just returns process_time() and zero. Here is the function: def clock2(): """Under windows, system CPU time can't be measured. This just returns process_time() and zero.""" return time.process_time(), 0.0
Under windows, system CPU time can't be measured. This just returns process_time() and zero.
176,905
import time def timings_out(reps,func,*args,**kw): """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds, the time per call and the function's output. Under Unix, the return value is the sum of user+system time consumed by the process, computed via the resource module. This prevents problems related to the wraparound effect which the time.clock() function has. Under Windows the return value is in wall clock seconds. See the documentation for the time module for more details.""" reps = int(reps) assert reps >=1, 'reps must be >= 1' if reps==1: start = clock() out = func(*args,**kw) tot_time = clock()-start else: rng = range(reps-1) # the last time is executed separately to store output start = clock() for dummy in rng: func(*args,**kw) out = func(*args,**kw) # one last time tot_time = clock()-start av_time = tot_time / reps return tot_time,av_time,out The provided code snippet includes necessary dependencies for implementing the `timings` function. Write a Python function `def timings(reps,func,*args,**kw)` to solve the following problem: timings(reps,func,*args,**kw) -> (t_total,t_per_call) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds and the time per call. These are just the first two values in timings_out(). Here is the function: def timings(reps,func,*args,**kw): """timings(reps,func,*args,**kw) -> (t_total,t_per_call) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds and the time per call. These are just the first two values in timings_out().""" return timings_out(reps,func,*args,**kw)[0:2]
timings(reps,func,*args,**kw) -> (t_total,t_per_call) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds and the time per call. These are just the first two values in timings_out().
176,906
import time def timings_out(reps,func,*args,**kw): """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds, the time per call and the function's output. Under Unix, the return value is the sum of user+system time consumed by the process, computed via the resource module. This prevents problems related to the wraparound effect which the time.clock() function has. Under Windows the return value is in wall clock seconds. See the documentation for the time module for more details.""" reps = int(reps) assert reps >=1, 'reps must be >= 1' if reps==1: start = clock() out = func(*args,**kw) tot_time = clock()-start else: rng = range(reps-1) # the last time is executed separately to store output start = clock() for dummy in rng: func(*args,**kw) out = func(*args,**kw) # one last time tot_time = clock()-start av_time = tot_time / reps return tot_time,av_time,out The provided code snippet includes necessary dependencies for implementing the `timing` function. Write a Python function `def timing(func,*args,**kw)` to solve the following problem: timing(func,*args,**kw) -> t_total Execute a function once, return the elapsed total CPU time in seconds. This is just the first value in timings_out(). Here is the function: def timing(func,*args,**kw): """timing(func,*args,**kw) -> t_total Execute a function once, return the elapsed total CPU time in seconds. This is just the first value in timings_out().""" return timings_out(1,func,*args,**kw)[0]
timing(func,*args,**kw) -> t_total Execute a function once, return the elapsed total CPU time in seconds. This is just the first value in timings_out().
176,907
import subprocess import shlex import sys import os from IPython.utils import py3compat def process_handler(cmd, callback, stderr=subprocess.PIPE): """Open a command in a shell subprocess and execute a callback. This function provides common scaffolding for creating subprocess.Popen() calls. It creates a Popen object and then calls the callback with it. Parameters ---------- cmd : str or list A command to be executed by the system, using :class:`subprocess.Popen`. If a string is passed, it will be run in the system shell. If a list is passed, it will be used directly as arguments. callback : callable A one-argument function that will be called with the Popen object. stderr : file descriptor number, optional By default this is set to ``subprocess.PIPE``, but you can also pass the value ``subprocess.STDOUT`` to force the subprocess' stderr to go into the same file descriptor as its stdout. This is useful to read stdout and stderr combined in the order they are generated. Returns ------- The return value of the provided callback is returned. """ sys.stdout.flush() sys.stderr.flush() # On win32, close_fds can't be true when using pipes for stdin/out/err close_fds = sys.platform != 'win32' # Determine if cmd should be run with system shell. shell = isinstance(cmd, str) # On POSIX systems run shell commands with user-preferred shell. executable = None if shell and os.name == 'posix' and 'SHELL' in os.environ: executable = os.environ['SHELL'] p = subprocess.Popen(cmd, shell=shell, executable=executable, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=close_fds) try: out = callback(p) except KeyboardInterrupt: print('^C') sys.stdout.flush() sys.stderr.flush() out = None finally: # Make really sure that we don't leave processes behind, in case the # call above raises an exception # We start by assuming the subprocess finished (to avoid NameErrors # later depending on the path taken) if p.returncode is None: try: p.terminate() p.poll() except OSError: pass # One last try on our way out if p.returncode is None: try: p.kill() except OSError: pass return out import subprocess The provided code snippet includes necessary dependencies for implementing the `getoutput` function. Write a Python function `def getoutput(cmd)` to solve the following problem: Run a command and return its stdout/stderr as a string. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- output : str A string containing the combination of stdout and stderr from the subprocess, in whatever order the subprocess originally wrote to its file descriptors (so the order of the information in this string is the correct order as would be seen if running the command in a terminal). Here is the function: def getoutput(cmd): """Run a command and return its stdout/stderr as a string. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- output : str A string containing the combination of stdout and stderr from the subprocess, in whatever order the subprocess originally wrote to its file descriptors (so the order of the information in this string is the correct order as would be seen if running the command in a terminal). """ out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT) if out is None: return '' return py3compat.decode(out)
Run a command and return its stdout/stderr as a string. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- output : str A string containing the combination of stdout and stderr from the subprocess, in whatever order the subprocess originally wrote to its file descriptors (so the order of the information in this string is the correct order as would be seen if running the command in a terminal).
176,908
import subprocess import shlex import sys import os from IPython.utils import py3compat def get_output_error_code(cmd): """Return (standard output, standard error, return code) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str stderr : str returncode: int """ out_err, p = process_handler(cmd, lambda p: (p.communicate(), p)) if out_err is None: return '', '', p.returncode out, err = out_err return py3compat.decode(out), py3compat.decode(err), p.returncode The provided code snippet includes necessary dependencies for implementing the `getoutputerror` function. Write a Python function `def getoutputerror(cmd)` to solve the following problem: Return (standard output, standard error) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str stderr : str Here is the function: def getoutputerror(cmd): """Return (standard output, standard error) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str stderr : str """ return get_output_error_code(cmd)[:2]
Return (standard output, standard error) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str stderr : str
176,909
import functools import linecache from warnings import warn The provided code snippet includes necessary dependencies for implementing the `getlines` function. Write a Python function `def getlines(filename, module_globals=None)` to solve the following problem: Deprecated since IPython 6.0 Here is the function: def getlines(filename, module_globals=None): """ Deprecated since IPython 6.0 """ warn(("`IPython.utils.ulinecache.getlines` is deprecated since" " IPython 6.0 and will be removed in future versions."), DeprecationWarning, stacklevel=2) return linecache.getlines(filename, module_globals=module_globals)
Deprecated since IPython 6.0
176,910
from collections import namedtuple from io import StringIO from keyword import iskeyword import tokenize The provided code snippet includes necessary dependencies for implementing the `line_at_cursor` function. Write a Python function `def line_at_cursor(cell, cursor_pos=0)` to solve the following problem: Return the line in a cell at a given cursor position Used for calling line-based APIs that don't support multi-line input, yet. Parameters ---------- cell : str multiline block of text cursor_pos : integer the cursor position Returns ------- (line, offset): (string, integer) The line with the current cursor, and the character offset of the start of the line. Here is the function: def line_at_cursor(cell, cursor_pos=0): """Return the line in a cell at a given cursor position Used for calling line-based APIs that don't support multi-line input, yet. Parameters ---------- cell : str multiline block of text cursor_pos : integer the cursor position Returns ------- (line, offset): (string, integer) The line with the current cursor, and the character offset of the start of the line. """ offset = 0 lines = cell.splitlines(True) for line in lines: next_offset = offset + len(line) if not line.endswith('\n'): # If the last line doesn't have a trailing newline, treat it as if # it does so that the cursor at the end of the line still counts # as being on that line. next_offset += 1 if next_offset > cursor_pos: break offset = next_offset else: line = "" return (line, offset)
Return the line in a cell at a given cursor position Used for calling line-based APIs that don't support multi-line input, yet. Parameters ---------- cell : str multiline block of text cursor_pos : integer the cursor position Returns ------- (line, offset): (string, integer) The line with the current cursor, and the character offset of the start of the line.
176,911
from collections import namedtuple from io import StringIO from keyword import iskeyword import tokenize Token = namedtuple('Token', ['token', 'text', 'start', 'end', 'line']) def generate_tokens(readline): """wrap generate_tokens to catch EOF errors""" try: for token in tokenize.generate_tokens(readline): yield token except tokenize.TokenError: # catch EOF error return class StringIO(TextIOWrapper): def __init__(self, initial_value: Optional[str] = ..., newline: Optional[str] = ...) -> None: ... # StringIO does not contain a "name" field. This workaround is necessary # to allow StringIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def getvalue(self) -> str: ... def iskeyword(s: Text) -> bool: ... The provided code snippet includes necessary dependencies for implementing the `token_at_cursor` function. Write a Python function `def token_at_cursor(cell, cursor_pos=0)` to solve the following problem: Get the token at a given cursor Used for introspection. Function calls are prioritized, so the token for the callable will be returned if the cursor is anywhere inside the call. Parameters ---------- cell : unicode A block of Python code cursor_pos : int The location of the cursor in the block where the token should be found Here is the function: def token_at_cursor(cell, cursor_pos=0): """Get the token at a given cursor Used for introspection. Function calls are prioritized, so the token for the callable will be returned if the cursor is anywhere inside the call. Parameters ---------- cell : unicode A block of Python code cursor_pos : int The location of the cursor in the block where the token should be found """ names = [] tokens = [] call_names = [] offsets = {1: 0} # lines start at 1 for tup in generate_tokens(StringIO(cell).readline): tok = Token(*tup) # token, text, start, end, line = tup start_line, start_col = tok.start end_line, end_col = tok.end if end_line + 1 not in offsets: # keep track of offsets for each line lines = tok.line.splitlines(True) for lineno, line in enumerate(lines, start_line + 1): if lineno not in offsets: offsets[lineno] = offsets[lineno-1] + len(line) offset = offsets[start_line] # allow '|foo' to find 'foo' at the beginning of a line boundary = cursor_pos + 1 if start_col == 0 else cursor_pos if offset + start_col >= boundary: # current token starts after the cursor, # don't consume it break if tok.token == tokenize.NAME and not iskeyword(tok.text): if names and tokens and tokens[-1].token == tokenize.OP and tokens[-1].text == '.': names[-1] = "%s.%s" % (names[-1], tok.text) else: names.append(tok.text) elif tok.token == tokenize.OP: if tok.text == '=' and names: # don't inspect the lhs of an assignment names.pop(-1) if tok.text == '(' and names: # if we are inside a function call, inspect the function call_names.append(names[-1]) elif tok.text == ')' and call_names: call_names.pop(-1) tokens.append(tok) if offsets[end_line] + end_col > cursor_pos: # we found the cursor, stop reading break if call_names: return call_names[-1] elif names: return names[-1] else: return ''
Get the token at a given cursor Used for introspection. Function calls are prioritized, so the token for the callable will be returned if the cursor is anywhere inside the call. Parameters ---------- cell : unicode A block of Python code cursor_pos : int The location of the cursor in the block where the token should be found
176,912
import inspect import types The provided code snippet includes necessary dependencies for implementing the `get_real_method` function. Write a Python function `def get_real_method(obj, name)` to solve the following problem: Like getattr, but with a few extra sanity checks: - If obj is a class, ignore everything except class methods - Check if obj is a proxy that claims to have all attributes - Catch attribute access failing with any exception - Check that the attribute is a callable object Returns the method or None. Here is the function: def get_real_method(obj, name): """Like getattr, but with a few extra sanity checks: - If obj is a class, ignore everything except class methods - Check if obj is a proxy that claims to have all attributes - Catch attribute access failing with any exception - Check that the attribute is a callable object Returns the method or None. """ try: canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None) except Exception: return None if canary is not None: # It claimed to have an attribute it should never have return None try: m = getattr(obj, name, None) except Exception: return None if inspect.isclass(obj) and not isinstance(m, types.MethodType): return None if callable(m): return m return None
Like getattr, but with a few extra sanity checks: - If obj is a class, ignore everything except class methods - Check if obj is a proxy that claims to have all attributes - Catch attribute access failing with any exception - Check that the attribute is a callable object Returns the method or None.
176,913
import errno import os import subprocess as sp import sys import pexpect from ._process_common import getoutput, arg_split from IPython.utils.encoding import DEFAULT_ENCODING import os if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError def check_pid(pid): try: os.kill(pid, 0) except OSError as err: if err.errno == errno.ESRCH: return False elif err.errno == errno.EPERM: # Don't have permission to signal the process - probably means it exists return True raise else: return True
null
176,914
import os import platform import pprint import sys import subprocess from IPython.core import release from IPython.utils import _sysinfo, encoding def get_sys_info(): """Return useful information about IPython and the system, as a dict.""" p = os.path path = p.realpath(p.dirname(p.abspath(p.join(__file__, '..')))) return pkg_info(path) The provided code snippet includes necessary dependencies for implementing the `sys_info` function. Write a Python function `def sys_info()` to solve the following problem: Return useful information about IPython and the system, as a string. Examples -------- :: In [2]: print(sys_info()) {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'} Here is the function: def sys_info(): """Return useful information about IPython and the system, as a string. Examples -------- :: In [2]: print(sys_info()) {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'} """ return pprint.pformat(get_sys_info())
Return useful information about IPython and the system, as a string. Examples -------- :: In [2]: print(sys_info()) {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}
176,915
import os import platform import pprint import sys import subprocess from IPython.core import release from IPython.utils import _sysinfo, encoding import os if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError import warnings warnings.warn("Importing from numpy.testing.utils is deprecated " "since 1.15.0, import from numpy.testing instead.", DeprecationWarning, stacklevel=2) The provided code snippet includes necessary dependencies for implementing the `num_cpus` function. Write a Python function `def num_cpus()` to solve the following problem: DEPRECATED Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect). Here is the function: def num_cpus(): """DEPRECATED Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect). """ import warnings warnings.warn( "`num_cpus` is deprecated since IPython 8.0. Use `os.cpu_count` instead.", DeprecationWarning, stacklevel=2, ) return os.cpu_count() or 1
DEPRECATED Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect).
176,916
import sys import locale import warnings def get_stream_enc(stream, default=None): """Return the given stream's encoding or a default. There are cases where ``sys.std*`` might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. ``default`` is None if not provided. """ if not hasattr(stream, 'encoding') or not stream.encoding: return default else: return stream.encoding import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) import warnings warnings.warn("Importing from numpy.testing.utils is deprecated " "since 1.15.0, import from numpy.testing instead.", DeprecationWarning, stacklevel=2) The provided code snippet includes necessary dependencies for implementing the `getdefaultencoding` function. Write a Python function `def getdefaultencoding(prefer_stream=True)` to solve the following problem: Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually UTF8 as of Python 3. Here is the function: def getdefaultencoding(prefer_stream=True): """Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually UTF8 as of Python 3. """ enc = None if prefer_stream: enc = get_stream_enc(sys.stdin) if not enc or enc=='ascii': try: # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative here. enc = locale.getpreferredencoding() except Exception: pass enc = enc or sys.getdefaultencoding() # On windows `cp0` can be returned to indicate that there is no code page. # Since cp0 is an invalid encoding return instead cp1252 which is the # Western European default. if enc == 'cp0': warnings.warn( "Invalid code page cp0 detected - using cp1252 instead." "If cp1252 is incorrect please ensure a valid code page " "is defined for the process.", RuntimeWarning) return 'cp1252' return enc
Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually UTF8 as of Python 3.
176,917
from IPython.core.error import TryNext from functools import singledispatch class TryNext(IPythonCoreError): """Try next hook exception. Raise this in your hook function to indicate that the next hook handler should be used to handle the operation. """ The provided code snippet includes necessary dependencies for implementing the `inspect_object` function. Write a Python function `def inspect_object(obj)` to solve the following problem: Called when you do obj? Here is the function: def inspect_object(obj): """Called when you do obj?""" raise TryNext
Called when you do obj?
176,918
from IPython.core.error import TryNext from functools import singledispatch class TryNext(IPythonCoreError): """Try next hook exception. Raise this in your hook function to indicate that the next hook handler should be used to handle the operation. """ The provided code snippet includes necessary dependencies for implementing the `complete_object` function. Write a Python function `def complete_object(obj, prev_completions)` to solve the following problem: Custom completer dispatching for python objects. Parameters ---------- obj : object The object to complete. prev_completions : list List of attributes discovered so far. This should return the list of attributes in obj. If you only wish to add to the attributes already discovered normally, return own_attrs + prev_completions. Here is the function: def complete_object(obj, prev_completions): """Custom completer dispatching for python objects. Parameters ---------- obj : object The object to complete. prev_completions : list List of attributes discovered so far. This should return the list of attributes in obj. If you only wish to add to the attributes already discovered normally, return own_attrs + prev_completions. """ raise TryNext
Custom completer dispatching for python objects. Parameters ---------- obj : object The object to complete. prev_completions : list List of attributes discovered so far. This should return the list of attributes in obj. If you only wish to add to the attributes already discovered normally, return own_attrs + prev_completions.
176,919
import os import sys import errno import shutil import random import glob from IPython.utils.process import system if sys.platform == 'win32': def _get_long_path_name(path): """Get a long path name (expand ~) on Windows using ctypes. Examples -------- >>> get_long_path_name('c:\\\\docume~1') 'c:\\\\Documents and Settings' """ try: import ctypes except ImportError as e: raise ImportError('you need to have ctypes installed for this to work') from e _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint ] buf = ctypes.create_unicode_buffer(260) rv = _GetLongPathName(path, buf, 260) if rv == 0 or rv > 260: return path else: return buf.value else: def _get_long_path_name(path): """Dummy no-op.""" return path The provided code snippet includes necessary dependencies for implementing the `get_long_path_name` function. Write a Python function `def get_long_path_name(path)` to solve the following problem: Expand a path into its long form. On Windows this expands any ~ in the paths. On other platforms, it is a null operation. Here is the function: def get_long_path_name(path): """Expand a path into its long form. On Windows this expands any ~ in the paths. On other platforms, it is a null operation. """ return _get_long_path_name(path)
Expand a path into its long form. On Windows this expands any ~ in the paths. On other platforms, it is a null operation.
176,920
import os import sys import errno import shutil import random import glob from IPython.utils.process import system import os if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError The provided code snippet includes necessary dependencies for implementing the `get_py_filename` function. Write a Python function `def get_py_filename(name)` to solve the following problem: Return a valid python filename in the current directory. If the given name is not a file, it adds '.py' and searches again. Raises IOError with an informative message if the file isn't found. Here is the function: def get_py_filename(name): """Return a valid python filename in the current directory. If the given name is not a file, it adds '.py' and searches again. Raises IOError with an informative message if the file isn't found. """ name = os.path.expanduser(name) if os.path.isfile(name): return name if not name.endswith(".py"): py_name = name + ".py" if os.path.isfile(py_name): return py_name raise IOError("File `%r` not found." % name)
Return a valid python filename in the current directory. If the given name is not a file, it adds '.py' and searches again. Raises IOError with an informative message if the file isn't found.
176,921
import os import sys import errno import shutil import random import glob from IPython.utils.process import system def expand_path(s): """Expand $VARS and ~names in a string, like a shell :Examples: In [2]: os.environ['FOO']='test' In [3]: expand_path('variable FOO is $FOO') Out[3]: 'variable FOO is test' """ # This is a pretty subtle hack. When expand user is given a UNC path # on Windows (\\server\share$\%username%), os.path.expandvars, removes # the $ to get (\\server\share\%username%). I think it considered $ # alone an empty var. But, we need the $ to remains there (it indicates # a hidden share). if os.name=='nt': s = s.replace('$\\', 'IPYTHON_TEMP') s = os.path.expandvars(os.path.expanduser(s)) if os.name=='nt': s = s.replace('IPYTHON_TEMP', '$\\') return s import os if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError The provided code snippet includes necessary dependencies for implementing the `filefind` function. Write a Python function `def filefind(filename: str, path_dirs=None) -> str` to solve the following problem: Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurrence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a simple call:: filefind('myfile.txt') will find the file in the current working dir, but:: filefind('~/myfile.txt') Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user's home directory. Parameters ---------- filename : str The filename to look for. path_dirs : str, None or sequence of str The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with ``filename``, calling :func:`expandvars` and :func:`expanduser` before testing for existence. Returns ------- path : str returns absolute path to file. Raises ------ IOError Here is the function: def filefind(filename: str, path_dirs=None) -> str: """Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurrence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a simple call:: filefind('myfile.txt') will find the file in the current working dir, but:: filefind('~/myfile.txt') Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user's home directory. Parameters ---------- filename : str The filename to look for. path_dirs : str, None or sequence of str The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with ``filename``, calling :func:`expandvars` and :func:`expanduser` before testing for existence. Returns ------- path : str returns absolute path to file. Raises ------ IOError """ # If paths are quoted, abspath gets confused, strip them... filename = filename.strip('"').strip("'") # If the input is an absolute path, just check it exists if os.path.isabs(filename) and os.path.isfile(filename): return filename if path_dirs is None: path_dirs = ("",) elif isinstance(path_dirs, str): path_dirs = (path_dirs,) for path in path_dirs: if path == '.': path = os.getcwd() testname = expand_path(os.path.join(path, filename)) if os.path.isfile(testname): return os.path.abspath(testname) raise IOError("File %r does not exist in any of the search paths: %r" % (filename, path_dirs) )
Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurrence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expandvars` and :func:`expanduser`. Thus a simple call:: filefind('myfile.txt') will find the file in the current working dir, but:: filefind('~/myfile.txt') Will find the file in the users home directory. This function does not automatically try any paths, such as the cwd or the user's home directory. Parameters ---------- filename : str The filename to look for. path_dirs : str, None or sequence of str The sequence of paths to look for the file in. If None, the filename need to be absolute or be in the cwd. If a string, the string is put into a sequence and the searched. If a sequence, walk through each element and join with ``filename``, calling :func:`expandvars` and :func:`expanduser` before testing for existence. Returns ------- path : str returns absolute path to file. Raises ------ IOError
176,922
import os import sys import errno import shutil import random import glob from IPython.utils.process import system if sys.platform == 'win32': else: def unescape_glob(string): """Unescape glob pattern in `string`.""" def unescape(s): for pattern in '*[]!?': s = s.replace(r'\{0}'.format(pattern), pattern) return s return '\\'.join(map(unescape, string.split('\\\\'))) import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `shellglob` function. Write a Python function `def shellglob(args)` to solve the following problem: Do glob expansion for each element in `args` and return a flattened list. Unmatched glob pattern will remain as-is in the returned list. Here is the function: def shellglob(args): """ Do glob expansion for each element in `args` and return a flattened list. Unmatched glob pattern will remain as-is in the returned list. """ expanded = [] # Do not unescape backslash in Windows as it is interpreted as # path separator: unescape = unescape_glob if sys.platform != 'win32' else lambda x: x for a in args: expanded.extend(glob.glob(a) or [unescape(a)]) return expanded
Do glob expansion for each element in `args` and return a flattened list. Unmatched glob pattern will remain as-is in the returned list.
176,923
import os import sys import errno import shutil import random import glob from IPython.utils.process import system def target_outdated(target,deps): """Determine whether a target is out of date. target_outdated(target,deps) -> 1/0 deps: list of filenames which MUST exist. target: single filename which may or may not exist. If target doesn't exist or is older than any file listed in deps, return true, otherwise return false. """ try: target_time = os.path.getmtime(target) except os.error: return 1 for dep in deps: dep_time = os.path.getmtime(dep) if dep_time > target_time: #print "For target",target,"Dep failed:",dep # dbg #print "times (dep,tar):",dep_time,target_time # dbg return 1 return 0 The provided code snippet includes necessary dependencies for implementing the `target_update` function. Write a Python function `def target_update(target,deps,cmd)` to solve the following problem: Update a target with a given command given a list of dependencies. target_update(target,deps,cmd) -> runs cmd if target is outdated. This is just a wrapper around target_outdated() which calls the given command if target is outdated. Here is the function: def target_update(target,deps,cmd): """Update a target with a given command given a list of dependencies. target_update(target,deps,cmd) -> runs cmd if target is outdated. This is just a wrapper around target_outdated() which calls the given command if target is outdated.""" if target_outdated(target,deps): system(cmd)
Update a target with a given command given a list of dependencies. target_update(target,deps,cmd) -> runs cmd if target is outdated. This is just a wrapper around target_outdated() which calls the given command if target is outdated.
176,924
import os import sys import errno import shutil import random import glob from IPython.utils.process import system def link(src, dst): """Hard links ``src`` to ``dst``, returning 0 or errno. Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't supported by the operating system. """ if not hasattr(os, "link"): return ENOLINK link_errno = 0 try: os.link(src, dst) except OSError as e: link_errno = e.errno return link_errno import os if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError The provided code snippet includes necessary dependencies for implementing the `link_or_copy` function. Write a Python function `def link_or_copy(src, dst)` to solve the following problem: Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place. Here is the function: def link_or_copy(src, dst): """Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) link_errno = link(src, dst) if link_errno == errno.EEXIST: if os.stat(src).st_ino == os.stat(dst).st_ino: # dst is already a hard link to the correct file, so we don't need # to do anything else. If we try to link and rename the file # anyway, we get duplicate files - see http://bugs.python.org/issue21876 return new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), ) try: link_or_copy(src, new_dst) except: try: os.remove(new_dst) except OSError: pass raise os.rename(new_dst, dst) elif link_errno != 0: # Either link isn't supported, or the filesystem doesn't support # linking, or 'src' and 'dst' are on different filesystems. shutil.copy(src, dst)
Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place.
176,925
import importlib import sys import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `find_mod` function. Write a Python function `def find_mod(module_name)` to solve the following problem: Find module `module_name` on sys.path, and return the path to module `module_name`. - If `module_name` refers to a module directory, then return path to __init__ file. - If `module_name` is a directory without an __init__file, return None. - If module is missing or does not have a `.py` or `.pyw` extension, return None. - Note that we are not interested in running bytecode. - Otherwise, return the fill path of the module. Parameters ---------- module_name : str Returns ------- module_path : str Path to module `module_name`, its __init__.py, or None, depending on above conditions. Here is the function: def find_mod(module_name): """ Find module `module_name` on sys.path, and return the path to module `module_name`. - If `module_name` refers to a module directory, then return path to __init__ file. - If `module_name` is a directory without an __init__file, return None. - If module is missing or does not have a `.py` or `.pyw` extension, return None. - Note that we are not interested in running bytecode. - Otherwise, return the fill path of the module. Parameters ---------- module_name : str Returns ------- module_path : str Path to module `module_name`, its __init__.py, or None, depending on above conditions. """ spec = importlib.util.find_spec(module_name) module_path = spec.origin if module_path is None: if spec.loader in sys.meta_path: return spec.loader return None else: split_path = module_path.split(".") if split_path[-1] in ["py", "pyw"]: return module_path else: return None
Find module `module_name` on sys.path, and return the path to module `module_name`. - If `module_name` refers to a module directory, then return path to __init__ file. - If `module_name` is a directory without an __init__file, return None. - If module is missing or does not have a `.py` or `.pyw` extension, return None. - Note that we are not interested in running bytecode. - Otherwise, return the fill path of the module. Parameters ---------- module_name : str Returns ------- module_path : str Path to module `module_name`, its __init__.py, or None, depending on above conditions.
176,926
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size if os.name == 'posix': elif sys.platform == 'win32': else: if os.name == 'posix': TERM = os.environ.get('TERM','') if TERM.startswith('xterm'): _set_term_title = _set_term_title_xterm _restore_term_title = _restore_term_title_xterm elif sys.platform == 'win32': import ctypes SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW SetConsoleTitleW.argtypes = [ctypes.c_wchar_p] import os if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError def _term_clear(): os.system('clear')
null
176,927
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size if os.name == 'posix': elif sys.platform == 'win32': else: if os.name == 'posix': TERM = os.environ.get('TERM','') if TERM.startswith('xterm'): _set_term_title = _set_term_title_xterm _restore_term_title = _restore_term_title_xterm elif sys.platform == 'win32': import ctypes SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW SetConsoleTitleW.argtypes = [ctypes.c_wchar_p] import os if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError def _term_clear(): os.system('cls')
null
176,928
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size def _term_clear(): pass
null
176,929
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size ignore_termtitle = True The provided code snippet includes necessary dependencies for implementing the `toggle_set_term_title` function. Write a Python function `def toggle_set_term_title(val)` to solve the following problem: Control whether set_term_title is active or not. set_term_title() allows writing to the console titlebar. In embedded widgets this can cause problems, so this call can be used to toggle it on or off as needed. The default state of the module is for the function to be disabled. Parameters ---------- val : bool If True, set_term_title() actually writes to the terminal (using the appropriate platform-specific module). If False, it is a no-op. Here is the function: def toggle_set_term_title(val): """Control whether set_term_title is active or not. set_term_title() allows writing to the console titlebar. In embedded widgets this can cause problems, so this call can be used to toggle it on or off as needed. The default state of the module is for the function to be disabled. Parameters ---------- val : bool If True, set_term_title() actually writes to the terminal (using the appropriate platform-specific module). If False, it is a no-op. """ global ignore_termtitle ignore_termtitle = not(val)
Control whether set_term_title is active or not. set_term_title() allows writing to the console titlebar. In embedded widgets this can cause problems, so this call can be used to toggle it on or off as needed. The default state of the module is for the function to be disabled. Parameters ---------- val : bool If True, set_term_title() actually writes to the terminal (using the appropriate platform-specific module). If False, it is a no-op.
176,930
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size _xterm_term_title_saved = False import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `_set_term_title_xterm` function. Write a Python function `def _set_term_title_xterm(title)` to solve the following problem: Change virtual terminal title in xterm-workalikes Here is the function: def _set_term_title_xterm(title): """ Change virtual terminal title in xterm-workalikes """ global _xterm_term_title_saved # Only save the title the first time we set, otherwise restore will only # go back one title (probably undoing a %cd title change). if not _xterm_term_title_saved: # save the current title to the xterm "stack" sys.stdout.write("\033[22;0t") _xterm_term_title_saved = True sys.stdout.write('\033]0;%s\007' % title)
Change virtual terminal title in xterm-workalikes
176,931
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size _xterm_term_title_saved = False import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) def _restore_term_title_xterm(): # Make sure the restore has at least one accompanying set. global _xterm_term_title_saved assert _xterm_term_title_saved sys.stdout.write('\033[23;0t') _xterm_term_title_saved = False
null
176,932
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size ignore_termtitle = True def _set_term_title(*args,**kw): """Dummy no-op.""" pass if os.name == 'posix': TERM = os.environ.get('TERM','') if TERM.startswith('xterm'): _set_term_title = _set_term_title_xterm _restore_term_title = _restore_term_title_xterm elif sys.platform == 'win32': import ctypes SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW SetConsoleTitleW.argtypes = [ctypes.c_wchar_p] def _set_term_title(title): """Set terminal title using ctypes to access the Win32 APIs.""" SetConsoleTitleW(title) The provided code snippet includes necessary dependencies for implementing the `set_term_title` function. Write a Python function `def set_term_title(title)` to solve the following problem: Set terminal title using the necessary platform-dependent calls. Here is the function: def set_term_title(title): """Set terminal title using the necessary platform-dependent calls.""" if ignore_termtitle: return _set_term_title(title)
Set terminal title using the necessary platform-dependent calls.
176,933
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size ignore_termtitle = True def _restore_term_title(): pass The provided code snippet includes necessary dependencies for implementing the `restore_term_title` function. Write a Python function `def restore_term_title()` to solve the following problem: Restore, if possible, terminal title to the original state Here is the function: def restore_term_title(): """Restore, if possible, terminal title to the original state""" if ignore_termtitle: return _restore_term_title()
Restore, if possible, terminal title to the original state
176,934
import os import sys import warnings from shutil import get_terminal_size as _get_terminal_size ignore_termtitle = True import warnings warnings.warn("Importing from numpy.testing.utils is deprecated " "since 1.15.0, import from numpy.testing instead.", DeprecationWarning, stacklevel=2) def freeze_term_title(): warnings.warn("This function is deprecated, use toggle_set_term_title()") global ignore_termtitle ignore_termtitle = True
null
176,935
import os import sys import ctypes import time from ctypes import c_int, POINTER from ctypes.wintypes import LPCWSTR, HLOCAL from subprocess import STDOUT, TimeoutExpired from threading import Thread from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split from . import py3compat from .encoding import DEFAULT_ENCODING class AvoidUNCPath(object): """A context manager to protect command execution from UNC paths. In the Win32 API, commands can't be invoked with the cwd being a UNC path. This context manager temporarily changes directory to the 'C:' drive on entering, and restores the original working directory on exit. The context manager returns the starting working directory *if* it made a change and None otherwise, so that users can apply the necessary adjustment to their system calls in the event of a change. Examples -------- :: cmd = 'dir' with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) os.system(cmd) """ def __enter__(self): self.path = os.getcwd() self.is_unc_path = self.path.startswith(r"\\") if self.is_unc_path: # change to c drive (as cmd.exe cannot handle UNC addresses) os.chdir("C:") return self.path else: # We return None to signal that there was no change in the working # directory return None def __exit__(self, exc_type, exc_value, traceback): if self.is_unc_path: os.chdir(self.path) def _system_body(p): """Callback for _system.""" enc = DEFAULT_ENCODING def stdout_read(): for line in read_no_interrupt(p.stdout).splitlines(): line = line.decode(enc, 'replace') print(line, file=sys.stdout) def stderr_read(): for line in read_no_interrupt(p.stderr).splitlines(): line = line.decode(enc, 'replace') print(line, file=sys.stderr) Thread(target=stdout_read).start() Thread(target=stderr_read).start() # Wait to finish for returncode. Unfortunately, Python has a bug where # wait() isn't interruptible (https://bugs.python.org/issue28168) so poll in # a loop instead of just doing `return p.wait()`. while True: result = p.poll() if result is None: time.sleep(0.01) else: return result def process_handler(cmd, callback, stderr=subprocess.PIPE): """Open a command in a shell subprocess and execute a callback. This function provides common scaffolding for creating subprocess.Popen() calls. It creates a Popen object and then calls the callback with it. Parameters ---------- cmd : str or list A command to be executed by the system, using :class:`subprocess.Popen`. If a string is passed, it will be run in the system shell. If a list is passed, it will be used directly as arguments. callback : callable A one-argument function that will be called with the Popen object. stderr : file descriptor number, optional By default this is set to ``subprocess.PIPE``, but you can also pass the value ``subprocess.STDOUT`` to force the subprocess' stderr to go into the same file descriptor as its stdout. This is useful to read stdout and stderr combined in the order they are generated. Returns ------- The return value of the provided callback is returned. """ sys.stdout.flush() sys.stderr.flush() # On win32, close_fds can't be true when using pipes for stdin/out/err close_fds = sys.platform != 'win32' # Determine if cmd should be run with system shell. shell = isinstance(cmd, str) # On POSIX systems run shell commands with user-preferred shell. executable = None if shell and os.name == 'posix' and 'SHELL' in os.environ: executable = os.environ['SHELL'] p = subprocess.Popen(cmd, shell=shell, executable=executable, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=close_fds) try: out = callback(p) except KeyboardInterrupt: print('^C') sys.stdout.flush() sys.stderr.flush() out = None finally: # Make really sure that we don't leave processes behind, in case the # call above raises an exception # We start by assuming the subprocess finished (to avoid NameErrors # later depending on the path taken) if p.returncode is None: try: p.terminate() p.poll() except OSError: pass # One last try on our way out if p.returncode is None: try: p.kill() except OSError: pass return out The provided code snippet includes necessary dependencies for implementing the `system` function. Write a Python function `def system(cmd)` to solve the following problem: Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- int : child process' exit code. Here is the function: def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- int : child process' exit code. """ # The controller provides interactivity with both # stdin and stdout #import _process_win32_controller #_process_win32_controller.system(cmd) with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) return process_handler(cmd, _system_body)
Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- int : child process' exit code.
176,936
import os import sys import ctypes import time from ctypes import c_int, POINTER from ctypes.wintypes import LPCWSTR, HLOCAL from subprocess import STDOUT, TimeoutExpired from threading import Thread from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split from . import py3compat from .encoding import DEFAULT_ENCODING class AvoidUNCPath(object): """A context manager to protect command execution from UNC paths. In the Win32 API, commands can't be invoked with the cwd being a UNC path. This context manager temporarily changes directory to the 'C:' drive on entering, and restores the original working directory on exit. The context manager returns the starting working directory *if* it made a change and None otherwise, so that users can apply the necessary adjustment to their system calls in the event of a change. Examples -------- :: cmd = 'dir' with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) os.system(cmd) """ def __enter__(self): self.path = os.getcwd() self.is_unc_path = self.path.startswith(r"\\") if self.is_unc_path: # change to c drive (as cmd.exe cannot handle UNC addresses) os.chdir("C:") return self.path else: # We return None to signal that there was no change in the working # directory return None def __exit__(self, exc_type, exc_value, traceback): if self.is_unc_path: os.chdir(self.path) STDOUT: int def process_handler(cmd, callback, stderr=subprocess.PIPE): """Open a command in a shell subprocess and execute a callback. This function provides common scaffolding for creating subprocess.Popen() calls. It creates a Popen object and then calls the callback with it. Parameters ---------- cmd : str or list A command to be executed by the system, using :class:`subprocess.Popen`. If a string is passed, it will be run in the system shell. If a list is passed, it will be used directly as arguments. callback : callable A one-argument function that will be called with the Popen object. stderr : file descriptor number, optional By default this is set to ``subprocess.PIPE``, but you can also pass the value ``subprocess.STDOUT`` to force the subprocess' stderr to go into the same file descriptor as its stdout. This is useful to read stdout and stderr combined in the order they are generated. Returns ------- The return value of the provided callback is returned. """ sys.stdout.flush() sys.stderr.flush() # On win32, close_fds can't be true when using pipes for stdin/out/err close_fds = sys.platform != 'win32' # Determine if cmd should be run with system shell. shell = isinstance(cmd, str) # On POSIX systems run shell commands with user-preferred shell. executable = None if shell and os.name == 'posix' and 'SHELL' in os.environ: executable = os.environ['SHELL'] p = subprocess.Popen(cmd, shell=shell, executable=executable, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=close_fds) try: out = callback(p) except KeyboardInterrupt: print('^C') sys.stdout.flush() sys.stderr.flush() out = None finally: # Make really sure that we don't leave processes behind, in case the # call above raises an exception # We start by assuming the subprocess finished (to avoid NameErrors # later depending on the path taken) if p.returncode is None: try: p.terminate() p.poll() except OSError: pass # One last try on our way out if p.returncode is None: try: p.kill() except OSError: pass return out The provided code snippet includes necessary dependencies for implementing the `getoutput` function. Write a Python function `def getoutput(cmd)` to solve the following problem: Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str Here is the function: def getoutput(cmd): """Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str """ with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT) if out is None: out = b'' return py3compat.decode(out)
Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- stdout : str
176,937
import os import sys import ctypes import time from ctypes import c_int, POINTER from ctypes.wintypes import LPCWSTR, HLOCAL from subprocess import STDOUT, TimeoutExpired from threading import Thread from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split from . import py3compat from .encoding import DEFAULT_ENCODING try: CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPCWSTR) LocalFree = ctypes.windll.kernel32.LocalFree LocalFree.res_type = HLOCAL LocalFree.arg_types = [HLOCAL] except AttributeError: arg_split = py_arg_split The provided code snippet includes necessary dependencies for implementing the `arg_split` function. Write a Python function `def arg_split(commandline, posix=False, strict=True)` to solve the following problem: Split a command line's arguments in a shell-like manner. This is a special version for windows that use a ctypes call to CommandLineToArgvW to do the argv splitting. The posix parameter is ignored. If strict=False, process_common.arg_split(...strict=False) is used instead. Here is the function: def arg_split(commandline, posix=False, strict=True): """Split a command line's arguments in a shell-like manner. This is a special version for windows that use a ctypes call to CommandLineToArgvW to do the argv splitting. The posix parameter is ignored. If strict=False, process_common.arg_split(...strict=False) is used instead. """ #CommandLineToArgvW returns path to executable if called with empty string. if commandline.strip() == "": return [] if not strict: # not really a cl-arg, fallback on _process_common return py_arg_split(commandline, posix=posix, strict=strict) argvn = c_int() result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn)) result_array_type = LPCWSTR * argvn.value result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))] retval = LocalFree(result_pointer) return result
Split a command line's arguments in a shell-like manner. This is a special version for windows that use a ctypes call to CommandLineToArgvW to do the argv splitting. The posix parameter is ignored. If strict=False, process_common.arg_split(...strict=False) is used instead.
176,938
import os import sys import ctypes import time from ctypes import c_int, POINTER from ctypes.wintypes import LPCWSTR, HLOCAL from subprocess import STDOUT, TimeoutExpired from threading import Thread from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split from . import py3compat from .encoding import DEFAULT_ENCODING def check_pid(pid): # OpenProcess returns 0 if no such process (of ours) exists # positive int otherwise return bool(ctypes.windll.kernel32.OpenProcess(1,0,pid))
null
176,939
The provided code snippet includes necessary dependencies for implementing the `uniq_stable` function. Write a Python function `def uniq_stable(elems)` to solve the following problem: uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which they first appear. Note: All elements in the input must be hashable for this routine to work, as it internally uses a set for efficiency reasons. Here is the function: def uniq_stable(elems): """uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which they first appear. Note: All elements in the input must be hashable for this routine to work, as it internally uses a set for efficiency reasons. """ seen = set() return [x for x in elems if x not in seen and not seen.add(x)]
uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which they first appear. Note: All elements in the input must be hashable for this routine to work, as it internally uses a set for efficiency reasons.
176,940
from typing import Sequence from IPython.utils.docs import GENERATING_DOCUMENTATION The provided code snippet includes necessary dependencies for implementing the `undoc` function. Write a Python function `def undoc(func)` to solve the following problem: Mark a function or class as undocumented. This is found by inspecting the AST, so for now it must be used directly as @undoc, not as e.g. @decorators.undoc Here is the function: def undoc(func): """Mark a function or class as undocumented. This is found by inspecting the AST, so for now it must be used directly as @undoc, not as e.g. @decorators.undoc """ return func
Mark a function or class as undocumented. This is found by inspecting the AST, so for now it must be used directly as @undoc, not as e.g. @decorators.undoc
176,941
from typing import Sequence from IPython.utils.docs import GENERATING_DOCUMENTATION class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): def __getitem__(self, i: int) -> _T_co: ... def __getitem__(self, s: slice) -> Sequence[_T_co]: ... # Mixin methods def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ... def count(self, value: Any) -> int: ... def __contains__(self, x: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... GENERATING_DOCUMENTATION = os.environ.get("IN_SPHINX_RUN", None) == "True" The provided code snippet includes necessary dependencies for implementing the `sphinx_options` function. Write a Python function `def sphinx_options( show_inheritance: bool = True, show_inherited_members: bool = False, exclude_inherited_from: Sequence[str] = tuple(), )` to solve the following problem: Set sphinx options Here is the function: def sphinx_options( show_inheritance: bool = True, show_inherited_members: bool = False, exclude_inherited_from: Sequence[str] = tuple(), ): """Set sphinx options""" def wrapper(func): if not GENERATING_DOCUMENTATION: return func func._sphinx_options = dict( show_inheritance=show_inheritance, show_inherited_members=show_inherited_members, exclude_inherited_from=exclude_inherited_from, ) return func return wrapper
Set sphinx options
176,942
import re import types from IPython.utils.dir2 import dir2 typestr2type, type2typestr = create_typestr2type_dicts() The provided code snippet includes necessary dependencies for implementing the `create_typestr2type_dicts` function. Write a Python function `def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"])` to solve the following problem: Return dictionaries mapping lower case typename (e.g. 'tuple') to type objects from the types package, and vice versa. Here is the function: def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]): """Return dictionaries mapping lower case typename (e.g. 'tuple') to type objects from the types package, and vice versa.""" typenamelist = [tname for tname in dir(types) if tname.endswith("Type")] typestr2type, type2typestr = {}, {} for tname in typenamelist: name = tname[:-4].lower() # Cut 'Type' off the end of the name obj = getattr(types, tname) typestr2type[name] = obj if name not in dont_include_in_type2typestr: type2typestr[obj] = name return typestr2type, type2typestr
Return dictionaries mapping lower case typename (e.g. 'tuple') to type objects from the types package, and vice versa.
176,943
import re import types from IPython.utils.dir2 import dir2 def dict_dir(obj): """Produce a dictionary of an object's attributes. Builds on dir2 by checking that a getattr() call actually succeeds.""" ns = {} for key in dir2(obj): # This seemingly unnecessary try/except is actually needed # because there is code out there with metaclasses that # create 'write only' attributes, where a getattr() call # will fail even if the attribute appears listed in the # object's dictionary. Properties can actually do the same # thing. In particular, Traits use this pattern try: ns[key] = getattr(obj, key) except AttributeError: pass return ns def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True, show_all=True): """Filter a namespace dictionary by name pattern and item type.""" pattern = name_pattern.replace("*",".*").replace("?",".") if ignore_case: reg = re.compile(pattern+"$", re.I) else: reg = re.compile(pattern+"$") # Check each one matches regex; shouldn't be hidden; of correct type. return dict((key,obj) for key, obj in ns.items() if reg.match(key) \ and show_hidden(key, show_all) \ and is_type(obj, type_pattern) ) The provided code snippet includes necessary dependencies for implementing the `list_namespace` function. Write a Python function `def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False)` to solve the following problem: Return dictionary of all objects in a namespace dictionary that match type_pattern and filter. Here is the function: def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): """Return dictionary of all objects in a namespace dictionary that match type_pattern and filter.""" pattern_list=filter.split(".") if len(pattern_list) == 1: return filter_ns(namespace, name_pattern=pattern_list[0], type_pattern=type_pattern, ignore_case=ignore_case, show_all=show_all) else: # This is where we can change if all objects should be searched or # only modules. Just change the type_pattern to module to search only # modules filtered = filter_ns(namespace, name_pattern=pattern_list[0], type_pattern="all", ignore_case=ignore_case, show_all=show_all) results = {} for name, obj in filtered.items(): ns = list_namespace(dict_dir(obj), type_pattern, ".".join(pattern_list[1:]), ignore_case=ignore_case, show_all=show_all) for inner_name, inner_obj in ns.items(): results["%s.%s"%(name,inner_name)] = inner_obj return results
Return dictionary of all objects in a namespace dictionary that match type_pattern and filter.
176,944
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `list_strings` function. Write a Python function `def list_strings(arg)` to solve the following problem: Always return a list of strings, given a string or list of strings as input. Examples -------- :: In [7]: list_strings('A single string') Out[7]: ['A single string'] In [8]: list_strings(['A single string in a list']) Out[8]: ['A single string in a list'] In [9]: list_strings(['A','list','of','strings']) Out[9]: ['A', 'list', 'of', 'strings'] Here is the function: def list_strings(arg): """Always return a list of strings, given a string or list of strings as input. Examples -------- :: In [7]: list_strings('A single string') Out[7]: ['A single string'] In [8]: list_strings(['A single string in a list']) Out[8]: ['A single string in a list'] In [9]: list_strings(['A','list','of','strings']) Out[9]: ['A', 'list', 'of', 'strings'] """ if isinstance(arg, str): return [arg] else: return arg
Always return a list of strings, given a string or list of strings as input. Examples -------- :: In [7]: list_strings('A single string') Out[7]: ['A single string'] In [8]: list_strings(['A single string in a list']) Out[8]: ['A single string in a list'] In [9]: list_strings(['A','list','of','strings']) Out[9]: ['A', 'list', 'of', 'strings']
176,945
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `marquee` function. Write a Python function `def marquee(txt='',width=78,mark='*')` to solve the following problem: Return the input string centered in a 'marquee'. Examples -------- :: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test ' Here is the function: def marquee(txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'. Examples -------- :: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test ' """ if not txt: return (mark*width)[:width] nmark = (width-len(txt)-2)//len(mark)//2 if nmark < 0: nmark =0 marks = mark*nmark return '%s %s %s' % (marks,txt,marks)
Return the input string centered in a 'marquee'. Examples -------- :: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test '
176,946
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path ini_spaces_re = re.compile(r'^(\s+)') The provided code snippet includes necessary dependencies for implementing the `num_ini_spaces` function. Write a Python function `def num_ini_spaces(strng)` to solve the following problem: Return the number of initial spaces in a string Here is the function: def num_ini_spaces(strng): """Return the number of initial spaces in a string""" ini_spaces = ini_spaces_re.match(strng) if ini_spaces: return ini_spaces.end() else: return 0
Return the number of initial spaces in a string
176,947
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `format_screen` function. Write a Python function `def format_screen(strng)` to solve the following problem: Format a string for screen printing. This removes some latex-type format codes. Here is the function: def format_screen(strng): """Format a string for screen printing. This removes some latex-type format codes.""" # Paragraph continue par_re = re.compile(r'\\$',re.MULTILINE) strng = par_re.sub('',strng) return strng
Format a string for screen printing. This removes some latex-type format codes.
176,948
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. """ if text.startswith('\n'): # text starts with blank line, don't ignore the first line return textwrap.dedent(text) # split first line splits = text.split('\n',1) if len(splits) == 1: # only one line return textwrap.dedent(text) first, rest = splits # dedent everything but the first line rest = textwrap.dedent(rest) return '\n'.join([first, rest]) The provided code snippet includes necessary dependencies for implementing the `wrap_paragraphs` function. Write a Python function `def wrap_paragraphs(text, ncols=80)` to solve the following problem: Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. Here is the function: def wrap_paragraphs(text, ncols=80): """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. """ paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) text = dedent(text).strip() paragraphs = paragraph_re.split(text)[::2] # every other entry is space out_ps = [] indent_re = re.compile(r'\n\s+', re.MULTILINE) for p in paragraphs: # presume indentation that survives dedent is meaningful formatting, # so don't fill unless text is flush. if indent_re.search(p) is None: # wrap paragraph p = textwrap.fill(p, ncols) out_ps.append(p) return out_ps
Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns.
176,949
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `strip_email_quotes` function. Write a Python function `def strip_email_quotes(text)` to solve the following problem: Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: In [2]: strip_email_quotes('> > text') Out[2]: 'text' In [3]: strip_email_quotes('> > text\\n> > more') Out[3]: 'text\\nmore' Note how only the common prefix that appears in all lines is stripped:: In [4]: strip_email_quotes('> > text\\n> > more\\n> more...') Out[4]: '> text\\n> more\\nmore...' So if any line has no quote marks ('>'), then none are stripped from any of them :: In [5]: strip_email_quotes('> > text\\n> > more\\nlast different') Out[5]: '> > text\\n> > more\\nlast different' Here is the function: def strip_email_quotes(text): """Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: In [2]: strip_email_quotes('> > text') Out[2]: 'text' In [3]: strip_email_quotes('> > text\\n> > more') Out[3]: 'text\\nmore' Note how only the common prefix that appears in all lines is stripped:: In [4]: strip_email_quotes('> > text\\n> > more\\n> more...') Out[4]: '> text\\n> more\\nmore...' So if any line has no quote marks ('>'), then none are stripped from any of them :: In [5]: strip_email_quotes('> > text\\n> > more\\nlast different') Out[5]: '> > text\\n> > more\\nlast different' """ lines = text.splitlines() strip_len = 0 for characters in zip(*lines): # Check if all characters in this position are the same if len(set(characters)) > 1: break prefix_char = characters[0] if prefix_char in string.whitespace or prefix_char == ">": strip_len += 1 else: break text = "\n".join([ln[strip_len:] for ln in lines]) return text
Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: In [2]: strip_email_quotes('> > text') Out[2]: 'text' In [3]: strip_email_quotes('> > text\\n> > more') Out[3]: 'text\\nmore' Note how only the common prefix that appears in all lines is stripped:: In [4]: strip_email_quotes('> > text\\n> > more\\n> more...') Out[4]: '> text\\n> more\\nmore...' So if any line has no quote marks ('>'), then none are stripped from any of them :: In [5]: strip_email_quotes('> > text\\n> > more\\nlast different') Out[5]: '> > text\\n> > more\\nlast different'
176,950
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `strip_ansi` function. Write a Python function `def strip_ansi(source)` to solve the following problem: Remove ansi escape codes from text. Parameters ---------- source : str Source to remove the ansi from Here is the function: def strip_ansi(source): """ Remove ansi escape codes from text. Parameters ---------- source : str Source to remove the ansi from """ return re.sub(r'\033\[(\d|;)+?m', '', source)
Remove ansi escape codes from text. Parameters ---------- source : str Source to remove the ansi from
176,951
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) : """Returns a nested list, and info to columnize items Parameters ---------- items list of strings to columize row_first : (default False) Whether to compute columns for a row-first matrix instead of column-first (default). empty : (default None) default value to fill list if needed separator_size : int (default=2) How much characters will be used as a separation between each columns. displaywidth : int (default=80) The width of the area onto which the columns should enter Returns ------- strings_matrix nested list of string, the outer most list contains as many list as rows, the innermost lists have each as many element as columns. If the total number of elements in `items` does not equal the product of rows*columns, the last element of some lists are filled with `None`. dict_info some info to make columnize easier: num_columns number of columns max_rows maximum number of rows (final number may be less) column_widths list of with of each columns optimal_separator_width best separator width between columns Examples -------- :: In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l'] In [2]: list, info = compute_item_matrix(l, displaywidth=12) In [3]: list Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]] In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5} In [5]: all((info[k] == ideal[k] for k in ideal.keys())) Out[5]: True """ info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs) nrow, ncol = info['max_rows'], info['num_columns'] if row_first: return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info) else: return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info) The provided code snippet includes necessary dependencies for implementing the `columnize` function. Write a Python function `def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=False)` to solve the following problem: Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. row_first : (default False) Whether to compute columns for a row-first matrix instead of column-first (default). separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string. Here is the function: def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=False): """Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. row_first : (default False) Whether to compute columns for a row-first matrix instead of column-first (default). separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string. """ if not items: return '\n' matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth) if spread: separator = separator.ljust(int(info['optimal_separator_width'])) fmatrix = [filter(None, x) for x in matrix] sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])]) return '\n'.join(map(sjoin, fmatrix))+'\n'
Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. row_first : (default False) Whether to compute columns for a row-first matrix instead of column-first (default). separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string.
176,952
import os import re import string import sys import textwrap from string import Formatter from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `get_text_list` function. Write a Python function `def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with="")` to solve the following problem: Return a string with a natural enumeration of items >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c and d' >>> get_text_list(['a', 'b', 'c'], ' or ') 'a, b or c' >>> get_text_list(['a', 'b', 'c'], ', ') 'a, b, c' >>> get_text_list(['a', 'b'], ' or ') 'a or b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' >>> get_text_list(['a', 'b'], wrap_item_with="`") '`a` and `b`' >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ") 'a + b + c = d' Here is the function: def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""): """ Return a string with a natural enumeration of items >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c and d' >>> get_text_list(['a', 'b', 'c'], ' or ') 'a, b or c' >>> get_text_list(['a', 'b', 'c'], ', ') 'a, b, c' >>> get_text_list(['a', 'b'], ' or ') 'a or b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' >>> get_text_list(['a', 'b'], wrap_item_with="`") '`a` and `b`' >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ") 'a + b + c = d' """ if len(list_) == 0: return '' if wrap_item_with: list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for item in list_] if len(list_) == 1: return list_[0] return '%s%s%s' % ( sep.join(i for i in list_[:-1]), last_sep, list_[-1])
Return a string with a natural enumeration of items >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c and d' >>> get_text_list(['a', 'b', 'c'], ' or ') 'a, b or c' >>> get_text_list(['a', 'b', 'c'], ', ') 'a, b, c' >>> get_text_list(['a', 'b'], ' or ') 'a or b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' >>> get_text_list(['a', 'b'], wrap_item_with="`") '`a` and `b`' >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ") 'a + b + c = d'
176,953
import platform import builtins as builtin_mod from .encoding import DEFAULT_ENCODING The provided code snippet includes necessary dependencies for implementing the `safe_unicode` function. Write a Python function `def safe_unicode(e)` to solve the following problem: unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. Here is the function: def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return str(e) except UnicodeError: pass try: return repr(e) except UnicodeError: pass return "Unrecoverably corrupt evalue"
unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on.
176,954
import platform import builtins as builtin_mod from .encoding import DEFAULT_ENCODING def execfile(fname, glob, loc=None, compiler=None): loc = loc if (loc is not None) else glob with open(fname, "rb") as f: compiler = compiler or compile exec(compiler(f.read(), fname, "exec"), glob, loc)
null
176,955
import platform import builtins as builtin_mod from .encoding import DEFAULT_ENCODING def no_code(x, encoding=None): return x
null
176,957
import io from io import TextIOWrapper, BytesIO from pathlib import Path import re from tokenize import open, detect_encoding def strip_encoding_cookie(filelike): """Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines. """ it = iter(filelike) try: first = next(it) if not cookie_comment_re.match(first): yield first second = next(it) if not cookie_comment_re.match(second): yield second except StopIteration: return for line in it: yield line class Path(PurePath): def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ... def __enter__(self: _P) -> _P: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> Optional[bool]: ... def cwd(cls: Type[_P]) -> _P: ... def stat(self) -> os.stat_result: ... def chmod(self, mode: int) -> None: ... def exists(self) -> bool: ... def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def group(self) -> str: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... if sys.version_info >= (3, 7): def is_mount(self) -> bool: ... def is_symlink(self) -> bool: ... def is_socket(self) -> bool: ... def is_fifo(self) -> bool: ... def is_block_device(self) -> bool: ... def is_char_device(self) -> bool: ... def iterdir(self: _P) -> Generator[_P, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> os.stat_result: ... def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... # Adapted from builtins.open # Text mode: always returns a TextIOWrapper def open( self, mode: OpenTextMode = ..., buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> TextIOWrapper: ... # Unbuffered binary mode: returns a FileIO def open( self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... ) -> FileIO: ... # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter def open( self, mode: OpenBinaryModeUpdating, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedRandom: ... def open( self, mode: OpenBinaryModeWriting, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedWriter: ... def open( self, mode: OpenBinaryModeReading, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedReader: ... # Buffering cannot be determined: fall back to BinaryIO def open( self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... ) -> BinaryIO: ... # Fallback if mode is not specified def open( self, mode: str, buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> IO[Any]: ... def owner(self) -> str: ... if sys.version_info >= (3, 9): def readlink(self: _P) -> _P: ... if sys.version_info >= (3, 8): def rename(self: _P, target: Union[str, PurePath]) -> _P: ... def replace(self: _P, target: Union[str, PurePath]) -> _P: ... else: def rename(self, target: Union[str, PurePath]) -> None: ... def replace(self, target: Union[str, PurePath]) -> None: ... def resolve(self: _P, strict: bool = ...) -> _P: ... def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ... def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... if sys.version_info >= (3, 8): def unlink(self, missing_ok: bool = ...) -> None: ... else: def unlink(self) -> None: ... def home(cls: Type[_P]) -> _P: ... def absolute(self: _P) -> _P: ... def expanduser(self: _P) -> _P: ... def read_bytes(self) -> bytes: ... def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... def write_bytes(self, data: bytes) -> int: ... def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ... if sys.version_info >= (3, 8): def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ... def open(filename: Union[str, bytes, int, PathLike[Any]]) -> TextIO: ... The provided code snippet includes necessary dependencies for implementing the `read_py_file` function. Write a Python function `def read_py_file(filename, skip_encoding_cookie=True)` to solve the following problem: Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output. Returns ------- A unicode string containing the contents of the file. Here is the function: def read_py_file(filename, skip_encoding_cookie=True): """Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output. Returns ------- A unicode string containing the contents of the file. """ filepath = Path(filename) with open(filepath) as f: # the open function defined in this module. if skip_encoding_cookie: return "".join(strip_encoding_cookie(f)) else: return f.read()
Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output. Returns ------- A unicode string containing the contents of the file.
176,958
import io from io import TextIOWrapper, BytesIO from pathlib import Path import re from tokenize import open, detect_encoding def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True): """Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a string containing the source code. """ if isinstance(txt, str): return txt if isinstance(txt, bytes): buffer = BytesIO(txt) else: buffer = txt try: encoding, _ = detect_encoding(buffer.readline) except SyntaxError: encoding = "ascii" buffer.seek(0) with TextIOWrapper(buffer, encoding, errors=errors, line_buffering=True) as text: text.mode = 'r' if skip_encoding_cookie: return u"".join(strip_encoding_cookie(text)) else: return text.read() class BytesIO(BufferedIOBase, BinaryIO): def __init__(self, initial_bytes: bytes = ...) -> None: ... # BytesIO does not contain a "name" field. This workaround is necessary # to allow BytesIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def __enter__(self: _T) -> _T: ... def getvalue(self) -> bytes: ... def getbuffer(self) -> memoryview: ... if sys.version_info >= (3, 7): def read1(self, __size: Optional[int] = ...) -> bytes: ... else: def read1(self, __size: Optional[int]) -> bytes: ... # type: ignore The provided code snippet includes necessary dependencies for implementing the `read_py_url` function. Write a Python function `def read_py_url(url, errors='replace', skip_encoding_cookie=True)` to solve the following problem: Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output. Returns ------- A unicode string containing the contents of the file. Here is the function: def read_py_url(url, errors='replace', skip_encoding_cookie=True): """Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output. Returns ------- A unicode string containing the contents of the file. """ # Deferred import for faster start from urllib.request import urlopen response = urlopen(url) buffer = io.BytesIO(response.read()) return source_to_unicode(buffer, errors, skip_encoding_cookie)
Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output. Returns ------- A unicode string containing the contents of the file.
176,959
import os import shutil import sys if sys.platform == 'win32': from ._process_win32 import system, getoutput, arg_split, check_pid elif sys.platform == 'cli': from ._process_cli import system, getoutput, arg_split, check_pid else: from ._process_posix import system, getoutput, arg_split, check_pid from ._process_common import getoutputerror, get_output_error_code, process_handler import os import sys if os.name == 'nt': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance=None, inum=-1, format=None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link) # My older explanation for this was that the "AddCounter" process # forced the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter)) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) elif sys.platform[:5] == 'linux': def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'): """ Return virtual memory size in bytes of the running python. """ try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[22]) except Exception: return else: def memusage(): """ Return memory usage of running python. [Not implemented] """ raise NotImplementedError if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `abbrev_cwd` function. Write a Python function `def abbrev_cwd()` to solve the following problem: Return abbreviated version of cwd, e.g. d:mydir Here is the function: def abbrev_cwd(): """ Return abbreviated version of cwd, e.g. d:mydir """ cwd = os.getcwd().replace('\\','/') drivepart = '' tail = cwd if sys.platform == 'win32': if len(cwd) < 4: return cwd drivepart,tail = os.path.splitdrive(cwd) parts = tail.split('/') if len(parts) > 2: tail = '/'.join(parts[-2:]) return (drivepart + ( cwd == '/' and '/' or tail))
Return abbreviated version of cwd, e.g. d:mydir
176,960
import atexit import os import sys import tempfile from pathlib import Path from warnings import warn from IPython.utils.decorators import undoc from .capture import CapturedIO, capture_output The provided code snippet includes necessary dependencies for implementing the `ask_yes_no` function. Write a Python function `def ask_yes_no(prompt, default=None, interrupt=None)` to solve the following problem: Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. If interrupt is given (one of 'y','n'), it is used if the user presses Ctrl-C. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops. Valid answers are: y/yes/n/no (match is not case sensitive). Here is the function: def ask_yes_no(prompt, default=None, interrupt=None): """Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. If interrupt is given (one of 'y','n'), it is used if the user presses Ctrl-C. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops. Valid answers are: y/yes/n/no (match is not case sensitive).""" answers = {'y':True,'n':False,'yes':True,'no':False} ans = None while ans not in answers.keys(): try: ans = input(prompt+' ').lower() if not ans: # response was an empty string ans = default except KeyboardInterrupt: if interrupt: ans = interrupt print("\r") except EOFError: if default in answers.keys(): ans = default print() else: raise return answers[ans]
Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. If interrupt is given (one of 'y','n'), it is used if the user presses Ctrl-C. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an exception is raised to prevent infinite loops. Valid answers are: y/yes/n/no (match is not case sensitive).
176,961
import atexit import os import sys import tempfile from pathlib import Path from warnings import warn from IPython.utils.decorators import undoc from .capture import CapturedIO, capture_output class Path(PurePath): def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ... def __enter__(self: _P) -> _P: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> Optional[bool]: ... def cwd(cls: Type[_P]) -> _P: ... def stat(self) -> os.stat_result: ... def chmod(self, mode: int) -> None: ... def exists(self) -> bool: ... def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def group(self) -> str: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... if sys.version_info >= (3, 7): def is_mount(self) -> bool: ... def is_symlink(self) -> bool: ... def is_socket(self) -> bool: ... def is_fifo(self) -> bool: ... def is_block_device(self) -> bool: ... def is_char_device(self) -> bool: ... def iterdir(self: _P) -> Generator[_P, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> os.stat_result: ... def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... # Adapted from builtins.open # Text mode: always returns a TextIOWrapper def open( self, mode: OpenTextMode = ..., buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> TextIOWrapper: ... # Unbuffered binary mode: returns a FileIO def open( self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... ) -> FileIO: ... # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter def open( self, mode: OpenBinaryModeUpdating, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedRandom: ... def open( self, mode: OpenBinaryModeWriting, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedWriter: ... def open( self, mode: OpenBinaryModeReading, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedReader: ... # Buffering cannot be determined: fall back to BinaryIO def open( self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... ) -> BinaryIO: ... # Fallback if mode is not specified def open( self, mode: str, buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> IO[Any]: ... def owner(self) -> str: ... if sys.version_info >= (3, 9): def readlink(self: _P) -> _P: ... if sys.version_info >= (3, 8): def rename(self: _P, target: Union[str, PurePath]) -> _P: ... def replace(self: _P, target: Union[str, PurePath]) -> _P: ... else: def rename(self, target: Union[str, PurePath]) -> None: ... def replace(self, target: Union[str, PurePath]) -> None: ... def resolve(self: _P, strict: bool = ...) -> _P: ... def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ... def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... if sys.version_info >= (3, 8): def unlink(self, missing_ok: bool = ...) -> None: ... else: def unlink(self) -> None: ... def home(cls: Type[_P]) -> _P: ... def absolute(self: _P) -> _P: ... def expanduser(self: _P) -> _P: ... def read_bytes(self) -> bytes: ... def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... def write_bytes(self, data: bytes) -> int: ... def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ... if sys.version_info >= (3, 8): def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ... The provided code snippet includes necessary dependencies for implementing the `temp_pyfile` function. Write a Python function `def temp_pyfile(src, ext='.py')` to solve the following problem: Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. Returns ------- (filename, open filehandle) It is the caller's responsibility to close the open file and unlink it. Here is the function: def temp_pyfile(src, ext='.py'): """Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. Returns ------- (filename, open filehandle) It is the caller's responsibility to close the open file and unlink it. """ fname = tempfile.mkstemp(ext)[1] with open(Path(fname), "w", encoding="utf-8") as f: f.write(src) f.flush() return fname
Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. Returns ------- (filename, open filehandle) It is the caller's responsibility to close the open file and unlink it.
176,962
import atexit import os import sys import tempfile from pathlib import Path from warnings import warn from IPython.utils.decorators import undoc from .capture import CapturedIO, capture_output import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `raw_print` function. Write a Python function `def raw_print(*args, **kw)` to solve the following problem: DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print(). Here is the function: def raw_print(*args, **kw): """DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print().""" warn("IPython.utils.io.raw_print has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2) print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'), file=sys.__stdout__) sys.__stdout__.flush()
DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print().
176,963
import atexit import os import sys import tempfile from pathlib import Path from warnings import warn from IPython.utils.decorators import undoc from .capture import CapturedIO, capture_output import sys if sys.platform[:5] == 'linux': def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: with open(_proc_pid_stat, 'r') as f: l = f.readline().split(' ') return int(l[13]) except Exception: return int(100*(time.time()-_load_time[0])) else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies elapsed. Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) The provided code snippet includes necessary dependencies for implementing the `raw_print_err` function. Write a Python function `def raw_print_err(*args, **kw)` to solve the following problem: DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print(). Here is the function: def raw_print_err(*args, **kw): """DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print().""" warn("IPython.utils.io.raw_print_err has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2) print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'), file=sys.__stderr__) sys.__stderr__.flush()
DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print().
176,964
import clr import System import os from ._process_common import arg_split The provided code snippet includes necessary dependencies for implementing the `system` function. Write a Python function `def system(cmd)` to solve the following problem: system(cmd) should work in a cli environment on Mac OSX, Linux, and Windows Here is the function: def system(cmd): """ system(cmd) should work in a cli environment on Mac OSX, Linux, and Windows """ psi = System.Diagnostics.ProcessStartInfo(cmd) psi.RedirectStandardOutput = True psi.RedirectStandardError = True psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal psi.UseShellExecute = False # Start up process: reg = System.Diagnostics.Process.Start(psi)
system(cmd) should work in a cli environment on Mac OSX, Linux, and Windows
176,965
import clr import System import os from ._process_common import arg_split The provided code snippet includes necessary dependencies for implementing the `getoutput` function. Write a Python function `def getoutput(cmd)` to solve the following problem: getoutput(cmd) should work in a cli environment on Mac OSX, Linux, and Windows Here is the function: def getoutput(cmd): """ getoutput(cmd) should work in a cli environment on Mac OSX, Linux, and Windows """ psi = System.Diagnostics.ProcessStartInfo(cmd) psi.RedirectStandardOutput = True psi.RedirectStandardError = True psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal psi.UseShellExecute = False # Start up process: reg = System.Diagnostics.Process.Start(psi) myOutput = reg.StandardOutput output = myOutput.ReadToEnd() myError = reg.StandardError error = myError.ReadToEnd() return output
getoutput(cmd) should work in a cli environment on Mac OSX, Linux, and Windows
176,966
import clr import System import os from ._process_common import arg_split The provided code snippet includes necessary dependencies for implementing the `check_pid` function. Write a Python function `def check_pid(pid)` to solve the following problem: Check if a process with the given PID (pid) exists Here is the function: def check_pid(pid): """ Check if a process with the given PID (pid) exists """ try: System.Diagnostics.Process.GetProcessById(pid) # process with given pid is running return True except System.InvalidOperationException: # process wasn't started by this object (but is running) return True except System.ArgumentException: # process with given pid isn't running return False
Check if a process with the given PID (pid) exists
176,967
import ast import dis from types import CodeType, FrameType from typing import Any, Callable, Iterator, Optional, Sequence, Set, Tuple, Type, Union, cast from .executing import EnhancedAST, NotOneValueFound, Source, only, function_node_types, assert_ from ._exceptions import KnownIssue, VerifierFailure from functools import lru_cache def parents(node: EnhancedAST) -> Iterator[EnhancedAST]: class Iterator(Iterable[_T_co], Protocol[_T_co]): def __next__(self) -> _T_co: def __iter__(self) -> Iterator[_T_co]: class EnhancedAST(ast.AST): # type: EnhancedAST def node_and_parents(node: EnhancedAST) -> Iterator[EnhancedAST]: yield node yield from parents(node)
null
176,968
import ast import dis from types import CodeType, FrameType from typing import Any, Callable, Iterator, Optional, Sequence, Set, Tuple, Type, Union, cast from .executing import EnhancedAST, NotOneValueFound, Source, only, function_node_types, assert_ from ._exceptions import KnownIssue, VerifierFailure from functools import lru_cache class EnhancedAST(ast.AST): parent = None # type: EnhancedAST The provided code snippet includes necessary dependencies for implementing the `mangled_name` function. Write a Python function `def mangled_name(node: EnhancedAST) -> str` to solve the following problem: Parameters: node: the node which should be mangled name: the name of the node Returns: The mangled name of `node` Here is the function: def mangled_name(node: EnhancedAST) -> str: """ Parameters: node: the node which should be mangled name: the name of the node Returns: The mangled name of `node` """ if isinstance(node, ast.Attribute): name = node.attr elif isinstance(node, ast.Name): name = node.id elif isinstance(node, (ast.alias)): name = node.asname or node.name.split(".")[0] elif isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef)): name = node.name elif isinstance(node, ast.ExceptHandler): name = node.name or "exc" else: raise TypeError("no node to mangle") if name.startswith("__") and not name.endswith("__"): parent,child=node.parent,node while not (isinstance(parent,ast.ClassDef) and child not in parent.bases): if not hasattr(parent,"parent"): break parent,child=parent.parent,parent else: class_name=parent.name.lstrip("_") if class_name!="": return "_" + class_name + name return name
Parameters: node: the node which should be mangled name: the name of the node Returns: The mangled name of `node`
176,969
import __future__ import ast import dis import functools import inspect import io import linecache import re import sys import types from collections import defaultdict, namedtuple from copy import deepcopy from itertools import islice from operator import attrgetter from threading import RLock from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast def cache(func): # type: (Callable) -> Callable d = {} # type: Dict[Tuple, Callable] @functools.wraps(func) def wrapper(*args): # type: (Any) -> Any if args in d: return d[args] result = d[args] = func(*args) return result return wrapper
null
176,970
import __future__ import ast import dis import functools import inspect import io import linecache import re import sys import types from collections import defaultdict, namedtuple from copy import deepcopy from itertools import islice from operator import attrgetter from threading import RLock from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast future_flags = sum( getattr(__future__, fname).compiler_flag for fname in __future__.all_feature_names ) def compile_similar_to(source, matching_code): # type: (ast.Module, types.CodeType) -> Any return compile( source, matching_code.co_filename, 'exec', flags=future_flags & matching_code.co_flags, dont_inherit=True, )
null
176,971
import __future__ import ast import dis import functools import inspect import io import linecache import re import sys import types from collections import defaultdict, namedtuple from copy import deepcopy from itertools import islice from operator import attrgetter from threading import RLock from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Sized, Tuple, Type, TypeVar, Union, cast def get_instructions(co): # type: (types.CodeType) -> Iterator[EnhancedInstruction] lineno = co.co_firstlineno for inst in _get_instructions(co): inst = cast(EnhancedInstruction, inst) lineno = inst.starts_line or lineno assert_(lineno) inst.lineno = lineno yield inst def is_rewritten_by_pytest(code): # type: (types.CodeType) -> bool return any( bc.opname != "LOAD_CONST" and isinstance(bc.argval,str) and bc.argval.startswith("@py") for bc in get_instructions(code) )
null