partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
InteractiveShell.register_post_execute
Register a function for calling after code execution.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def register_post_execute(self, func): """Register a function for calling after code execution. """ if not callable(func): raise ValueError('argument %s must be callable' % func) self._post_execute[func] = True
def register_post_execute(self, func): """Register a function for calling after code execution. """ if not callable(func): raise ValueError('argument %s must be callable' % func) self._post_execute[func] = True
[ "Register", "a", "function", "for", "calling", "after", "code", "execution", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L786-L791
[ "def", "register_post_execute", "(", "self", ",", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "ValueError", "(", "'argument %s must be callable'", "%", "func", ")", "self", ".", "_post_execute", "[", "func", "]", "=", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.new_main_mod
Return a new 'main' module object for user code execution.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def new_main_mod(self,ns=None): """Return a new 'main' module object for user code execution. """ main_mod = self._user_main_module init_fakemod_dict(main_mod,ns) return main_mod
def new_main_mod(self,ns=None): """Return a new 'main' module object for user code execution. """ main_mod = self._user_main_module init_fakemod_dict(main_mod,ns) return main_mod
[ "Return", "a", "new", "main", "module", "object", "for", "user", "code", "execution", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L797-L802
[ "def", "new_main_mod", "(", "self", ",", "ns", "=", "None", ")", ":", "main_mod", "=", "self", ".", "_user_main_module", "init_fakemod_dict", "(", "main_mod", ",", "ns", ")", "return", "main_mod" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.cache_main_mod
Cache a main module's namespace. When scripts are executed via %run, we must keep a reference to the namespace of their __main__ module (a FakeModule instance) around so that Python doesn't clear it, rendering objects defined therein useless. This method keeps said reference in a private dict, keyed by the absolute path of the module object (which corresponds to the script path). 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. Note: we can not allow the actual FakeModule instances to be deleted, because of how Python tears down modules (it hard-sets all their references to None without regard for reference counts). This method must therefore make a *copy* of the given namespace, to allow the original module's __dict__ to be cleared and reused. Parameters ---------- ns : a namespace (a dict, typically) fname : str Filename associated with the namespace. Examples -------- In [10]: import IPython In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) In [12]: IPython.__file__ in _ip._main_ns_cache Out[12]: True
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def cache_main_mod(self,ns,fname): """Cache a main module's namespace. When scripts are executed via %run, we must keep a reference to the namespace of their __main__ module (a FakeModule instance) around so that Python doesn't clear it, rendering objects defined therein useless. This method keeps said reference in a private dict, keyed by the absolute path of the module object (which corresponds to the script path). 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. Note: we can not allow the actual FakeModule instances to be deleted, because of how Python tears down modules (it hard-sets all their references to None without regard for reference counts). This method must therefore make a *copy* of the given namespace, to allow the original module's __dict__ to be cleared and reused. Parameters ---------- ns : a namespace (a dict, typically) fname : str Filename associated with the namespace. Examples -------- In [10]: import IPython In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) In [12]: IPython.__file__ in _ip._main_ns_cache Out[12]: True """ self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
def cache_main_mod(self,ns,fname): """Cache a main module's namespace. When scripts are executed via %run, we must keep a reference to the namespace of their __main__ module (a FakeModule instance) around so that Python doesn't clear it, rendering objects defined therein useless. This method keeps said reference in a private dict, keyed by the absolute path of the module object (which corresponds to the script path). 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. Note: we can not allow the actual FakeModule instances to be deleted, because of how Python tears down modules (it hard-sets all their references to None without regard for reference counts). This method must therefore make a *copy* of the given namespace, to allow the original module's __dict__ to be cleared and reused. Parameters ---------- ns : a namespace (a dict, typically) fname : str Filename associated with the namespace. Examples -------- In [10]: import IPython In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) In [12]: IPython.__file__ in _ip._main_ns_cache Out[12]: True """ self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
[ "Cache", "a", "main", "module", "s", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L804-L843
[ "def", "cache_main_mod", "(", "self", ",", "ns", ",", "fname", ")", ":", "self", ".", "_main_ns_cache", "[", "os", ".", "path", ".", "abspath", "(", "fname", ")", "]", "=", "ns", ".", "copy", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.debugger
Call the pydb/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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def debugger(self,force=False): """Call the pydb/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 # use pydb if available if debugger.has_pydb: from pydb import pm else: # fallback to our internal debugger pm = lambda : self.InteractiveTB.debugger(force=True) with self.readline_no_record: pm()
def debugger(self,force=False): """Call the pydb/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 # use pydb if available if debugger.has_pydb: from pydb import pm else: # fallback to our internal debugger pm = lambda : self.InteractiveTB.debugger(force=True) with self.readline_no_record: pm()
[ "Call", "the", "pydb", "/", "pdb", "debugger", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L893-L919
[ "def", "debugger", "(", "self", ",", "force", "=", "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", "# use pydb if available", "if", "debugger", ".", "has_pydb", ":", "from", "pydb", "import", "pm", "else", ":", "# fallback to our internal debugger", "pm", "=", "lambda", ":", "self", ".", "InteractiveTB", ".", "debugger", "(", "force", "=", "True", ")", "with", "self", ".", "readline_no_record", ":", "pm", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.prepare_user_module
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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__") class DummyMod(object): "A dummy module used for IPython's interactive namespace." pass 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 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__") class DummyMod(object): "A dummy module used for IPython's interactive namespace." pass 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
[ "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", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1011-L1056
[ "def", "prepare_user_module", "(", "self", ",", "user_module", "=", "None", ",", "user_ns", "=", "None", ")", ":", "if", "user_module", "is", "None", "and", "user_ns", "is", "not", "None", ":", "user_ns", ".", "setdefault", "(", "\"__name__\"", ",", "\"__main__\"", ")", "class", "DummyMod", "(", "object", ")", ":", "\"A dummy module used for IPython's interactive namespace.\"", "pass", "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" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.init_user_ns
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 therm.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 therm. """ # 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 theye 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 = dict() # Put 'help' in the user namespace try: from site import _Helper ns['help'] = _Helper() except ImportError: warn('help() not available - check site.py') # 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 ns['_sh'] = shadowns # 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 # 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 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 therm. """ # 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 theye 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 = dict() # Put 'help' in the user namespace try: from site import _Helper ns['help'] = _Helper() except ImportError: warn('help() not available - check site.py') # 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 ns['_sh'] = shadowns # 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 # 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)
[ "Initialize", "all", "user", "-", "visible", "namespaces", "to", "their", "minimum", "defaults", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1078-L1143
[ "def", "init_user_ns", "(", "self", ")", ":", "# 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 theye 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", "=", "dict", "(", ")", "# Put 'help' in the user namespace", "try", ":", "from", "site", "import", "_Helper", "ns", "[", "'help'", "]", "=", "_Helper", "(", ")", "except", "ImportError", ":", "warn", "(", "'help() not available - check site.py'", ")", "# 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", "ns", "[", "'_sh'", "]", "=", "shadowns", "# 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", "# 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", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.all_ns_refs
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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_main_module.__dict__] + self._main_ns_cache.values()
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_main_module.__dict__] + self._main_ns_cache.values()
[ "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", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1146-L1153
[ "def", "all_ns_refs", "(", "self", ")", ":", "return", "[", "self", ".", "user_ns", ",", "self", ".", "user_global_ns", ",", "self", ".", "_user_main_module", ".", "__dict__", "]", "+", "self", ".", "_main_ns_cache", ".", "values", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.reset
Clear all internal namespaces, and attempt to release references to user objects. If new_session is True, a new history session will be opened.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def reset(self, new_session=True): """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 # 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() # Restore the default and user aliases self.alias_manager.clear_aliases() self.alias_manager.init_aliases() # Flush the private list of module references kept for script # execution protection self.clear_main_mod_cache() # Clear out the namespace from the last %run self.new_main_mod()
def reset(self, new_session=True): """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 # 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() # Restore the default and user aliases self.alias_manager.clear_aliases() self.alias_manager.init_aliases() # Flush the private list of module references kept for script # execution protection self.clear_main_mod_cache() # Clear out the namespace from the last %run self.new_main_mod()
[ "Clear", "all", "internal", "namespaces", "and", "attempt", "to", "release", "references", "to", "user", "objects", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1155-L1198
[ "def", "reset", "(", "self", ",", "new_session", "=", "True", ")", ":", "# Clear histories", "self", ".", "history_manager", ".", "reset", "(", "new_session", ")", "# Reset counter used to index all histories", "if", "new_session", ":", "self", ".", "execution_count", "=", "1", "# 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", "(", ")", "# Restore the default and user aliases", "self", ".", "alias_manager", ".", "clear_aliases", "(", ")", "self", ".", "alias_manager", ".", "init_aliases", "(", ")", "# Flush the private list of module references kept for script", "# execution protection", "self", ".", "clear_main_mod_cache", "(", ")", "# Clear out the namespace from the last %run", "self", ".", "new_main_mod", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.del_var
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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: raise NameError("name '%s' is not defined" % varname) # 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.iteritems() if o is obj] for name in to_delete: del ns[name] # 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 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: raise NameError("name '%s' is not defined" % varname) # 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.iteritems() if o is obj] for name in to_delete: del ns[name] # displayhook keeps extra references, but not in a dictionary for name in ('_', '__', '___'): if getattr(self.displayhook, name) is obj: setattr(self.displayhook, name, None)
[ "Delete", "a", "variable", "from", "the", "various", "namespaces", "so", "that", "as", "far", "as", "possible", "we", "re", "not", "keeping", "any", "hidden", "references", "to", "it", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1200-L1239
[ "def", "del_var", "(", "self", ",", "varname", ",", "by_name", "=", "False", ")", ":", "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", ":", "raise", "NameError", "(", "\"name '%s' is not defined\"", "%", "varname", ")", "# 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", ".", "iteritems", "(", ")", "if", "o", "is", "obj", "]", "for", "name", "in", "to_delete", ":", "del", "ns", "[", "name", "]", "# displayhook keeps extra references, but not in a dictionary", "for", "name", "in", "(", "'_'", ",", "'__'", ",", "'___'", ")", ":", "if", "getattr", "(", "self", ".", "displayhook", ",", "name", ")", "is", "obj", ":", "setattr", "(", "self", ".", "displayhook", ",", "name", ",", "None", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.reset_selective
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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: raise TypeError('regex must be a string or compiled pattern') # 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 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: raise TypeError('regex must be a string or compiled pattern') # 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]
[ "Clear", "selective", "variables", "from", "internal", "namespaces", "based", "on", "a", "specified", "regular", "expression", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1241-L1261
[ "def", "reset_selective", "(", "self", ",", "regex", "=", "None", ")", ":", "if", "regex", "is", "not", "None", ":", "try", ":", "m", "=", "re", ".", "compile", "(", "regex", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "'regex must be a string or compiled pattern'", ")", "# 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", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.push
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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, (basestring, list, tuple)): if isinstance(variables, basestring): 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: user_ns_hidden.difference_update(vdict) else: user_ns_hidden.update(vdict)
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, (basestring, list, tuple)): if isinstance(variables, basestring): 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: user_ns_hidden.difference_update(vdict) else: user_ns_hidden.update(vdict)
[ "Inject", "a", "group", "of", "variables", "into", "the", "IPython", "user", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1263-L1308
[ "def", "push", "(", "self", ",", "variables", ",", "interactive", "=", "True", ")", ":", "vdict", "=", "None", "# We need a dict of name/value pairs to do namespace updates.", "if", "isinstance", "(", "variables", ",", "dict", ")", ":", "vdict", "=", "variables", "elif", "isinstance", "(", "variables", ",", "(", "basestring", ",", "list", ",", "tuple", ")", ")", ":", "if", "isinstance", "(", "variables", ",", "basestring", ")", ":", "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", ":", "user_ns_hidden", ".", "difference_update", "(", "vdict", ")", "else", ":", "user_ns_hidden", ".", "update", "(", "vdict", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.drop_by_id
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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.iteritems(): if name in self.user_ns and self.user_ns[name] is obj: del self.user_ns[name] self.user_ns_hidden.discard(name)
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.iteritems(): if name in self.user_ns and self.user_ns[name] is obj: del self.user_ns[name] self.user_ns_hidden.discard(name)
[ "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", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1310-L1326
[ "def", "drop_by_id", "(", "self", ",", "variables", ")", ":", "for", "name", ",", "obj", "in", "variables", ".", "iteritems", "(", ")", ":", "if", "name", "in", "self", ".", "user_ns", "and", "self", ".", "user_ns", "[", "name", "]", "is", "obj", ":", "del", "self", ".", "user_ns", "[", "name", "]", "self", ".", "user_ns_hidden", ".", "discard", "(", "name", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell._ofind
Find an object in the available namespaces. self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic Has special code to detect magic functions.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def _ofind(self, oname, namespaces=None): """Find an object in the available namespaces. self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic Has special code to detect magic functions. """ oname = oname.strip() #print '1- oname: <%r>' % oname # dbg if not oname.startswith(ESC_MAGIC) and \ not oname.startswith(ESC_MAGIC2) and \ not py3compat.isidentifier(oname, dotted=True): return dict(found=False) alias_ns = 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__), ('Alias', self.alias_manager.alias_table), ] alias_ns = self.alias_manager.alias_table # initialize results to 'null' found = False; obj = None; ospace = None; ds = None; ismagic = False; isalias = False; parent = None # We need to special-case 'print', which as of python2.6 registers as a # function but should only be treated as one if print_function was # loaded with a future import. In this case, just bail. if (oname == 'print' and not py3compat.PY3 and not \ (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): return {'found':found, 'obj':obj, 'namespace':ospace, 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} # 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 = oname.split('.') oname_head, oname_rest = oname_parts[0],oname_parts[1:] for nsname,ns in namespaces: try: obj = ns[oname_head] except KeyError: continue else: #print 'oname_rest:', oname_rest # dbg for part in oname_rest: try: parent = obj 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 if ns == alias_ns: isalias = True 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 # Last try: special-case some literals like '', [], {}, etc: if not found and oname_head in ["''",'""','[]','{}','()']: obj = eval(oname_head) found = True ospace = 'Interactive' return {'found':found, 'obj':obj, 'namespace':ospace, 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
def _ofind(self, oname, namespaces=None): """Find an object in the available namespaces. self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic Has special code to detect magic functions. """ oname = oname.strip() #print '1- oname: <%r>' % oname # dbg if not oname.startswith(ESC_MAGIC) and \ not oname.startswith(ESC_MAGIC2) and \ not py3compat.isidentifier(oname, dotted=True): return dict(found=False) alias_ns = 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__), ('Alias', self.alias_manager.alias_table), ] alias_ns = self.alias_manager.alias_table # initialize results to 'null' found = False; obj = None; ospace = None; ds = None; ismagic = False; isalias = False; parent = None # We need to special-case 'print', which as of python2.6 registers as a # function but should only be treated as one if print_function was # loaded with a future import. In this case, just bail. if (oname == 'print' and not py3compat.PY3 and not \ (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): return {'found':found, 'obj':obj, 'namespace':ospace, 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} # 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 = oname.split('.') oname_head, oname_rest = oname_parts[0],oname_parts[1:] for nsname,ns in namespaces: try: obj = ns[oname_head] except KeyError: continue else: #print 'oname_rest:', oname_rest # dbg for part in oname_rest: try: parent = obj 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 if ns == alias_ns: isalias = True 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 # Last try: special-case some literals like '', [], {}, etc: if not found and oname_head in ["''",'""','[]','{}','()']: obj = eval(oname_head) found = True ospace = 'Interactive' return {'found':found, 'obj':obj, 'namespace':ospace, 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
[ "Find", "an", "object", "in", "the", "available", "namespaces", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1332-L1425
[ "def", "_ofind", "(", "self", ",", "oname", ",", "namespaces", "=", "None", ")", ":", "oname", "=", "oname", ".", "strip", "(", ")", "#print '1- oname: <%r>' % oname # dbg", "if", "not", "oname", ".", "startswith", "(", "ESC_MAGIC", ")", "and", "not", "oname", ".", "startswith", "(", "ESC_MAGIC2", ")", "and", "not", "py3compat", ".", "isidentifier", "(", "oname", ",", "dotted", "=", "True", ")", ":", "return", "dict", "(", "found", "=", "False", ")", "alias_ns", "=", "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__", ")", ",", "(", "'Alias'", ",", "self", ".", "alias_manager", ".", "alias_table", ")", ",", "]", "alias_ns", "=", "self", ".", "alias_manager", ".", "alias_table", "# initialize results to 'null'", "found", "=", "False", "obj", "=", "None", "ospace", "=", "None", "ds", "=", "None", "ismagic", "=", "False", "isalias", "=", "False", "parent", "=", "None", "# We need to special-case 'print', which as of python2.6 registers as a", "# function but should only be treated as one if print_function was", "# loaded with a future import. In this case, just bail.", "if", "(", "oname", "==", "'print'", "and", "not", "py3compat", ".", "PY3", "and", "not", "(", "self", ".", "compile", ".", "compiler_flags", "&", "__future__", ".", "CO_FUTURE_PRINT_FUNCTION", ")", ")", ":", "return", "{", "'found'", ":", "found", ",", "'obj'", ":", "obj", ",", "'namespace'", ":", "ospace", ",", "'ismagic'", ":", "ismagic", ",", "'isalias'", ":", "isalias", ",", "'parent'", ":", "parent", "}", "# 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", "=", "oname", ".", "split", "(", "'.'", ")", "oname_head", ",", "oname_rest", "=", "oname_parts", "[", "0", "]", ",", "oname_parts", "[", "1", ":", "]", "for", "nsname", ",", "ns", "in", "namespaces", ":", "try", ":", "obj", "=", "ns", "[", "oname_head", "]", "except", "KeyError", ":", "continue", "else", ":", "#print 'oname_rest:', oname_rest # dbg", "for", "part", "in", "oname_rest", ":", "try", ":", "parent", "=", "obj", "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", "if", "ns", "==", "alias_ns", ":", "isalias", "=", "True", "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", "# Last try: special-case some literals like '', [], {}, etc:", "if", "not", "found", "and", "oname_head", "in", "[", "\"''\"", ",", "'\"\"'", ",", "'[]'", ",", "'{}'", ",", "'()'", "]", ":", "obj", "=", "eval", "(", "oname_head", ")", "found", "=", "True", "ospace", "=", "'Interactive'", "return", "{", "'found'", ":", "found", ",", "'obj'", ":", "obj", ",", "'namespace'", ":", "ospace", ",", "'ismagic'", ":", "ismagic", ",", "'isalias'", ":", "isalias", ",", "'parent'", ":", "parent", "}" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell._ofind_property
Second part of object finding, to look for property details.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def _ofind_property(self, oname, info): """Second part of object finding, to look for property details.""" if info.found: # Get the docstring of the class property if it exists. path = oname.split('.') root = '.'.join(path[:-1]) if info.parent is not None: try: target = getattr(info.parent, '__class__') # The object belongs to a class instance. try: target = getattr(target, path[-1]) # The class defines the object. if isinstance(target, property): oname = root + '.__class__.' + path[-1] info = Struct(self._ofind(oname)) except AttributeError: pass except AttributeError: pass # We return either the new info or the unmodified input if the object # hadn't been found return info
def _ofind_property(self, oname, info): """Second part of object finding, to look for property details.""" if info.found: # Get the docstring of the class property if it exists. path = oname.split('.') root = '.'.join(path[:-1]) if info.parent is not None: try: target = getattr(info.parent, '__class__') # The object belongs to a class instance. try: target = getattr(target, path[-1]) # The class defines the object. if isinstance(target, property): oname = root + '.__class__.' + path[-1] info = Struct(self._ofind(oname)) except AttributeError: pass except AttributeError: pass # We return either the new info or the unmodified input if the object # hadn't been found return info
[ "Second", "part", "of", "object", "finding", "to", "look", "for", "property", "details", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1427-L1448
[ "def", "_ofind_property", "(", "self", ",", "oname", ",", "info", ")", ":", "if", "info", ".", "found", ":", "# Get the docstring of the class property if it exists.", "path", "=", "oname", ".", "split", "(", "'.'", ")", "root", "=", "'.'", ".", "join", "(", "path", "[", ":", "-", "1", "]", ")", "if", "info", ".", "parent", "is", "not", "None", ":", "try", ":", "target", "=", "getattr", "(", "info", ".", "parent", ",", "'__class__'", ")", "# The object belongs to a class instance.", "try", ":", "target", "=", "getattr", "(", "target", ",", "path", "[", "-", "1", "]", ")", "# The class defines the object.", "if", "isinstance", "(", "target", ",", "property", ")", ":", "oname", "=", "root", "+", "'.__class__.'", "+", "path", "[", "-", "1", "]", "info", "=", "Struct", "(", "self", ".", "_ofind", "(", "oname", ")", ")", "except", "AttributeError", ":", "pass", "except", "AttributeError", ":", "pass", "# We return either the new info or the unmodified input if the object", "# hadn't been found", "return", "info" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell._object_find
Find an object and return a struct with info about it.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def _object_find(self, oname, namespaces=None): """Find an object and return a struct with info about it.""" inf = Struct(self._ofind(oname, namespaces)) return Struct(self._ofind_property(oname, inf))
def _object_find(self, oname, namespaces=None): """Find an object and return a struct with info about it.""" inf = Struct(self._ofind(oname, namespaces)) return Struct(self._ofind_property(oname, inf))
[ "Find", "an", "object", "and", "return", "a", "struct", "with", "info", "about", "it", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1450-L1453
[ "def", "_object_find", "(", "self", ",", "oname", ",", "namespaces", "=", "None", ")", ":", "inf", "=", "Struct", "(", "self", ".", "_ofind", "(", "oname", ",", "namespaces", ")", ")", "return", "Struct", "(", "self", ".", "_ofind_property", "(", "oname", ",", "inf", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell._inspect
Generic interface to the inspector system. This function is meant to be called by pdef, pdoc & friends.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 = self._object_find(oname, namespaces) if info.found: pmethod = getattr(self.inspector, meth) formatter = format_screen if info.ismagic else None if meth == 'pdoc': pmethod(info.obj, oname, formatter) elif meth == 'pinfo': pmethod(info.obj, oname, formatter, info, **kw) else: pmethod(info.obj, oname) else: print 'Object `%s` not found.' % oname return 'not found'
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 = self._object_find(oname, namespaces) if info.found: pmethod = getattr(self.inspector, meth) formatter = format_screen if info.ismagic else None if meth == 'pdoc': pmethod(info.obj, oname, formatter) elif meth == 'pinfo': pmethod(info.obj, oname, formatter, info, **kw) else: pmethod(info.obj, oname) else: print 'Object `%s` not found.' % oname return 'not found'
[ "Generic", "interface", "to", "the", "inspector", "system", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1455-L1471
[ "def", "_inspect", "(", "self", ",", "meth", ",", "oname", ",", "namespaces", "=", "None", ",", "*", "*", "kw", ")", ":", "info", "=", "self", ".", "_object_find", "(", "oname", ",", "namespaces", ")", "if", "info", ".", "found", ":", "pmethod", "=", "getattr", "(", "self", ".", "inspector", ",", "meth", ")", "formatter", "=", "format_screen", "if", "info", ".", "ismagic", "else", "None", "if", "meth", "==", "'pdoc'", ":", "pmethod", "(", "info", ".", "obj", ",", "oname", ",", "formatter", ")", "elif", "meth", "==", "'pinfo'", ":", "pmethod", "(", "info", ".", "obj", ",", "oname", ",", "formatter", ",", "info", ",", "*", "*", "kw", ")", "else", ":", "pmethod", "(", "info", ".", "obj", ",", "oname", ")", "else", ":", "print", "'Object `%s` not found.'", "%", "oname", "return", "'not found'" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.init_history
Sets up the command history, and starts regular autosaves.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def init_history(self): """Sets up the command history, and starts regular autosaves.""" self.history_manager = HistoryManager(shell=self, config=self.config) self.configurables.append(self.history_manager)
def init_history(self): """Sets up the command history, and starts regular autosaves.""" self.history_manager = HistoryManager(shell=self, config=self.config) self.configurables.append(self.history_manager)
[ "Sets", "up", "the", "command", "history", "and", "starts", "regular", "autosaves", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1487-L1490
[ "def", "init_history", "(", "self", ")", ":", "self", ".", "history_manager", "=", "HistoryManager", "(", "shell", "=", "self", ",", "config", "=", "self", ".", "config", ")", "self", ".", "configurables", ".", "append", "(", "self", ".", "history_manager", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.set_custom_exc
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. 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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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. 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.""" assert type(exc_tuple)==type(()) , \ "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 #print 'Source code :','\n'.join(self.buffer) 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, basestring): 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, basestring): 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 >> io.stderr, "Custom TB Handler failed, unregistering" # show the exception in handler first stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) print >> io.stdout, self.InteractiveTB.stb2text(stb) print >> io.stdout, "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 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. 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.""" assert type(exc_tuple)==type(()) , \ "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 #print 'Source code :','\n'.join(self.buffer) 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, basestring): 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, basestring): 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 >> io.stderr, "Custom TB Handler failed, unregistering" # show the exception in handler first stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) print >> io.stdout, self.InteractiveTB.stb2text(stb) print >> io.stdout, "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
[ "set_custom_exc", "(", "exc_tuple", "handler", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1519-L1619
[ "def", "set_custom_exc", "(", "self", ",", "exc_tuple", ",", "handler", ")", ":", "assert", "type", "(", "exc_tuple", ")", "==", "type", "(", "(", ")", ")", ",", "\"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", "#print 'Source code :','\\n'.join(self.buffer)", "def", "validate_stb", "(", "stb", ")", ":", "\"\"\"validate structured traceback return type\n \n return type of CustomTB *should* be a list of strings, but allow\n single strings or None, which are harmless.\n \n This function will *always* return a list of strings,\n and will raise a TypeError if stb is inappropriate.\n \"\"\"", "msg", "=", "\"CustomTB must return list of strings, not %r\"", "%", "stb", "if", "stb", "is", "None", ":", "return", "[", "]", "elif", "isinstance", "(", "stb", ",", "basestring", ")", ":", "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", ",", "basestring", ")", ":", "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\n \n This makes it harder (but not impossible) for custom exception\n handlers to crash IPython.\n \"\"\"", "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", ">>", "io", ".", "stderr", ",", "\"Custom TB Handler failed, unregistering\"", "# show the exception in handler first", "stb", "=", "self", ".", "InteractiveTB", ".", "structured_traceback", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "print", ">>", "io", ".", "stdout", ",", "self", ".", "InteractiveTB", ".", "stb2text", "(", "stb", ")", "print", ">>", "io", ".", "stdout", ",", "\"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" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.excepthook
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 excepts 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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 excepts 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 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 excepts 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)
[ "One", "more", "defense", "for", "GUI", "apps", "that", "call", "sys", ".", "excepthook", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1621-L1643
[ "def", "excepthook", "(", "self", ",", "etype", ",", "value", ",", "tb", ")", ":", "self", ".", "showtraceback", "(", "(", "etype", ",", "value", ",", "tb", ")", ",", "tb_offset", "=", "0", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell._get_exc_info
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
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 _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
[ "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" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1645-L1675
[ "def", "_get_exc_info", "(", "self", ",", "exc_tuple", "=", "None", ")", ":", "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" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.showtraceback
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, exception_only=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: self.write_err('No traceback available to show.\n') return if etype is 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) elif etype is UsageError: self.write_err("UsageError: %s" % 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. stb = value._render_traceback_() except Exception: stb = self.InteractiveTB.structured_traceback(etype, value, tb, tb_offset=tb_offset) 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: self.write_err("\nKeyboardInterrupt\n")
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, exception_only=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: self.write_err('No traceback available to show.\n') return if etype is 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) elif etype is UsageError: self.write_err("UsageError: %s" % 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. stb = value._render_traceback_() except Exception: stb = self.InteractiveTB.structured_traceback(etype, value, tb, tb_offset=tb_offset) 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: self.write_err("\nKeyboardInterrupt\n")
[ "Display", "the", "exception", "that", "just", "occurred", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1678-L1730
[ "def", "showtraceback", "(", "self", ",", "exc_tuple", "=", "None", ",", "filename", "=", "None", ",", "tb_offset", "=", "None", ",", "exception_only", "=", "False", ")", ":", "try", ":", "try", ":", "etype", ",", "value", ",", "tb", "=", "self", ".", "_get_exc_info", "(", "exc_tuple", ")", "except", "ValueError", ":", "self", ".", "write_err", "(", "'No traceback available to show.\\n'", ")", "return", "if", "etype", "is", "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", ")", "elif", "etype", "is", "UsageError", ":", "self", ".", "write_err", "(", "\"UsageError: %s\"", "%", "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.", "stb", "=", "value", ".", "_render_traceback_", "(", ")", "except", "Exception", ":", "stb", "=", "self", ".", "InteractiveTB", ".", "structured_traceback", "(", "etype", ",", "value", ",", "tb", ",", "tb_offset", "=", "tb_offset", ")", "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", ":", "self", ".", "write_err", "(", "\"\\nKeyboardInterrupt\\n\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell._showtraceback
Actually show a traceback. Subclasses may override this method to put the traceback on a different place, like a side channel.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def _showtraceback(self, etype, evalue, stb): """Actually show a traceback. Subclasses may override this method to put the traceback on a different place, like a side channel. """ print >> io.stdout, self.InteractiveTB.stb2text(stb)
def _showtraceback(self, etype, evalue, stb): """Actually show a traceback. Subclasses may override this method to put the traceback on a different place, like a side channel. """ print >> io.stdout, self.InteractiveTB.stb2text(stb)
[ "Actually", "show", "a", "traceback", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1732-L1738
[ "def", "_showtraceback", "(", "self", ",", "etype", ",", "evalue", ",", "stb", ")", ":", "print", ">>", "io", ".", "stdout", ",", "self", ".", "InteractiveTB", ".", "stb2text", "(", "stb", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.showsyntaxerror
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).
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def showsyntaxerror(self, filename=None): """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). """ etype, value, last_traceback = self._get_exc_info() if filename and etype is SyntaxError: try: value.filename = filename except: # Not the format we expect; leave it alone pass stb = self.SyntaxTB.structured_traceback(etype, value, []) self._showtraceback(etype, value, stb)
def showsyntaxerror(self, filename=None): """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). """ etype, value, last_traceback = self._get_exc_info() if filename and etype is SyntaxError: try: value.filename = filename except: # Not the format we expect; leave it alone pass stb = self.SyntaxTB.structured_traceback(etype, value, []) self._showtraceback(etype, value, stb)
[ "Display", "the", "syntax", "error", "that", "just", "occurred", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1740-L1759
[ "def", "showsyntaxerror", "(", "self", ",", "filename", "=", "None", ")", ":", "etype", ",", "value", ",", "last_traceback", "=", "self", ".", "_get_exc_info", "(", ")", "if", "filename", "and", "etype", "is", "SyntaxError", ":", "try", ":", "value", ".", "filename", "=", "filename", "except", ":", "# Not the format we expect; leave it alone", "pass", "stb", "=", "self", ".", "SyntaxTB", ".", "structured_traceback", "(", "etype", ",", "value", ",", "[", "]", ")", "self", ".", "_showtraceback", "(", "etype", ",", "value", ",", "stb", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.init_readline
Command history completion/saving/reloading.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def init_readline(self): """Command history completion/saving/reloading.""" if self.readline_use: import IPython.utils.rlineimpl as readline self.rl_next_input = None self.rl_do_indent = False if not self.readline_use or not readline.have_readline: self.has_readline = False self.readline = None # Set a number of methods that depend on readline to be no-op self.readline_no_record = no_op_context self.set_readline_completer = no_op self.set_custom_completer = no_op if self.readline_use: warn('Readline services not available or not loaded.') else: self.has_readline = True self.readline = readline sys.modules['readline'] = readline # Platform-specific configuration if os.name == 'nt': # FIXME - check with Frederick to see if we can harmonize # naming conventions with pyreadline to avoid this # platform-dependent check self.readline_startup_hook = readline.set_pre_input_hook else: self.readline_startup_hook = readline.set_startup_hook # Load user's initrc file (readline config) # Or if libedit is used, load editrc. inputrc_name = os.environ.get('INPUTRC') if inputrc_name is None: inputrc_name = '.inputrc' if readline.uses_libedit: inputrc_name = '.editrc' inputrc_name = os.path.join(self.home_dir, inputrc_name) if os.path.isfile(inputrc_name): try: readline.read_init_file(inputrc_name) except: warn('Problems reading readline initialization file <%s>' % inputrc_name) # Configure readline according to user's prefs # This is only done if GNU readline is being used. If libedit # is being used (as on Leopard) the readline config is # not run as the syntax for libedit is different. if not readline.uses_libedit: for rlcommand in self.readline_parse_and_bind: #print "loading rl:",rlcommand # dbg readline.parse_and_bind(rlcommand) # Remove some chars from the delimiters list. If we encounter # unicode chars, discard them. delims = readline.get_completer_delims() if not py3compat.PY3: delims = delims.encode("ascii", "ignore") for d in self.readline_remove_delims: delims = delims.replace(d, "") delims = delims.replace(ESC_MAGIC, '') readline.set_completer_delims(delims) # otherwise we end up with a monster history after a while: readline.set_history_length(self.history_length) self.refill_readline_hist() self.readline_no_record = ReadlineNoRecord(self) # Configure auto-indent for all platforms self.set_autoindent(self.autoindent)
def init_readline(self): """Command history completion/saving/reloading.""" if self.readline_use: import IPython.utils.rlineimpl as readline self.rl_next_input = None self.rl_do_indent = False if not self.readline_use or not readline.have_readline: self.has_readline = False self.readline = None # Set a number of methods that depend on readline to be no-op self.readline_no_record = no_op_context self.set_readline_completer = no_op self.set_custom_completer = no_op if self.readline_use: warn('Readline services not available or not loaded.') else: self.has_readline = True self.readline = readline sys.modules['readline'] = readline # Platform-specific configuration if os.name == 'nt': # FIXME - check with Frederick to see if we can harmonize # naming conventions with pyreadline to avoid this # platform-dependent check self.readline_startup_hook = readline.set_pre_input_hook else: self.readline_startup_hook = readline.set_startup_hook # Load user's initrc file (readline config) # Or if libedit is used, load editrc. inputrc_name = os.environ.get('INPUTRC') if inputrc_name is None: inputrc_name = '.inputrc' if readline.uses_libedit: inputrc_name = '.editrc' inputrc_name = os.path.join(self.home_dir, inputrc_name) if os.path.isfile(inputrc_name): try: readline.read_init_file(inputrc_name) except: warn('Problems reading readline initialization file <%s>' % inputrc_name) # Configure readline according to user's prefs # This is only done if GNU readline is being used. If libedit # is being used (as on Leopard) the readline config is # not run as the syntax for libedit is different. if not readline.uses_libedit: for rlcommand in self.readline_parse_and_bind: #print "loading rl:",rlcommand # dbg readline.parse_and_bind(rlcommand) # Remove some chars from the delimiters list. If we encounter # unicode chars, discard them. delims = readline.get_completer_delims() if not py3compat.PY3: delims = delims.encode("ascii", "ignore") for d in self.readline_remove_delims: delims = delims.replace(d, "") delims = delims.replace(ESC_MAGIC, '') readline.set_completer_delims(delims) # otherwise we end up with a monster history after a while: readline.set_history_length(self.history_length) self.refill_readline_hist() self.readline_no_record = ReadlineNoRecord(self) # Configure auto-indent for all platforms self.set_autoindent(self.autoindent)
[ "Command", "history", "completion", "/", "saving", "/", "reloading", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1775-L1847
[ "def", "init_readline", "(", "self", ")", ":", "if", "self", ".", "readline_use", ":", "import", "IPython", ".", "utils", ".", "rlineimpl", "as", "readline", "self", ".", "rl_next_input", "=", "None", "self", ".", "rl_do_indent", "=", "False", "if", "not", "self", ".", "readline_use", "or", "not", "readline", ".", "have_readline", ":", "self", ".", "has_readline", "=", "False", "self", ".", "readline", "=", "None", "# Set a number of methods that depend on readline to be no-op", "self", ".", "readline_no_record", "=", "no_op_context", "self", ".", "set_readline_completer", "=", "no_op", "self", ".", "set_custom_completer", "=", "no_op", "if", "self", ".", "readline_use", ":", "warn", "(", "'Readline services not available or not loaded.'", ")", "else", ":", "self", ".", "has_readline", "=", "True", "self", ".", "readline", "=", "readline", "sys", ".", "modules", "[", "'readline'", "]", "=", "readline", "# Platform-specific configuration", "if", "os", ".", "name", "==", "'nt'", ":", "# FIXME - check with Frederick to see if we can harmonize", "# naming conventions with pyreadline to avoid this", "# platform-dependent check", "self", ".", "readline_startup_hook", "=", "readline", ".", "set_pre_input_hook", "else", ":", "self", ".", "readline_startup_hook", "=", "readline", ".", "set_startup_hook", "# Load user's initrc file (readline config)", "# Or if libedit is used, load editrc.", "inputrc_name", "=", "os", ".", "environ", ".", "get", "(", "'INPUTRC'", ")", "if", "inputrc_name", "is", "None", ":", "inputrc_name", "=", "'.inputrc'", "if", "readline", ".", "uses_libedit", ":", "inputrc_name", "=", "'.editrc'", "inputrc_name", "=", "os", ".", "path", ".", "join", "(", "self", ".", "home_dir", ",", "inputrc_name", ")", "if", "os", ".", "path", ".", "isfile", "(", "inputrc_name", ")", ":", "try", ":", "readline", ".", "read_init_file", "(", "inputrc_name", ")", "except", ":", "warn", "(", "'Problems reading readline initialization file <%s>'", "%", "inputrc_name", ")", "# Configure readline according to user's prefs", "# This is only done if GNU readline is being used. If libedit", "# is being used (as on Leopard) the readline config is", "# not run as the syntax for libedit is different.", "if", "not", "readline", ".", "uses_libedit", ":", "for", "rlcommand", "in", "self", ".", "readline_parse_and_bind", ":", "#print \"loading rl:\",rlcommand # dbg", "readline", ".", "parse_and_bind", "(", "rlcommand", ")", "# Remove some chars from the delimiters list. If we encounter", "# unicode chars, discard them.", "delims", "=", "readline", ".", "get_completer_delims", "(", ")", "if", "not", "py3compat", ".", "PY3", ":", "delims", "=", "delims", ".", "encode", "(", "\"ascii\"", ",", "\"ignore\"", ")", "for", "d", "in", "self", ".", "readline_remove_delims", ":", "delims", "=", "delims", ".", "replace", "(", "d", ",", "\"\"", ")", "delims", "=", "delims", ".", "replace", "(", "ESC_MAGIC", ",", "''", ")", "readline", ".", "set_completer_delims", "(", "delims", ")", "# otherwise we end up with a monster history after a while:", "readline", ".", "set_history_length", "(", "self", ".", "history_length", ")", "self", ".", "refill_readline_hist", "(", ")", "self", ".", "readline_no_record", "=", "ReadlineNoRecord", "(", "self", ")", "# Configure auto-indent for all platforms", "self", ".", "set_autoindent", "(", "self", ".", "autoindent", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.pre_readline
readline hook to be used at the start of each line. Currently it handles auto-indent only.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def pre_readline(self): """readline hook to be used at the start of each line. Currently it handles auto-indent only.""" if self.rl_do_indent: self.readline.insert_text(self._indent_current_str()) if self.rl_next_input is not None: self.readline.insert_text(self.rl_next_input) self.rl_next_input = None
def pre_readline(self): """readline hook to be used at the start of each line. Currently it handles auto-indent only.""" if self.rl_do_indent: self.readline.insert_text(self._indent_current_str()) if self.rl_next_input is not None: self.readline.insert_text(self.rl_next_input) self.rl_next_input = None
[ "readline", "hook", "to", "be", "used", "at", "the", "start", "of", "each", "line", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1881-L1890
[ "def", "pre_readline", "(", "self", ")", ":", "if", "self", ".", "rl_do_indent", ":", "self", ".", "readline", ".", "insert_text", "(", "self", ".", "_indent_current_str", "(", ")", ")", "if", "self", ".", "rl_next_input", "is", "not", "None", ":", "self", ".", "readline", ".", "insert_text", "(", "self", ".", "rl_next_input", ")", "self", ".", "rl_next_input", "=", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.init_completer
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), programatically (such as in test suites) or out-of-prcess (typically over the network by remote frontends).
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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), programatically (such as in test suites) or out-of-prcess (typically over the network by remote frontends). """ from IPython.core.completer import IPCompleter from IPython.core.completerlib import (module_completer, magic_run_completer, cd_completer, reset_completer) self.Completer = IPCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, alias_table=self.alias_manager.alias_table, use_readline=self.has_readline, config=self.config, ) 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', 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') # Only configure readline if we truly are using readline. IPython can # do tab-completion over the network, in GUIs, etc, where readline # itself may be absent if self.has_readline: self.set_readline_completer()
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), programatically (such as in test suites) or out-of-prcess (typically over the network by remote frontends). """ from IPython.core.completer import IPCompleter from IPython.core.completerlib import (module_completer, magic_run_completer, cd_completer, reset_completer) self.Completer = IPCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, alias_table=self.alias_manager.alias_table, use_readline=self.has_readline, config=self.config, ) 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', 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') # Only configure readline if we truly are using readline. IPython can # do tab-completion over the network, in GUIs, etc, where readline # itself may be absent if self.has_readline: self.set_readline_completer()
[ "Initialize", "the", "completion", "machinery", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1900-L1936
[ "def", "init_completer", "(", "self", ")", ":", "from", "IPython", ".", "core", ".", "completer", "import", "IPCompleter", "from", "IPython", ".", "core", ".", "completerlib", "import", "(", "module_completer", ",", "magic_run_completer", ",", "cd_completer", ",", "reset_completer", ")", "self", ".", "Completer", "=", "IPCompleter", "(", "shell", "=", "self", ",", "namespace", "=", "self", ".", "user_ns", ",", "global_namespace", "=", "self", ".", "user_global_ns", ",", "alias_table", "=", "self", ".", "alias_manager", ".", "alias_table", ",", "use_readline", "=", "self", ".", "has_readline", ",", "config", "=", "self", ".", "config", ",", ")", "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'", ",", "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'", ")", "# Only configure readline if we truly are using readline. IPython can", "# do tab-completion over the network, in GUIs, etc, where readline", "# itself may be absent", "if", "self", ".", "has_readline", ":", "self", ".", "set_readline_completer", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.complete
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. 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. Simple usage example: In [1]: x = 'hello' In [2]: _ip.complete('x.l') Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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. 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. Simple usage example: 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 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. 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. Simple usage example: 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)
[ "Return", "the", "completed", "text", "and", "a", "list", "of", "completions", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1938-L1981
[ "def", "complete", "(", "self", ",", "text", ",", "line", "=", "None", ",", "cursor_pos", "=", "None", ")", ":", "# Inject names into __builtin__ so we can complete on the added names.", "with", "self", ".", "builtin_trap", ":", "return", "self", ".", "Completer", ".", "complete", "(", "text", ",", "line", ",", "cursor_pos", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.set_custom_completer
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def set_custom_completer(self, completer, pos=0): """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.""" newcomp = types.MethodType(completer,self.Completer) self.Completer.matchers.insert(pos,newcomp)
def set_custom_completer(self, completer, pos=0): """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.""" newcomp = types.MethodType(completer,self.Completer) self.Completer.matchers.insert(pos,newcomp)
[ "Adds", "a", "new", "custom", "completer", "function", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1983-L1990
[ "def", "set_custom_completer", "(", "self", ",", "completer", ",", "pos", "=", "0", ")", ":", "newcomp", "=", "types", ".", "MethodType", "(", "completer", ",", "self", ".", "Completer", ")", "self", ".", "Completer", ".", "matchers", ".", "insert", "(", "pos", ",", "newcomp", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.set_completer_frame
Set the frame of the completer.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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
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
[ "Set", "the", "frame", "of", "the", "completer", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1996-L2003
[ "def", "set_completer_frame", "(", "self", ",", "frame", "=", "None", ")", ":", "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" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.run_line_magic
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def run_line_magic(self, magic_name, line): """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. """ 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 ) error(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. stack_depth = 2 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] # Grab local namespace if we need it: if getattr(fn, "needs_local_scope", False): args.append(sys._getframe(stack_depth).f_locals) with self.builtin_trap: result = fn(*args) return result
def run_line_magic(self, magic_name, line): """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. """ 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 ) error(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. stack_depth = 2 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] # Grab local namespace if we need it: if getattr(fn, "needs_local_scope", False): args.append(sys._getframe(stack_depth).f_locals) with self.builtin_trap: result = fn(*args) return result
[ "Execute", "the", "given", "line", "magic", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2032-L2063
[ "def", "run_line_magic", "(", "self", ",", "magic_name", ",", "line", ")", ":", "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", ")", "error", "(", "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.", "stack_depth", "=", "2", "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", "]", "# Grab local namespace if we need it:", "if", "getattr", "(", "fn", ",", "\"needs_local_scope\"", ",", "False", ")", ":", "args", ".", "append", "(", "sys", ".", "_getframe", "(", "stack_depth", ")", ".", "f_locals", ")", "with", "self", ".", "builtin_trap", ":", "result", "=", "fn", "(", "*", "args", ")", "return", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.run_cell_magic
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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_cell_magic(magic_name) if fn is None: lm = self.find_line_magic(magic_name) etpl = "Cell magic function `%%%%%s` not found%s." extra = '' if lm is None else (' (But line magic `%%%s` exists, ' 'did you mean that instead?)' % magic_name ) error(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. stack_depth = 2 magic_arg_s = self.var_expand(line, stack_depth) with self.builtin_trap: result = fn(line, cell) return result
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_cell_magic(magic_name) if fn is None: lm = self.find_line_magic(magic_name) etpl = "Cell magic function `%%%%%s` not found%s." extra = '' if lm is None else (' (But line magic `%%%s` exists, ' 'did you mean that instead?)' % magic_name ) error(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. stack_depth = 2 magic_arg_s = self.var_expand(line, stack_depth) with self.builtin_trap: result = fn(line, cell) return result
[ "Execute", "the", "given", "cell", "magic", ".", "Parameters", "----------", "magic_name", ":", "str", "Name", "of", "the", "desired", "magic", "function", "without", "%", "prefix", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2065-L2094
[ "def", "run_cell_magic", "(", "self", ",", "magic_name", ",", "line", ",", "cell", ")", ":", "fn", "=", "self", ".", "find_cell_magic", "(", "magic_name", ")", "if", "fn", "is", "None", ":", "lm", "=", "self", ".", "find_line_magic", "(", "magic_name", ")", "etpl", "=", "\"Cell magic function `%%%%%s` not found%s.\"", "extra", "=", "''", "if", "lm", "is", "None", "else", "(", "' (But line magic `%%%s` exists, '", "'did you mean that instead?)'", "%", "magic_name", ")", "error", "(", "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.", "stack_depth", "=", "2", "magic_arg_s", "=", "self", ".", "var_expand", "(", "line", ",", "stack_depth", ")", "with", "self", ".", "builtin_trap", ":", "result", "=", "fn", "(", "line", ",", "cell", ")", "return", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.find_magic
Find and return a magic of the given type by name. Returns None if the magic isn't found.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 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)
[ "Find", "and", "return", "a", "magic", "of", "the", "given", "type", "by", "name", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2108-L2112
[ "def", "find_magic", "(", "self", ",", "magic_name", ",", "magic_kind", "=", "'line'", ")", ":", "return", "self", ".", "magics_manager", ".", "magics", "[", "magic_kind", "]", ".", "get", "(", "magic_name", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.magic
DEPRECATED. Use run_line_magic() instead. 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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def magic(self, arg_s): """DEPRECATED. Use run_line_magic() instead. 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. """ # 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)
def magic(self, arg_s): """DEPRECATED. Use run_line_magic() instead. 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. """ # 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)
[ "DEPRECATED", ".", "Use", "run_line_magic", "()", "instead", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2114-L2136
[ "def", "magic", "(", "self", ",", "arg_s", ")", ":", "# 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", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.define_macro
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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, basestring): 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
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, basestring): 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
[ "Define", "a", "new", "macro" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2142-L2160
[ "def", "define_macro", "(", "self", ",", "name", ",", "themacro", ")", ":", "from", "IPython", ".", "core", "import", "macro", "if", "isinstance", "(", "themacro", ",", "basestring", ")", ":", "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" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.system_raw
Call the given cmd in a subprocess using os.system Parameters ---------- cmd : str Command to execute.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def system_raw(self, cmd): """Call the given cmd in a subprocess using os.system Parameters ---------- cmd : str Command to execute. """ cmd = self.var_expand(cmd, depth=1) # 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) cmd = py3compat.unicode_to_str(cmd) ec = os.system(cmd) else: cmd = py3compat.unicode_to_str(cmd) ec = os.system(cmd) # 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'] = ec
def system_raw(self, cmd): """Call the given cmd in a subprocess using os.system Parameters ---------- cmd : str Command to execute. """ cmd = self.var_expand(cmd, depth=1) # 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) cmd = py3compat.unicode_to_str(cmd) ec = os.system(cmd) else: cmd = py3compat.unicode_to_str(cmd) ec = os.system(cmd) # 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'] = ec
[ "Call", "the", "given", "cmd", "in", "a", "subprocess", "using", "os", ".", "system" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2189-L2213
[ "def", "system_raw", "(", "self", ",", "cmd", ")", ":", "cmd", "=", "self", ".", "var_expand", "(", "cmd", ",", "depth", "=", "1", ")", "# 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", ")", "cmd", "=", "py3compat", ".", "unicode_to_str", "(", "cmd", ")", "ec", "=", "os", ".", "system", "(", "cmd", ")", "else", ":", "cmd", "=", "py3compat", ".", "unicode_to_str", "(", "cmd", ")", "ec", "=", "os", ".", "system", "(", "cmd", ")", "# 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'", "]", "=", "ec" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.getoutput
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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
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
[ "Get", "output", "(", "possibly", "including", "stderr", ")", "from", "a", "subprocess", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2218-L2245
[ "def", "getoutput", "(", "self", ",", "cmd", ",", "split", "=", "True", ",", "depth", "=", "0", ")", ":", "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" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.auto_rewrite_input
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 rw = self.prompt_manager.render('rewrite') + cmd try: # plain ascii works better w/ pyreadline, on some machines, so # we use it and only print uncolored rewrite if we have unicode rw = str(rw) print >> io.stdout, rw except UnicodeEncodeError: print "------> " + cmd
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 rw = self.prompt_manager.render('rewrite') + cmd try: # plain ascii works better w/ pyreadline, on some machines, so # we use it and only print uncolored rewrite if we have unicode rw = str(rw) print >> io.stdout, rw except UnicodeEncodeError: print "------> " + cmd
[ "Print", "to", "the", "screen", "the", "rewritten", "form", "of", "the", "user", "s", "command", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2289-L2315
[ "def", "auto_rewrite_input", "(", "self", ",", "cmd", ")", ":", "if", "not", "self", ".", "show_rewritten_input", ":", "return", "rw", "=", "self", ".", "prompt_manager", ".", "render", "(", "'rewrite'", ")", "+", "cmd", "try", ":", "# plain ascii works better w/ pyreadline, on some machines, so", "# we use it and only print uncolored rewrite if we have unicode", "rw", "=", "str", "(", "rw", ")", "print", ">>", "io", ".", "stdout", ",", "rw", "except", "UnicodeEncodeError", ":", "print", "\"------> \"", "+", "cmd" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.user_variables
Get a list of variable names from the user's namespace. Parameters ---------- names : list of strings A list of names of variables to be read from the user namespace. Returns ------- A dict, keyed by the input names and with the repr() of each value.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def user_variables(self, names): """Get a list of variable names from the user's namespace. Parameters ---------- names : list of strings A list of names of variables to be read from the user namespace. Returns ------- A dict, keyed by the input names and with the repr() of each value. """ out = {} user_ns = self.user_ns for varname in names: try: value = repr(user_ns[varname]) except: value = self._simple_error() out[varname] = value return out
def user_variables(self, names): """Get a list of variable names from the user's namespace. Parameters ---------- names : list of strings A list of names of variables to be read from the user namespace. Returns ------- A dict, keyed by the input names and with the repr() of each value. """ out = {} user_ns = self.user_ns for varname in names: try: value = repr(user_ns[varname]) except: value = self._simple_error() out[varname] = value return out
[ "Get", "a", "list", "of", "variable", "names", "from", "the", "user", "s", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2325-L2345
[ "def", "user_variables", "(", "self", ",", "names", ")", ":", "out", "=", "{", "}", "user_ns", "=", "self", ".", "user_ns", "for", "varname", "in", "names", ":", "try", ":", "value", "=", "repr", "(", "user_ns", "[", "varname", "]", ")", "except", ":", "value", "=", "self", ".", "_simple_error", "(", ")", "out", "[", "varname", "]", "=", "value", "return", "out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.user_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 repr() of each value.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 repr() of each value. """ out = {} user_ns = self.user_ns global_ns = self.user_global_ns for key, expr in expressions.iteritems(): try: value = repr(eval(expr, global_ns, user_ns)) except: value = self._simple_error() out[key] = value return out
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 repr() of each value. """ out = {} user_ns = self.user_ns global_ns = self.user_global_ns for key, expr in expressions.iteritems(): try: value = repr(eval(expr, global_ns, user_ns)) except: value = self._simple_error() out[key] = value return out
[ "Evaluate", "a", "dict", "of", "expressions", "in", "the", "user", "s", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2347-L2371
[ "def", "user_expressions", "(", "self", ",", "expressions", ")", ":", "out", "=", "{", "}", "user_ns", "=", "self", ".", "user_ns", "global_ns", "=", "self", ".", "user_global_ns", "for", "key", ",", "expr", "in", "expressions", ".", "iteritems", "(", ")", ":", "try", ":", "value", "=", "repr", "(", "eval", "(", "expr", ",", "global_ns", ",", "user_ns", ")", ")", "except", ":", "value", "=", "self", ".", "_simple_error", "(", ")", "out", "[", "key", "]", "=", "value", "return", "out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.ex
Execute a normal python statement in user namespace.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec cmd in self.user_global_ns, self.user_ns
def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec cmd in self.user_global_ns, self.user_ns
[ "Execute", "a", "normal", "python", "statement", "in", "user", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2377-L2380
[ "def", "ex", "(", "self", ",", "cmd", ")", ":", "with", "self", ".", "builtin_trap", ":", "exec", "cmd", "in", "self", ".", "user_global_ns", ",", "self", ".", "user_ns" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.ev
Evaluate python expression expr in user namespace. Returns the result of evaluation
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 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)
[ "Evaluate", "python", "expression", "expr", "in", "user", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2382-L2388
[ "def", "ev", "(", "self", ",", "expr", ")", ":", "with", "self", ".", "builtin_trap", ":", "return", "eval", "(", "expr", ",", "self", ".", "user_global_ns", ",", "self", ".", "user_ns", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.safe_execfile
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def safe_execfile(self, fname, *where, **kw): """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. """ kw.setdefault('exit_ignore', False) kw.setdefault('raise_exceptions', False) fname = os.path.abspath(os.path.expanduser(fname)) # Make sure we can open the file try: with open(fname) as thefile: 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 = os.path.dirname(fname) with prepended_to_syspath(dname): try: py3compat.execfile(fname,*where) except SystemExit, 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 kw['raise_exceptions']: raise if status.code not in (0, None) and not kw['exit_ignore']: self.showtraceback(exception_only=True) except: if kw['raise_exceptions']: raise self.showtraceback()
def safe_execfile(self, fname, *where, **kw): """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. """ kw.setdefault('exit_ignore', False) kw.setdefault('raise_exceptions', False) fname = os.path.abspath(os.path.expanduser(fname)) # Make sure we can open the file try: with open(fname) as thefile: 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 = os.path.dirname(fname) with prepended_to_syspath(dname): try: py3compat.execfile(fname,*where) except SystemExit, 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 kw['raise_exceptions']: raise if status.code not in (0, None) and not kw['exit_ignore']: self.showtraceback(exception_only=True) except: if kw['raise_exceptions']: raise self.showtraceback()
[ "A", "safe", "version", "of", "the", "builtin", "execfile", "()", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2390-L2449
[ "def", "safe_execfile", "(", "self", ",", "fname", ",", "*", "where", ",", "*", "*", "kw", ")", ":", "kw", ".", "setdefault", "(", "'exit_ignore'", ",", "False", ")", "kw", ".", "setdefault", "(", "'raise_exceptions'", ",", "False", ")", "fname", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "fname", ")", ")", "# Make sure we can open the file", "try", ":", "with", "open", "(", "fname", ")", "as", "thefile", ":", "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", "=", "os", ".", "path", ".", "dirname", "(", "fname", ")", "with", "prepended_to_syspath", "(", "dname", ")", ":", "try", ":", "py3compat", ".", "execfile", "(", "fname", ",", "*", "where", ")", "except", "SystemExit", ",", "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", "kw", "[", "'raise_exceptions'", "]", ":", "raise", "if", "status", ".", "code", "not", "in", "(", "0", ",", "None", ")", "and", "not", "kw", "[", "'exit_ignore'", "]", ":", "self", ".", "showtraceback", "(", "exception_only", "=", "True", ")", "except", ":", "if", "kw", "[", "'raise_exceptions'", "]", ":", "raise", "self", ".", "showtraceback", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.safe_execfile_ipy
Like safe_execfile, but for .ipy files with IPython syntax. Parameters ---------- fname : str The name of the file to execute. The filename must have a .ipy extension.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def safe_execfile_ipy(self, fname): """Like safe_execfile, but for .ipy files with IPython syntax. Parameters ---------- fname : str The name of the file to execute. The filename must have a .ipy extension. """ fname = os.path.abspath(os.path.expanduser(fname)) # Make sure we can open the file try: with open(fname) as thefile: 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 = os.path.dirname(fname) with prepended_to_syspath(dname): try: with open(fname) as thefile: # self.run_cell currently captures all exceptions # raised in user code. It would be nice if there were # versions of runlines, execfile that did raise, so # we could catch the errors. self.run_cell(thefile.read(), store_history=False) except: self.showtraceback() warn('Unknown failure executing file: <%s>' % fname)
def safe_execfile_ipy(self, fname): """Like safe_execfile, but for .ipy files with IPython syntax. Parameters ---------- fname : str The name of the file to execute. The filename must have a .ipy extension. """ fname = os.path.abspath(os.path.expanduser(fname)) # Make sure we can open the file try: with open(fname) as thefile: 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 = os.path.dirname(fname) with prepended_to_syspath(dname): try: with open(fname) as thefile: # self.run_cell currently captures all exceptions # raised in user code. It would be nice if there were # versions of runlines, execfile that did raise, so # we could catch the errors. self.run_cell(thefile.read(), store_history=False) except: self.showtraceback() warn('Unknown failure executing file: <%s>' % fname)
[ "Like", "safe_execfile", "but", "for", ".", "ipy", "files", "with", "IPython", "syntax", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2451-L2485
[ "def", "safe_execfile_ipy", "(", "self", ",", "fname", ")", ":", "fname", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "fname", ")", ")", "# Make sure we can open the file", "try", ":", "with", "open", "(", "fname", ")", "as", "thefile", ":", "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", "=", "os", ".", "path", ".", "dirname", "(", "fname", ")", "with", "prepended_to_syspath", "(", "dname", ")", ":", "try", ":", "with", "open", "(", "fname", ")", "as", "thefile", ":", "# self.run_cell currently captures all exceptions", "# raised in user code. It would be nice if there were", "# versions of runlines, execfile that did raise, so", "# we could catch the errors.", "self", ".", "run_cell", "(", "thefile", ".", "read", "(", ")", ",", "store_history", "=", "False", ")", "except", ":", "self", ".", "showtraceback", "(", ")", "warn", "(", "'Unknown failure executing file: <%s>'", "%", "fname", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.safe_run_module
A safe version of runpy.run_module(). This version will never throw an exception, but instead print helpful error messages to the screen. Parameters ---------- mod_name : string The name of the module to be executed. where : dict The globals namespace.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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. Parameters ---------- mod_name : string The name of the module to be executed. where : dict The globals namespace. """ try: where.update( runpy.run_module(str(mod_name), run_name="__main__", alter_sys=True) ) except: self.showtraceback() warn('Unknown failure executing module: <%s>' % mod_name)
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. Parameters ---------- mod_name : string The name of the module to be executed. where : dict The globals namespace. """ try: where.update( runpy.run_module(str(mod_name), run_name="__main__", alter_sys=True) ) except: self.showtraceback() warn('Unknown failure executing module: <%s>' % mod_name)
[ "A", "safe", "version", "of", "runpy", ".", "run_module", "()", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2487-L2507
[ "def", "safe_run_module", "(", "self", ",", "mod_name", ",", "where", ")", ":", "try", ":", "where", ".", "update", "(", "runpy", ".", "run_module", "(", "str", "(", "mod_name", ")", ",", "run_name", "=", "\"__main__\"", ",", "alter_sys", "=", "True", ")", ")", "except", ":", "self", ".", "showtraceback", "(", ")", "warn", "(", "'Unknown failure executing module: <%s>'", "%", "mod_name", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell._run_cached_cell_magic
Special method to call a cell magic with the data stored in self.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def _run_cached_cell_magic(self, magic_name, line): """Special method to call a cell magic with the data stored in self. """ cell = self._current_cell_magic_body self._current_cell_magic_body = None return self.run_cell_magic(magic_name, line, cell)
def _run_cached_cell_magic(self, magic_name, line): """Special method to call a cell magic with the data stored in self. """ cell = self._current_cell_magic_body self._current_cell_magic_body = None return self.run_cell_magic(magic_name, line, cell)
[ "Special", "method", "to", "call", "a", "cell", "magic", "with", "the", "data", "stored", "in", "self", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2509-L2514
[ "def", "_run_cached_cell_magic", "(", "self", ",", "magic_name", ",", "line", ")", ":", "cell", "=", "self", ".", "_current_cell_magic_body", "self", ".", "_current_cell_magic_body", "=", "None", "return", "self", ".", "run_cell_magic", "(", "magic_name", ",", "line", ",", "cell", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.run_cell
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-effets, such as implicit displayhooks, history, and logging. silent=True forces store_history=False.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def run_cell(self, raw_cell, store_history=False, silent=False): """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-effets, such as implicit displayhooks, history, and logging. silent=True forces store_history=False. """ if (not raw_cell) or raw_cell.isspace(): return if silent: store_history = False self.input_splitter.push(raw_cell) # Check for cell magics, which leave state behind. This interface is # ugly, we need to do something cleaner later... Now the logic is # simply that the input_splitter remembers if there was a cell magic, # and in that case we grab the cell body. if self.input_splitter.cell_magic_parts: self._current_cell_magic_body = \ ''.join(self.input_splitter.cell_magic_parts) cell = self.input_splitter.source_reset() with self.builtin_trap: prefilter_failed = False if len(cell.splitlines()) == 1: try: # use prefilter_lines to handle trailing newlines # restore trailing newline for ast.parse cell = self.prefilter_manager.prefilter_lines(cell) + '\n' except AliasError as e: error(e) prefilter_failed = True except Exception: # don't allow prefilter errors to crash IPython self.showtraceback() prefilter_failed = True # 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) if not prefilter_failed: # don't run if prefilter failed cell_name = self.compile.cache(cell, self.execution_count) with self.display_trap: try: code_ast = self.compile.ast_parse(cell, filename=cell_name) except IndentationError: self.showindentationerror() if store_history: self.execution_count += 1 return None except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): self.showsyntaxerror() if store_history: self.execution_count += 1 return None interactivity = "none" if silent else self.ast_node_interactivity self.run_ast_nodes(code_ast.body, cell_name, interactivity=interactivity) # Execute any registered post-execution functions. # unless we are silent post_exec = [] if silent else self._post_execute.iteritems() for func, status in post_exec: if self.disable_failing_post_execute and not status: continue try: func() except KeyboardInterrupt: print >> io.stderr, "\nKeyboardInterrupt" except Exception: # register as failing: self._post_execute[func] = False self.showtraceback() print >> io.stderr, '\n'.join([ "post-execution function %r produced an error." % func, "If this problem persists, you can disable failing post-exec functions with:", "", " get_ipython().disable_failing_post_execute = True" ]) 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
def run_cell(self, raw_cell, store_history=False, silent=False): """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-effets, such as implicit displayhooks, history, and logging. silent=True forces store_history=False. """ if (not raw_cell) or raw_cell.isspace(): return if silent: store_history = False self.input_splitter.push(raw_cell) # Check for cell magics, which leave state behind. This interface is # ugly, we need to do something cleaner later... Now the logic is # simply that the input_splitter remembers if there was a cell magic, # and in that case we grab the cell body. if self.input_splitter.cell_magic_parts: self._current_cell_magic_body = \ ''.join(self.input_splitter.cell_magic_parts) cell = self.input_splitter.source_reset() with self.builtin_trap: prefilter_failed = False if len(cell.splitlines()) == 1: try: # use prefilter_lines to handle trailing newlines # restore trailing newline for ast.parse cell = self.prefilter_manager.prefilter_lines(cell) + '\n' except AliasError as e: error(e) prefilter_failed = True except Exception: # don't allow prefilter errors to crash IPython self.showtraceback() prefilter_failed = True # 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) if not prefilter_failed: # don't run if prefilter failed cell_name = self.compile.cache(cell, self.execution_count) with self.display_trap: try: code_ast = self.compile.ast_parse(cell, filename=cell_name) except IndentationError: self.showindentationerror() if store_history: self.execution_count += 1 return None except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): self.showsyntaxerror() if store_history: self.execution_count += 1 return None interactivity = "none" if silent else self.ast_node_interactivity self.run_ast_nodes(code_ast.body, cell_name, interactivity=interactivity) # Execute any registered post-execution functions. # unless we are silent post_exec = [] if silent else self._post_execute.iteritems() for func, status in post_exec: if self.disable_failing_post_execute and not status: continue try: func() except KeyboardInterrupt: print >> io.stderr, "\nKeyboardInterrupt" except Exception: # register as failing: self._post_execute[func] = False self.showtraceback() print >> io.stderr, '\n'.join([ "post-execution function %r produced an error." % func, "If this problem persists, you can disable failing post-exec functions with:", "", " get_ipython().disable_failing_post_execute = True" ]) 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
[ "Run", "a", "complete", "IPython", "cell", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2516-L2621
[ "def", "run_cell", "(", "self", ",", "raw_cell", ",", "store_history", "=", "False", ",", "silent", "=", "False", ")", ":", "if", "(", "not", "raw_cell", ")", "or", "raw_cell", ".", "isspace", "(", ")", ":", "return", "if", "silent", ":", "store_history", "=", "False", "self", ".", "input_splitter", ".", "push", "(", "raw_cell", ")", "# Check for cell magics, which leave state behind. This interface is", "# ugly, we need to do something cleaner later... Now the logic is", "# simply that the input_splitter remembers if there was a cell magic,", "# and in that case we grab the cell body.", "if", "self", ".", "input_splitter", ".", "cell_magic_parts", ":", "self", ".", "_current_cell_magic_body", "=", "''", ".", "join", "(", "self", ".", "input_splitter", ".", "cell_magic_parts", ")", "cell", "=", "self", ".", "input_splitter", ".", "source_reset", "(", ")", "with", "self", ".", "builtin_trap", ":", "prefilter_failed", "=", "False", "if", "len", "(", "cell", ".", "splitlines", "(", ")", ")", "==", "1", ":", "try", ":", "# use prefilter_lines to handle trailing newlines", "# restore trailing newline for ast.parse", "cell", "=", "self", ".", "prefilter_manager", ".", "prefilter_lines", "(", "cell", ")", "+", "'\\n'", "except", "AliasError", "as", "e", ":", "error", "(", "e", ")", "prefilter_failed", "=", "True", "except", "Exception", ":", "# don't allow prefilter errors to crash IPython", "self", ".", "showtraceback", "(", ")", "prefilter_failed", "=", "True", "# 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", ")", "if", "not", "prefilter_failed", ":", "# don't run if prefilter failed", "cell_name", "=", "self", ".", "compile", ".", "cache", "(", "cell", ",", "self", ".", "execution_count", ")", "with", "self", ".", "display_trap", ":", "try", ":", "code_ast", "=", "self", ".", "compile", ".", "ast_parse", "(", "cell", ",", "filename", "=", "cell_name", ")", "except", "IndentationError", ":", "self", ".", "showindentationerror", "(", ")", "if", "store_history", ":", "self", ".", "execution_count", "+=", "1", "return", "None", "except", "(", "OverflowError", ",", "SyntaxError", ",", "ValueError", ",", "TypeError", ",", "MemoryError", ")", ":", "self", ".", "showsyntaxerror", "(", ")", "if", "store_history", ":", "self", ".", "execution_count", "+=", "1", "return", "None", "interactivity", "=", "\"none\"", "if", "silent", "else", "self", ".", "ast_node_interactivity", "self", ".", "run_ast_nodes", "(", "code_ast", ".", "body", ",", "cell_name", ",", "interactivity", "=", "interactivity", ")", "# Execute any registered post-execution functions.", "# unless we are silent", "post_exec", "=", "[", "]", "if", "silent", "else", "self", ".", "_post_execute", ".", "iteritems", "(", ")", "for", "func", ",", "status", "in", "post_exec", ":", "if", "self", ".", "disable_failing_post_execute", "and", "not", "status", ":", "continue", "try", ":", "func", "(", ")", "except", "KeyboardInterrupt", ":", "print", ">>", "io", ".", "stderr", ",", "\"\\nKeyboardInterrupt\"", "except", "Exception", ":", "# register as failing:", "self", ".", "_post_execute", "[", "func", "]", "=", "False", "self", ".", "showtraceback", "(", ")", "print", ">>", "io", ".", "stderr", ",", "'\\n'", ".", "join", "(", "[", "\"post-execution function %r produced an error.\"", "%", "func", ",", "\"If this problem persists, you can disable failing post-exec functions with:\"", ",", "\"\"", ",", "\" get_ipython().disable_failing_post_execute = True\"", "]", ")", "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" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.run_ast_nodes
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' 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. Other values for this parameter will raise a ValueError.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): """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' 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. Other values for this parameter will raise a ValueError. """ if not nodelist: return 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) exec_count = self.execution_count try: for i, node in enumerate(to_run_exec): mod = ast.Module([node]) code = self.compile(mod, cell_name, "exec") if self.run_code(code): return True for i, node in enumerate(to_run_interactive): mod = ast.Interactive([node]) code = self.compile(mod, cell_name, "single") if self.run_code(code): 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. self.showtraceback() return False
def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): """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' 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. Other values for this parameter will raise a ValueError. """ if not nodelist: return 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) exec_count = self.execution_count try: for i, node in enumerate(to_run_exec): mod = ast.Module([node]) code = self.compile(mod, cell_name, "exec") if self.run_code(code): return True for i, node in enumerate(to_run_interactive): mod = ast.Interactive([node]) code = self.compile(mod, cell_name, "single") if self.run_code(code): 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. self.showtraceback() return False
[ "Run", "a", "sequence", "of", "AST", "nodes", ".", "The", "execution", "mode", "depends", "on", "the", "interactivity", "parameter", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2623-L2690
[ "def", "run_ast_nodes", "(", "self", ",", "nodelist", ",", "cell_name", ",", "interactivity", "=", "'last_expr'", ")", ":", "if", "not", "nodelist", ":", "return", "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", ")", "exec_count", "=", "self", ".", "execution_count", "try", ":", "for", "i", ",", "node", "in", "enumerate", "(", "to_run_exec", ")", ":", "mod", "=", "ast", ".", "Module", "(", "[", "node", "]", ")", "code", "=", "self", ".", "compile", "(", "mod", ",", "cell_name", ",", "\"exec\"", ")", "if", "self", ".", "run_code", "(", "code", ")", ":", "return", "True", "for", "i", ",", "node", "in", "enumerate", "(", "to_run_interactive", ")", ":", "mod", "=", "ast", ".", "Interactive", "(", "[", "node", "]", ")", "code", "=", "self", ".", "compile", "(", "mod", ",", "cell_name", ",", "\"single\"", ")", "if", "self", ".", "run_code", "(", "code", ")", ":", "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.", "self", ".", "showtraceback", "(", ")", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.run_code
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 Returns ------- False : successful execution. True : an error occurred.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def run_code(self, code_obj): """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 Returns ------- False : successful execution. True : an error occurred. """ # 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 = 1 # happens in more places, so it's easier as default try: try: self.hooks.pre_run_code_hook() #rprint('Running code', repr(code_obj)) # dbg exec code_obj in self.user_global_ns, self.user_ns finally: # Reset our crash handler in place sys.excepthook = old_excepthook except SystemExit: self.showtraceback(exception_only=True) warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) except self.custom_exceptions: etype,value,tb = sys.exc_info() self.CustomTB(etype,value,tb) except: self.showtraceback() else: outflag = 0 return outflag
def run_code(self, code_obj): """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 Returns ------- False : successful execution. True : an error occurred. """ # 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 = 1 # happens in more places, so it's easier as default try: try: self.hooks.pre_run_code_hook() #rprint('Running code', repr(code_obj)) # dbg exec code_obj in self.user_global_ns, self.user_ns finally: # Reset our crash handler in place sys.excepthook = old_excepthook except SystemExit: self.showtraceback(exception_only=True) warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) except self.custom_exceptions: etype,value,tb = sys.exc_info() self.CustomTB(etype,value,tb) except: self.showtraceback() else: outflag = 0 return outflag
[ "Execute", "a", "code", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2692-L2735
[ "def", "run_code", "(", "self", ",", "code_obj", ")", ":", "# 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", "=", "1", "# happens in more places, so it's easier as default", "try", ":", "try", ":", "self", ".", "hooks", ".", "pre_run_code_hook", "(", ")", "#rprint('Running code', repr(code_obj)) # dbg", "exec", "code_obj", "in", "self", ".", "user_global_ns", ",", "self", ".", "user_ns", "finally", ":", "# Reset our crash handler in place", "sys", ".", "excepthook", "=", "old_excepthook", "except", "SystemExit", ":", "self", ".", "showtraceback", "(", "exception_only", "=", "True", ")", "warn", "(", "\"To exit: use 'exit', 'quit', or Ctrl-D.\"", ",", "level", "=", "1", ")", "except", "self", ".", "custom_exceptions", ":", "etype", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "self", ".", "CustomTB", "(", "etype", ",", "value", ",", "tb", ")", "except", ":", "self", ".", "showtraceback", "(", ")", "else", ":", "outflag", "=", "0", "return", "outflag" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.enable_pylab
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 :param:`gui` argument. 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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def enable_pylab(self, gui=None, import_all=True): """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 :param:`gui` argument. 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 IPython.core.pylabtools import mpl_runner # 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 = {} try: gui = pylab_activate(ns, gui, import_all, self) except KeyError: error("Backend %r not supported" % gui) return self.user_ns.update(ns) self.user_ns_hidden.update(ns) # 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 = \ mpl_runner(self.safe_execfile)
def enable_pylab(self, gui=None, import_all=True): """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 :param:`gui` argument. 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 IPython.core.pylabtools import mpl_runner # 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 = {} try: gui = pylab_activate(ns, gui, import_all, self) except KeyError: error("Backend %r not supported" % gui) return self.user_ns.update(ns) self.user_ns_hidden.update(ns) # 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 = \ mpl_runner(self.safe_execfile)
[ "Activate", "pylab", "support", "at", "runtime", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2747-L2784
[ "def", "enable_pylab", "(", "self", ",", "gui", "=", "None", ",", "import_all", "=", "True", ")", ":", "from", "IPython", ".", "core", ".", "pylabtools", "import", "mpl_runner", "# 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", "=", "{", "}", "try", ":", "gui", "=", "pylab_activate", "(", "ns", ",", "gui", ",", "import_all", ",", "self", ")", "except", "KeyError", ":", "error", "(", "\"Backend %r not supported\"", "%", "gui", ")", "return", "self", ".", "user_ns", ".", "update", "(", "ns", ")", "self", ".", "user_ns_hidden", ".", "update", "(", "ns", ")", "# 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", "=", "mpl_runner", "(", "self", ".", "safe_execfile", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.var_expand
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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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() ns.update(sys._getframe(depth+1).f_locals) ns.pop('self', None) try: cmd = formatter.format(cmd, **ns) except Exception: # if formatter couldn't format, just let it go untransformed pass return cmd
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() ns.update(sys._getframe(depth+1).f_locals) ns.pop('self', None) try: cmd = formatter.format(cmd, **ns) except Exception: # if formatter couldn't format, just let it go untransformed pass return cmd
[ "Expand", "python", "variables", "in", "a", "string", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2790-L2807
[ "def", "var_expand", "(", "self", ",", "cmd", ",", "depth", "=", "0", ",", "formatter", "=", "DollarFormatter", "(", ")", ")", ":", "ns", "=", "self", ".", "user_ns", ".", "copy", "(", ")", "ns", ".", "update", "(", "sys", ".", "_getframe", "(", "depth", "+", "1", ")", ".", "f_locals", ")", "ns", ".", "pop", "(", "'self'", ",", "None", ")", "try", ":", "cmd", "=", "formatter", ".", "format", "(", "cmd", ",", "*", "*", "ns", ")", "except", "Exception", ":", "# if formatter couldn't format, just let it go untransformed", "pass", "return", "cmd" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.mktempfile
Make a new tempfile and return its filename. This makes a call to tempfile.mktemp, 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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def mktempfile(self, data=None, prefix='ipython_edit_'): """Make a new tempfile and return its filename. This makes a call to tempfile.mktemp, 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.""" filename = tempfile.mktemp('.py', prefix) self.tempfiles.append(filename) if data: tmp_file = open(filename,'w') tmp_file.write(data) tmp_file.close() return filename
def mktempfile(self, data=None, prefix='ipython_edit_'): """Make a new tempfile and return its filename. This makes a call to tempfile.mktemp, 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.""" filename = tempfile.mktemp('.py', prefix) self.tempfiles.append(filename) if data: tmp_file = open(filename,'w') tmp_file.write(data) tmp_file.close() return filename
[ "Make", "a", "new", "tempfile", "and", "return", "its", "filename", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2809-L2827
[ "def", "mktempfile", "(", "self", ",", "data", "=", "None", ",", "prefix", "=", "'ipython_edit_'", ")", ":", "filename", "=", "tempfile", ".", "mktemp", "(", "'.py'", ",", "prefix", ")", "self", ".", "tempfiles", ".", "append", "(", "filename", ")", "if", "data", ":", "tmp_file", "=", "open", "(", "filename", ",", "'w'", ")", "tmp_file", ".", "write", "(", "data", ")", "tmp_file", ".", "close", "(", ")", "return", "filename" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.extract_input_lines
Return as a string a set of input history slices. Parameters ---------- range_str : string 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. Optional Parameters: - raw(False): by default, the processed input is used. If this is true, the raw input history is used instead. Note that slices can be called with two notations: N:M -> standard python form, means including items N...(M-1). N-M -> include items N..M (closed endpoint).
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def extract_input_lines(self, range_str, raw=False): """Return as a string a set of input history slices. Parameters ---------- range_str : string 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. Optional Parameters: - raw(False): by default, the processed input is used. If this is true, the raw input history is used instead. Note that slices can be called 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) return "\n".join(x for _, _, x in lines)
def extract_input_lines(self, range_str, raw=False): """Return as a string a set of input history slices. Parameters ---------- range_str : string 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. Optional Parameters: - raw(False): by default, the processed input is used. If this is true, the raw input history is used instead. Note that slices can be called 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) return "\n".join(x for _, _, x in lines)
[ "Return", "as", "a", "string", "a", "set", "of", "input", "history", "slices", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2848-L2869
[ "def", "extract_input_lines", "(", "self", ",", "range_str", ",", "raw", "=", "False", ")", ":", "lines", "=", "self", ".", "history_manager", ".", "get_range_by_str", "(", "range_str", ",", "raw", "=", "raw", ")", "return", "\"\\n\"", ".", "join", "(", "x", "for", "_", ",", "_", ",", "x", "in", "lines", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.find_user_code
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, correspnding .py file, filename, or an expression evaluating to a string or Macro in the user namespace. 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.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def find_user_code(self, target, raw=True, py_only=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, correspnding .py file, filename, or an expression evaluating to a string or Macro in the user namespace. 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 utarget = unquote_filename(target) try: if utarget.startswith(('http://', 'https://')): return openpy.read_py_url(utarget, skip_encoding_cookie=True) except UnicodeDecodeError: if not py_only : response = urllib.urlopen(target) return response.read().decode('latin1') raise ValueError(("'%s' seem to be unreadable.") % utarget) 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=True) except UnicodeDecodeError : if not py_only : with io_open(tgt,'r', encoding='latin1') as f : return f.read() raise ValueError(("'%s' seem to be unreadable.") % target) try: # User namespace codeobj = eval(target, self.user_ns) except Exception: raise ValueError(("'%s' was not found in history, as a file, url, " "nor in the user namespace.") % target) if isinstance(codeobj, basestring): return codeobj elif isinstance(codeobj, Macro): return codeobj.value raise TypeError("%s is neither a string nor a macro." % target, codeobj)
def find_user_code(self, target, raw=True, py_only=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, correspnding .py file, filename, or an expression evaluating to a string or Macro in the user namespace. 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 utarget = unquote_filename(target) try: if utarget.startswith(('http://', 'https://')): return openpy.read_py_url(utarget, skip_encoding_cookie=True) except UnicodeDecodeError: if not py_only : response = urllib.urlopen(target) return response.read().decode('latin1') raise ValueError(("'%s' seem to be unreadable.") % utarget) 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=True) except UnicodeDecodeError : if not py_only : with io_open(tgt,'r', encoding='latin1') as f : return f.read() raise ValueError(("'%s' seem to be unreadable.") % target) try: # User namespace codeobj = eval(target, self.user_ns) except Exception: raise ValueError(("'%s' was not found in history, as a file, url, " "nor in the user namespace.") % target) if isinstance(codeobj, basestring): return codeobj elif isinstance(codeobj, Macro): return codeobj.value raise TypeError("%s is neither a string nor a macro." % target, codeobj)
[ "Get", "a", "code", "string", "from", "history", "file", "url", "or", "a", "string", "or", "macro", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2871-L2942
[ "def", "find_user_code", "(", "self", ",", "target", ",", "raw", "=", "True", ",", "py_only", "=", "False", ")", ":", "code", "=", "self", ".", "extract_input_lines", "(", "target", ",", "raw", "=", "raw", ")", "# Grab history", "if", "code", ":", "return", "code", "utarget", "=", "unquote_filename", "(", "target", ")", "try", ":", "if", "utarget", ".", "startswith", "(", "(", "'http://'", ",", "'https://'", ")", ")", ":", "return", "openpy", ".", "read_py_url", "(", "utarget", ",", "skip_encoding_cookie", "=", "True", ")", "except", "UnicodeDecodeError", ":", "if", "not", "py_only", ":", "response", "=", "urllib", ".", "urlopen", "(", "target", ")", "return", "response", ".", "read", "(", ")", ".", "decode", "(", "'latin1'", ")", "raise", "ValueError", "(", "(", "\"'%s' seem to be unreadable.\"", ")", "%", "utarget", ")", "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", "=", "True", ")", "except", "UnicodeDecodeError", ":", "if", "not", "py_only", ":", "with", "io_open", "(", "tgt", ",", "'r'", ",", "encoding", "=", "'latin1'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "raise", "ValueError", "(", "(", "\"'%s' seem to be unreadable.\"", ")", "%", "target", ")", "try", ":", "# User namespace", "codeobj", "=", "eval", "(", "target", ",", "self", ".", "user_ns", ")", "except", "Exception", ":", "raise", "ValueError", "(", "(", "\"'%s' was not found in history, as a file, url, \"", "\"nor in the user namespace.\"", ")", "%", "target", ")", "if", "isinstance", "(", "codeobj", ",", "basestring", ")", ":", "return", "codeobj", "elif", "isinstance", "(", "codeobj", ",", "Macro", ")", ":", "return", "codeobj", ".", "value", "raise", "TypeError", "(", "\"%s is neither a string nor a macro.\"", "%", "target", ",", "codeobj", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.atexit_operations
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
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
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 """ # 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() # Cleanup all tempfiles left around for tfile in self.tempfiles: try: os.unlink(tfile) except OSError: pass # Clear all user namespaces to release all references cleanly. self.reset(new_session=False) # Run user hooks self.hooks.shutdown_hook()
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 """ # 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() # Cleanup all tempfiles left around for tfile in self.tempfiles: try: os.unlink(tfile) except OSError: pass # Clear all user namespaces to release all references cleanly. self.reset(new_session=False) # Run user hooks self.hooks.shutdown_hook()
[ "This", "will", "be", "executed", "at", "the", "time", "of", "exit", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L2947-L2974
[ "def", "atexit_operations", "(", "self", ")", ":", "# 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", "(", ")", "# Cleanup all tempfiles left around", "for", "tfile", "in", "self", ".", "tempfiles", ":", "try", ":", "os", ".", "unlink", "(", "tfile", ")", "except", "OSError", ":", "pass", "# Clear all user namespaces to release all references cleanly.", "self", ".", "reset", "(", "new_session", "=", "False", ")", "# Run user hooks", "self", ".", "hooks", ".", "shutdown_hook", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
broadcast
broadcast a message from one engine to all others.
environment/share/doc/ipython/examples/parallel/interengine/interengine.py
def broadcast(client, sender, msg_name, dest_name=None, block=None): """broadcast a message from one engine to all others.""" dest_name = msg_name if dest_name is None else dest_name client[sender].execute('com.publish(%s)'%msg_name, block=None) targets = client.ids targets.remove(sender) return client[targets].execute('%s=com.consume()'%dest_name, block=None)
def broadcast(client, sender, msg_name, dest_name=None, block=None): """broadcast a message from one engine to all others.""" dest_name = msg_name if dest_name is None else dest_name client[sender].execute('com.publish(%s)'%msg_name, block=None) targets = client.ids targets.remove(sender) return client[targets].execute('%s=com.consume()'%dest_name, block=None)
[ "broadcast", "a", "message", "from", "one", "engine", "to", "all", "others", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/interengine.py#L22-L28
[ "def", "broadcast", "(", "client", ",", "sender", ",", "msg_name", ",", "dest_name", "=", "None", ",", "block", "=", "None", ")", ":", "dest_name", "=", "msg_name", "if", "dest_name", "is", "None", "else", "dest_name", "client", "[", "sender", "]", ".", "execute", "(", "'com.publish(%s)'", "%", "msg_name", ",", "block", "=", "None", ")", "targets", "=", "client", ".", "ids", "targets", ".", "remove", "(", "sender", ")", "return", "client", "[", "targets", "]", ".", "execute", "(", "'%s=com.consume()'", "%", "dest_name", ",", "block", "=", "None", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
send
send a message from one to one-or-more engines.
environment/share/doc/ipython/examples/parallel/interengine/interengine.py
def send(client, sender, targets, msg_name, dest_name=None, block=None): """send a message from one to one-or-more engines.""" dest_name = msg_name if dest_name is None else dest_name def _send(targets, m_name): msg = globals()[m_name] return com.send(targets, msg) client[sender].apply_async(_send, targets, msg_name) return client[targets].execute('%s=com.recv()'%dest_name, block=None)
def send(client, sender, targets, msg_name, dest_name=None, block=None): """send a message from one to one-or-more engines.""" dest_name = msg_name if dest_name is None else dest_name def _send(targets, m_name): msg = globals()[m_name] return com.send(targets, msg) client[sender].apply_async(_send, targets, msg_name) return client[targets].execute('%s=com.recv()'%dest_name, block=None)
[ "send", "a", "message", "from", "one", "to", "one", "-", "or", "-", "more", "engines", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/interengine.py#L30-L39
[ "def", "send", "(", "client", ",", "sender", ",", "targets", ",", "msg_name", ",", "dest_name", "=", "None", ",", "block", "=", "None", ")", ":", "dest_name", "=", "msg_name", "if", "dest_name", "is", "None", "else", "dest_name", "def", "_send", "(", "targets", ",", "m_name", ")", ":", "msg", "=", "globals", "(", ")", "[", "m_name", "]", "return", "com", ".", "send", "(", "targets", ",", "msg", ")", "client", "[", "sender", "]", ".", "apply_async", "(", "_send", ",", "targets", ",", "msg_name", ")", "return", "client", "[", "targets", "]", ".", "execute", "(", "'%s=com.recv()'", "%", "dest_name", ",", "block", "=", "None", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
skipif
Make function raise SkipTest exception if a given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- skip_condition : bool or callable Flag to determine whether to skip the decorated test. msg : str, optional Message to give on raising a SkipTest exception. Default is None. Returns ------- decorator : function Decorator which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata.
environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py
def skipif(skip_condition, msg=None): """ Make function raise SkipTest exception if a given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- skip_condition : bool or callable Flag to determine whether to skip the decorated test. msg : str, optional Message to give on raising a SkipTest exception. Default is None. Returns ------- decorator : function Decorator which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ def skip_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose # Allow for both boolean or callable skip conditions. if callable(skip_condition): skip_val = lambda : skip_condition() else: skip_val = lambda : skip_condition def get_msg(func,msg=None): """Skip message with information about function being skipped.""" if msg is None: out = 'Test skipped due to test condition' else: out = '\n'+msg return "Skipping test: %s%s" % (func.__name__,out) # We need to define *two* skippers because Python doesn't allow both # return with value and yield inside the same function. def skipper_func(*args, **kwargs): """Skipper for normal test functions.""" if skip_val(): raise nose.SkipTest(get_msg(f,msg)) else: return f(*args, **kwargs) def skipper_gen(*args, **kwargs): """Skipper for test generators.""" if skip_val(): raise nose.SkipTest(get_msg(f,msg)) else: for x in f(*args, **kwargs): yield x # Choose the right skipper to use when building the actual decorator. if nose.util.isgenerator(f): skipper = skipper_gen else: skipper = skipper_func return nose.tools.make_decorator(f)(skipper) return skip_decorator
def skipif(skip_condition, msg=None): """ Make function raise SkipTest exception if a given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- skip_condition : bool or callable Flag to determine whether to skip the decorated test. msg : str, optional Message to give on raising a SkipTest exception. Default is None. Returns ------- decorator : function Decorator which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ def skip_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose # Allow for both boolean or callable skip conditions. if callable(skip_condition): skip_val = lambda : skip_condition() else: skip_val = lambda : skip_condition def get_msg(func,msg=None): """Skip message with information about function being skipped.""" if msg is None: out = 'Test skipped due to test condition' else: out = '\n'+msg return "Skipping test: %s%s" % (func.__name__,out) # We need to define *two* skippers because Python doesn't allow both # return with value and yield inside the same function. def skipper_func(*args, **kwargs): """Skipper for normal test functions.""" if skip_val(): raise nose.SkipTest(get_msg(f,msg)) else: return f(*args, **kwargs) def skipper_gen(*args, **kwargs): """Skipper for test generators.""" if skip_val(): raise nose.SkipTest(get_msg(f,msg)) else: for x in f(*args, **kwargs): yield x # Choose the right skipper to use when building the actual decorator. if nose.util.isgenerator(f): skipper = skipper_gen else: skipper = skipper_func return nose.tools.make_decorator(f)(skipper) return skip_decorator
[ "Make", "function", "raise", "SkipTest", "exception", "if", "a", "given", "condition", "is", "true", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py#L99-L173
[ "def", "skipif", "(", "skip_condition", ",", "msg", "=", "None", ")", ":", "def", "skip_decorator", "(", "f", ")", ":", "# Local import to avoid a hard nose dependency and only incur the", "# import time overhead at actual test-time.", "import", "nose", "# Allow for both boolean or callable skip conditions.", "if", "callable", "(", "skip_condition", ")", ":", "skip_val", "=", "lambda", ":", "skip_condition", "(", ")", "else", ":", "skip_val", "=", "lambda", ":", "skip_condition", "def", "get_msg", "(", "func", ",", "msg", "=", "None", ")", ":", "\"\"\"Skip message with information about function being skipped.\"\"\"", "if", "msg", "is", "None", ":", "out", "=", "'Test skipped due to test condition'", "else", ":", "out", "=", "'\\n'", "+", "msg", "return", "\"Skipping test: %s%s\"", "%", "(", "func", ".", "__name__", ",", "out", ")", "# We need to define *two* skippers because Python doesn't allow both", "# return with value and yield inside the same function.", "def", "skipper_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Skipper for normal test functions.\"\"\"", "if", "skip_val", "(", ")", ":", "raise", "nose", ".", "SkipTest", "(", "get_msg", "(", "f", ",", "msg", ")", ")", "else", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "def", "skipper_gen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Skipper for test generators.\"\"\"", "if", "skip_val", "(", ")", ":", "raise", "nose", ".", "SkipTest", "(", "get_msg", "(", "f", ",", "msg", ")", ")", "else", ":", "for", "x", "in", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "yield", "x", "# Choose the right skipper to use when building the actual decorator.", "if", "nose", ".", "util", ".", "isgenerator", "(", "f", ")", ":", "skipper", "=", "skipper_gen", "else", ":", "skipper", "=", "skipper_func", "return", "nose", ".", "tools", ".", "make_decorator", "(", "f", ")", "(", "skipper", ")", "return", "skip_decorator" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
knownfailureif
Make function raise KnownFailureTest exception if given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- fail_condition : bool or callable Flag to determine whether to mark the decorated test as a known failure (if True) or not (if False). msg : str, optional Message to give on raising a KnownFailureTest exception. Default is None. Returns ------- decorator : function Decorator, which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata.
environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py
def knownfailureif(fail_condition, msg=None): """ Make function raise KnownFailureTest exception if given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- fail_condition : bool or callable Flag to determine whether to mark the decorated test as a known failure (if True) or not (if False). msg : str, optional Message to give on raising a KnownFailureTest exception. Default is None. Returns ------- decorator : function Decorator, which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ if msg is None: msg = 'Test skipped due to known failure' # Allow for both boolean or callable known failure conditions. if callable(fail_condition): fail_val = lambda : fail_condition() else: fail_val = lambda : fail_condition def knownfail_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose def knownfailer(*args, **kwargs): if fail_val(): raise KnownFailureTest, msg else: return f(*args, **kwargs) return nose.tools.make_decorator(f)(knownfailer) return knownfail_decorator
def knownfailureif(fail_condition, msg=None): """ Make function raise KnownFailureTest exception if given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- fail_condition : bool or callable Flag to determine whether to mark the decorated test as a known failure (if True) or not (if False). msg : str, optional Message to give on raising a KnownFailureTest exception. Default is None. Returns ------- decorator : function Decorator, which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ if msg is None: msg = 'Test skipped due to known failure' # Allow for both boolean or callable known failure conditions. if callable(fail_condition): fail_val = lambda : fail_condition() else: fail_val = lambda : fail_condition def knownfail_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose def knownfailer(*args, **kwargs): if fail_val(): raise KnownFailureTest, msg else: return f(*args, **kwargs) return nose.tools.make_decorator(f)(knownfailer) return knownfail_decorator
[ "Make", "function", "raise", "KnownFailureTest", "exception", "if", "given", "condition", "is", "true", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py#L175-L225
[ "def", "knownfailureif", "(", "fail_condition", ",", "msg", "=", "None", ")", ":", "if", "msg", "is", "None", ":", "msg", "=", "'Test skipped due to known failure'", "# Allow for both boolean or callable known failure conditions.", "if", "callable", "(", "fail_condition", ")", ":", "fail_val", "=", "lambda", ":", "fail_condition", "(", ")", "else", ":", "fail_val", "=", "lambda", ":", "fail_condition", "def", "knownfail_decorator", "(", "f", ")", ":", "# Local import to avoid a hard nose dependency and only incur the", "# import time overhead at actual test-time.", "import", "nose", "def", "knownfailer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "fail_val", "(", ")", ":", "raise", "KnownFailureTest", ",", "msg", "else", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "nose", ".", "tools", ".", "make_decorator", "(", "f", ")", "(", "knownfailer", ")", "return", "knownfail_decorator" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
deprecated
Filter deprecation warnings while running the test suite. This decorator can be used to filter DeprecationWarning's, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning. Parameters ---------- conditional : bool or callable, optional Flag to determine whether to mark test as deprecated or not. If the condition is a callable, it is used at runtime to dynamically make the decision. Default is True. Returns ------- decorator : function The `deprecated` decorator itself. Notes ----- .. versionadded:: 1.4.0
environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py
def deprecated(conditional=True): """ Filter deprecation warnings while running the test suite. This decorator can be used to filter DeprecationWarning's, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning. Parameters ---------- conditional : bool or callable, optional Flag to determine whether to mark test as deprecated or not. If the condition is a callable, it is used at runtime to dynamically make the decision. Default is True. Returns ------- decorator : function The `deprecated` decorator itself. Notes ----- .. versionadded:: 1.4.0 """ def deprecate_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose def _deprecated_imp(*args, **kwargs): # Poor man's replacement for the with statement ctx = WarningManager(record=True) l = ctx.__enter__() warnings.simplefilter('always') try: f(*args, **kwargs) if not len(l) > 0: raise AssertionError("No warning raised when calling %s" % f.__name__) if not l[0].category is DeprecationWarning: raise AssertionError("First warning for %s is not a " \ "DeprecationWarning( is %s)" % (f.__name__, l[0])) finally: ctx.__exit__() if callable(conditional): cond = conditional() else: cond = conditional if cond: return nose.tools.make_decorator(f)(_deprecated_imp) else: return f return deprecate_decorator
def deprecated(conditional=True): """ Filter deprecation warnings while running the test suite. This decorator can be used to filter DeprecationWarning's, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning. Parameters ---------- conditional : bool or callable, optional Flag to determine whether to mark test as deprecated or not. If the condition is a callable, it is used at runtime to dynamically make the decision. Default is True. Returns ------- decorator : function The `deprecated` decorator itself. Notes ----- .. versionadded:: 1.4.0 """ def deprecate_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose def _deprecated_imp(*args, **kwargs): # Poor man's replacement for the with statement ctx = WarningManager(record=True) l = ctx.__enter__() warnings.simplefilter('always') try: f(*args, **kwargs) if not len(l) > 0: raise AssertionError("No warning raised when calling %s" % f.__name__) if not l[0].category is DeprecationWarning: raise AssertionError("First warning for %s is not a " \ "DeprecationWarning( is %s)" % (f.__name__, l[0])) finally: ctx.__exit__() if callable(conditional): cond = conditional() else: cond = conditional if cond: return nose.tools.make_decorator(f)(_deprecated_imp) else: return f return deprecate_decorator
[ "Filter", "deprecation", "warnings", "while", "running", "the", "test", "suite", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py#L227-L281
[ "def", "deprecated", "(", "conditional", "=", "True", ")", ":", "def", "deprecate_decorator", "(", "f", ")", ":", "# Local import to avoid a hard nose dependency and only incur the", "# import time overhead at actual test-time.", "import", "nose", "def", "_deprecated_imp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Poor man's replacement for the with statement", "ctx", "=", "WarningManager", "(", "record", "=", "True", ")", "l", "=", "ctx", ".", "__enter__", "(", ")", "warnings", ".", "simplefilter", "(", "'always'", ")", "try", ":", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "len", "(", "l", ")", ">", "0", ":", "raise", "AssertionError", "(", "\"No warning raised when calling %s\"", "%", "f", ".", "__name__", ")", "if", "not", "l", "[", "0", "]", ".", "category", "is", "DeprecationWarning", ":", "raise", "AssertionError", "(", "\"First warning for %s is not a \"", "\"DeprecationWarning( is %s)\"", "%", "(", "f", ".", "__name__", ",", "l", "[", "0", "]", ")", ")", "finally", ":", "ctx", ".", "__exit__", "(", ")", "if", "callable", "(", "conditional", ")", ":", "cond", "=", "conditional", "(", ")", "else", ":", "cond", "=", "conditional", "if", "cond", ":", "return", "nose", ".", "tools", ".", "make_decorator", "(", "f", ")", "(", "_deprecated_imp", ")", "else", ":", "return", "f", "return", "deprecate_decorator" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
list_profiles_in
list profiles in a given root directory
environment/lib/python2.7/site-packages/IPython/core/profileapp.py
def list_profiles_in(path): """list profiles in a given root directory""" files = os.listdir(path) profiles = [] for f in files: full_path = os.path.join(path, f) if os.path.isdir(full_path) and f.startswith('profile_'): profiles.append(f.split('_',1)[-1]) return profiles
def list_profiles_in(path): """list profiles in a given root directory""" files = os.listdir(path) profiles = [] for f in files: full_path = os.path.join(path, f) if os.path.isdir(full_path) and f.startswith('profile_'): profiles.append(f.split('_',1)[-1]) return profiles
[ "list", "profiles", "in", "a", "given", "root", "directory" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/profileapp.py#L97-L105
[ "def", "list_profiles_in", "(", "path", ")", ":", "files", "=", "os", ".", "listdir", "(", "path", ")", "profiles", "=", "[", "]", "for", "f", "in", "files", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "os", ".", "path", ".", "isdir", "(", "full_path", ")", "and", "f", ".", "startswith", "(", "'profile_'", ")", ":", "profiles", ".", "append", "(", "f", ".", "split", "(", "'_'", ",", "1", ")", "[", "-", "1", "]", ")", "return", "profiles" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
list_bundled_profiles
list profiles that are bundled with IPython.
environment/lib/python2.7/site-packages/IPython/core/profileapp.py
def list_bundled_profiles(): """list profiles that are bundled with IPython.""" path = os.path.join(get_ipython_package_dir(), u'config', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if os.path.isdir(full_path) and profile != "__pycache__": profiles.append(profile) return profiles
def list_bundled_profiles(): """list profiles that are bundled with IPython.""" path = os.path.join(get_ipython_package_dir(), u'config', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if os.path.isdir(full_path) and profile != "__pycache__": profiles.append(profile) return profiles
[ "list", "profiles", "that", "are", "bundled", "with", "IPython", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/profileapp.py#L108-L117
[ "def", "list_bundled_profiles", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "get_ipython_package_dir", "(", ")", ",", "u'config'", ",", "u'profile'", ")", "files", "=", "os", ".", "listdir", "(", "path", ")", "profiles", "=", "[", "]", "for", "profile", "in", "files", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "profile", ")", "if", "os", ".", "path", ".", "isdir", "(", "full_path", ")", "and", "profile", "!=", "\"__pycache__\"", ":", "profiles", ".", "append", "(", "profile", ")", "return", "profiles" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
_bypass_ensure_directory
Sandbox-bypassing version of ensure_directory()
virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
def _bypass_ensure_directory(path, mode=0o777): """Sandbox-bypassing version of ensure_directory()""" if not WRITE_SUPPORT: raise IOError('"os.mkdir" not supported on this platform.') dirname, filename = split(path) if dirname and filename and not isdir(dirname): _bypass_ensure_directory(dirname) mkdir(dirname, mode)
def _bypass_ensure_directory(path, mode=0o777): """Sandbox-bypassing version of ensure_directory()""" if not WRITE_SUPPORT: raise IOError('"os.mkdir" not supported on this platform.') dirname, filename = split(path) if dirname and filename and not isdir(dirname): _bypass_ensure_directory(dirname) mkdir(dirname, mode)
[ "Sandbox", "-", "bypassing", "version", "of", "ensure_directory", "()" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L2902-L2909
[ "def", "_bypass_ensure_directory", "(", "path", ",", "mode", "=", "0o777", ")", ":", "if", "not", "WRITE_SUPPORT", ":", "raise", "IOError", "(", "'\"os.mkdir\" not supported on this platform.'", ")", "dirname", ",", "filename", "=", "split", "(", "path", ")", "if", "dirname", "and", "filename", "and", "not", "isdir", "(", "dirname", ")", ":", "_bypass_ensure_directory", "(", "dirname", ")", "mkdir", "(", "dirname", ",", "mode", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
WorkingSet.find
Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned.
virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
def find(self, req): """Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned. """ dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) else: return dist
def find(self, req): """Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned. """ dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) else: return dist
[ "Find", "a", "distribution", "matching", "requirement", "req" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L608-L623
[ "def", "find", "(", "self", ",", "req", ")", ":", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "not", "None", "and", "dist", "not", "in", "req", ":", "# XXX add more info", "raise", "VersionConflict", "(", "dist", ",", "req", ")", "else", ":", "return", "dist" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
WorkingSet.resolve
List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it.
virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
def resolve(self, requirements, env=None, installer=None, replace_conflicting=False): """List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. """ # set up the stack requirements = list(requirements)[::-1] # set of processed requirements processed = {} # key -> dist best = {} to_activate = [] # Mapping of requirement to set of distributions that required it; # useful for reporting info about conflicts. required_by = collections.defaultdict(set) while requirements: # process dependencies breadth-first req = requirements.pop(0) if req in processed: # Ignore cyclic or redundant dependencies continue dist = best.get(req.key) if dist is None: # Find the best distribution and add it to the map dist = self.by_key.get(req.key) if dist is None or (dist not in req and replace_conflicting): ws = self if env is None: if dist is None: env = Environment(self.entries) else: # Use an empty environment and workingset to avoid # any further conflicts with the conflicting # distribution env = Environment([]) ws = WorkingSet([]) dist = best[req.key] = env.best_match(req, ws, installer) if dist is None: #msg = ("The '%s' distribution was not found on this " # "system, and is required by this application.") #raise DistributionNotFound(msg % req) # unfortunately, zc.buildout uses a str(err) # to get the name of the distribution here.. raise DistributionNotFound(req) to_activate.append(dist) if dist not in req: # Oops, the "best" so far conflicts with a dependency tmpl = "%s is installed but %s is required by %s" args = dist, req, list(required_by.get(req, [])) raise VersionConflict(tmpl % args) # push the new requirements onto the stack new_requirements = dist.requires(req.extras)[::-1] requirements.extend(new_requirements) # Register the new requirements needed by req for new_requirement in new_requirements: required_by[new_requirement].add(req.project_name) processed[req] = True # return list of distros to activate return to_activate
def resolve(self, requirements, env=None, installer=None, replace_conflicting=False): """List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. """ # set up the stack requirements = list(requirements)[::-1] # set of processed requirements processed = {} # key -> dist best = {} to_activate = [] # Mapping of requirement to set of distributions that required it; # useful for reporting info about conflicts. required_by = collections.defaultdict(set) while requirements: # process dependencies breadth-first req = requirements.pop(0) if req in processed: # Ignore cyclic or redundant dependencies continue dist = best.get(req.key) if dist is None: # Find the best distribution and add it to the map dist = self.by_key.get(req.key) if dist is None or (dist not in req and replace_conflicting): ws = self if env is None: if dist is None: env = Environment(self.entries) else: # Use an empty environment and workingset to avoid # any further conflicts with the conflicting # distribution env = Environment([]) ws = WorkingSet([]) dist = best[req.key] = env.best_match(req, ws, installer) if dist is None: #msg = ("The '%s' distribution was not found on this " # "system, and is required by this application.") #raise DistributionNotFound(msg % req) # unfortunately, zc.buildout uses a str(err) # to get the name of the distribution here.. raise DistributionNotFound(req) to_activate.append(dist) if dist not in req: # Oops, the "best" so far conflicts with a dependency tmpl = "%s is installed but %s is required by %s" args = dist, req, list(required_by.get(req, [])) raise VersionConflict(tmpl % args) # push the new requirements onto the stack new_requirements = dist.requires(req.extras)[::-1] requirements.extend(new_requirements) # Register the new requirements needed by req for new_requirement in new_requirements: required_by[new_requirement].add(req.project_name) processed[req] = True # return list of distros to activate return to_activate
[ "List", "all", "distributions", "needed", "to", "(", "recursively", ")", "meet", "requirements" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L695-L774
[ "def", "resolve", "(", "self", ",", "requirements", ",", "env", "=", "None", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ")", ":", "# set up the stack", "requirements", "=", "list", "(", "requirements", ")", "[", ":", ":", "-", "1", "]", "# set of processed requirements", "processed", "=", "{", "}", "# key -> dist", "best", "=", "{", "}", "to_activate", "=", "[", "]", "# Mapping of requirement to set of distributions that required it;", "# useful for reporting info about conflicts.", "required_by", "=", "collections", ".", "defaultdict", "(", "set", ")", "while", "requirements", ":", "# process dependencies breadth-first", "req", "=", "requirements", ".", "pop", "(", "0", ")", "if", "req", "in", "processed", ":", "# Ignore cyclic or redundant dependencies", "continue", "dist", "=", "best", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", ":", "# Find the best distribution and add it to the map", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", "or", "(", "dist", "not", "in", "req", "and", "replace_conflicting", ")", ":", "ws", "=", "self", "if", "env", "is", "None", ":", "if", "dist", "is", "None", ":", "env", "=", "Environment", "(", "self", ".", "entries", ")", "else", ":", "# Use an empty environment and workingset to avoid", "# any further conflicts with the conflicting", "# distribution", "env", "=", "Environment", "(", "[", "]", ")", "ws", "=", "WorkingSet", "(", "[", "]", ")", "dist", "=", "best", "[", "req", ".", "key", "]", "=", "env", ".", "best_match", "(", "req", ",", "ws", ",", "installer", ")", "if", "dist", "is", "None", ":", "#msg = (\"The '%s' distribution was not found on this \"", "# \"system, and is required by this application.\")", "#raise DistributionNotFound(msg % req)", "# unfortunately, zc.buildout uses a str(err)", "# to get the name of the distribution here..", "raise", "DistributionNotFound", "(", "req", ")", "to_activate", ".", "append", "(", "dist", ")", "if", "dist", "not", "in", "req", ":", "# Oops, the \"best\" so far conflicts with a dependency", "tmpl", "=", "\"%s is installed but %s is required by %s\"", "args", "=", "dist", ",", "req", ",", "list", "(", "required_by", ".", "get", "(", "req", ",", "[", "]", ")", ")", "raise", "VersionConflict", "(", "tmpl", "%", "args", ")", "# push the new requirements onto the stack", "new_requirements", "=", "dist", ".", "requires", "(", "req", ".", "extras", ")", "[", ":", ":", "-", "1", "]", "requirements", ".", "extend", "(", "new_requirements", ")", "# Register the new requirements needed by req", "for", "new_requirement", "in", "new_requirements", ":", "required_by", "[", "new_requirement", "]", ".", "add", "(", "req", ".", "project_name", ")", "processed", "[", "req", "]", "=", "True", "# return list of distros to activate", "return", "to_activate" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
MarkerEvaluation.is_invalid_marker
Validate text as a PEP 426 environment marker; return an exception if invalid or False otherwise.
virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
def is_invalid_marker(cls, text): """ Validate text as a PEP 426 environment marker; return an exception if invalid or False otherwise. """ try: cls.evaluate_marker(text) except SyntaxError: return cls.normalize_exception(sys.exc_info()[1]) return False
def is_invalid_marker(cls, text): """ Validate text as a PEP 426 environment marker; return an exception if invalid or False otherwise. """ try: cls.evaluate_marker(text) except SyntaxError: return cls.normalize_exception(sys.exc_info()[1]) return False
[ "Validate", "text", "as", "a", "PEP", "426", "environment", "marker", ";", "return", "an", "exception", "if", "invalid", "or", "False", "otherwise", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1328-L1337
[ "def", "is_invalid_marker", "(", "cls", ",", "text", ")", ":", "try", ":", "cls", ".", "evaluate_marker", "(", "text", ")", "except", "SyntaxError", ":", "return", "cls", ".", "normalize_exception", "(", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", "return", "False" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
run
This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in output. If the full path to the command is not given then the path is searched. Note that lines are terminated by CR/LF (\\r\\n) combination even on UNIX-like systems because this is the standard for pseudo ttys. If you set 'withexitstatus' to true, then run will return a tuple of (command_output, exitstatus). If 'withexitstatus' is false then this returns just command_output. The run() function can often be used instead of creating a spawn instance. For example, the following code uses spawn:: from pexpect import * child = spawn('scp foo myname@host.example.com:.') child.expect ('(?i)password') child.sendline (mypassword) The previous code can be replace with the following:: from pexpect import * run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword}) Examples ======== Start the apache daemon on the local machine:: from pexpect import * run ("/usr/local/apache/bin/apachectl start") Check in a file using SVN:: from pexpect import * run ("svn ci -m 'automatic commit' my_file.py") Run a command and capture exit status:: from pexpect import * (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) Tricky Examples =============== The following will run SSH and execute 'ls -l' on the remote machine. The password 'secret' will be sent if the '(?i)password' pattern is ever seen:: run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'}) This will start mencoder to rip a video from DVD. This will also display progress ticks every 5 seconds as it runs. For example:: from pexpect import * def print_ticks(d): print d['event_count'], run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) The 'events' argument should be a dictionary of patterns and responses. Whenever one of the patterns is seen in the command out run() will send the associated response string. Note that you should put newlines in your string if Enter is necessary. The responses may also contain callback functions. Any callback is function that takes a dictionary as an argument. The dictionary contains all the locals from the run() function, so you can access the child spawn object or any other variable defined in run() (event_count, child, and extra_args are the most useful). A callback may return True to stop the current run process otherwise run() continues until the next event. A callback may also return a string which will be sent to the child. 'extra_args' is not used by directly run(). It provides a way to pass data to a callback function through run() through the locals dictionary passed to a callback.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, encoding='utf-8'): """ This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in output. If the full path to the command is not given then the path is searched. Note that lines are terminated by CR/LF (\\r\\n) combination even on UNIX-like systems because this is the standard for pseudo ttys. If you set 'withexitstatus' to true, then run will return a tuple of (command_output, exitstatus). If 'withexitstatus' is false then this returns just command_output. The run() function can often be used instead of creating a spawn instance. For example, the following code uses spawn:: from pexpect import * child = spawn('scp foo myname@host.example.com:.') child.expect ('(?i)password') child.sendline (mypassword) The previous code can be replace with the following:: from pexpect import * run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword}) Examples ======== Start the apache daemon on the local machine:: from pexpect import * run ("/usr/local/apache/bin/apachectl start") Check in a file using SVN:: from pexpect import * run ("svn ci -m 'automatic commit' my_file.py") Run a command and capture exit status:: from pexpect import * (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) Tricky Examples =============== The following will run SSH and execute 'ls -l' on the remote machine. The password 'secret' will be sent if the '(?i)password' pattern is ever seen:: run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'}) This will start mencoder to rip a video from DVD. This will also display progress ticks every 5 seconds as it runs. For example:: from pexpect import * def print_ticks(d): print d['event_count'], run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) The 'events' argument should be a dictionary of patterns and responses. Whenever one of the patterns is seen in the command out run() will send the associated response string. Note that you should put newlines in your string if Enter is necessary. The responses may also contain callback functions. Any callback is function that takes a dictionary as an argument. The dictionary contains all the locals from the run() function, so you can access the child spawn object or any other variable defined in run() (event_count, child, and extra_args are the most useful). A callback may return True to stop the current run process otherwise run() continues until the next event. A callback may also return a string which will be sent to the child. 'extra_args' is not used by directly run(). It provides a way to pass data to a callback function through run() through the locals dictionary passed to a callback.""" if timeout == -1: child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env, encoding=encoding) else: child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env, encoding=encoding) if events is not None: patterns = events.keys() responses = events.values() else: patterns=None # We assume that EOF or TIMEOUT will save us. responses=None child_result_list = [] event_count = 0 while 1: try: index = child.expect (patterns) if isinstance(child.after, basestring): child_result_list.append(child.before + child.after) else: # child.after may have been a TIMEOUT or EOF, so don't cat those. child_result_list.append(child.before) if isinstance(responses[index], basestring): child.send(responses[index]) elif type(responses[index]) is types.FunctionType: callback_result = responses[index](locals()) sys.stdout.flush() if isinstance(callback_result, basestring): child.send(callback_result) elif callback_result: break else: raise TypeError ('The callback must be a string or function type.') event_count = event_count + 1 except TIMEOUT, e: child_result_list.append(child.before) break except EOF, e: child_result_list.append(child.before) break child_result = child._empty_buffer.join(child_result_list) if withexitstatus: child.close() return (child_result, child.exitstatus) else: return child_result
def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, encoding='utf-8'): """ This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in output. If the full path to the command is not given then the path is searched. Note that lines are terminated by CR/LF (\\r\\n) combination even on UNIX-like systems because this is the standard for pseudo ttys. If you set 'withexitstatus' to true, then run will return a tuple of (command_output, exitstatus). If 'withexitstatus' is false then this returns just command_output. The run() function can often be used instead of creating a spawn instance. For example, the following code uses spawn:: from pexpect import * child = spawn('scp foo myname@host.example.com:.') child.expect ('(?i)password') child.sendline (mypassword) The previous code can be replace with the following:: from pexpect import * run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword}) Examples ======== Start the apache daemon on the local machine:: from pexpect import * run ("/usr/local/apache/bin/apachectl start") Check in a file using SVN:: from pexpect import * run ("svn ci -m 'automatic commit' my_file.py") Run a command and capture exit status:: from pexpect import * (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) Tricky Examples =============== The following will run SSH and execute 'ls -l' on the remote machine. The password 'secret' will be sent if the '(?i)password' pattern is ever seen:: run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'}) This will start mencoder to rip a video from DVD. This will also display progress ticks every 5 seconds as it runs. For example:: from pexpect import * def print_ticks(d): print d['event_count'], run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) The 'events' argument should be a dictionary of patterns and responses. Whenever one of the patterns is seen in the command out run() will send the associated response string. Note that you should put newlines in your string if Enter is necessary. The responses may also contain callback functions. Any callback is function that takes a dictionary as an argument. The dictionary contains all the locals from the run() function, so you can access the child spawn object or any other variable defined in run() (event_count, child, and extra_args are the most useful). A callback may return True to stop the current run process otherwise run() continues until the next event. A callback may also return a string which will be sent to the child. 'extra_args' is not used by directly run(). It provides a way to pass data to a callback function through run() through the locals dictionary passed to a callback.""" if timeout == -1: child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env, encoding=encoding) else: child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env, encoding=encoding) if events is not None: patterns = events.keys() responses = events.values() else: patterns=None # We assume that EOF or TIMEOUT will save us. responses=None child_result_list = [] event_count = 0 while 1: try: index = child.expect (patterns) if isinstance(child.after, basestring): child_result_list.append(child.before + child.after) else: # child.after may have been a TIMEOUT or EOF, so don't cat those. child_result_list.append(child.before) if isinstance(responses[index], basestring): child.send(responses[index]) elif type(responses[index]) is types.FunctionType: callback_result = responses[index](locals()) sys.stdout.flush() if isinstance(callback_result, basestring): child.send(callback_result) elif callback_result: break else: raise TypeError ('The callback must be a string or function type.') event_count = event_count + 1 except TIMEOUT, e: child_result_list.append(child.before) break except EOF, e: child_result_list.append(child.before) break child_result = child._empty_buffer.join(child_result_list) if withexitstatus: child.close() return (child_result, child.exitstatus) else: return child_result
[ "This", "function", "runs", "the", "given", "command", ";", "waits", "for", "it", "to", "finish", ";", "then", "returns", "all", "output", "as", "a", "string", ".", "STDERR", "is", "included", "in", "output", ".", "If", "the", "full", "path", "to", "the", "command", "is", "not", "given", "then", "the", "path", "is", "searched", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L160-L279
[ "def", "run", "(", "command", ",", "timeout", "=", "-", "1", ",", "withexitstatus", "=", "False", ",", "events", "=", "None", ",", "extra_args", "=", "None", ",", "logfile", "=", "None", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "timeout", "==", "-", "1", ":", "child", "=", "spawn", "(", "command", ",", "maxread", "=", "2000", ",", "logfile", "=", "logfile", ",", "cwd", "=", "cwd", ",", "env", "=", "env", ",", "encoding", "=", "encoding", ")", "else", ":", "child", "=", "spawn", "(", "command", ",", "timeout", "=", "timeout", ",", "maxread", "=", "2000", ",", "logfile", "=", "logfile", ",", "cwd", "=", "cwd", ",", "env", "=", "env", ",", "encoding", "=", "encoding", ")", "if", "events", "is", "not", "None", ":", "patterns", "=", "events", ".", "keys", "(", ")", "responses", "=", "events", ".", "values", "(", ")", "else", ":", "patterns", "=", "None", "# We assume that EOF or TIMEOUT will save us.", "responses", "=", "None", "child_result_list", "=", "[", "]", "event_count", "=", "0", "while", "1", ":", "try", ":", "index", "=", "child", ".", "expect", "(", "patterns", ")", "if", "isinstance", "(", "child", ".", "after", ",", "basestring", ")", ":", "child_result_list", ".", "append", "(", "child", ".", "before", "+", "child", ".", "after", ")", "else", ":", "# child.after may have been a TIMEOUT or EOF, so don't cat those.", "child_result_list", ".", "append", "(", "child", ".", "before", ")", "if", "isinstance", "(", "responses", "[", "index", "]", ",", "basestring", ")", ":", "child", ".", "send", "(", "responses", "[", "index", "]", ")", "elif", "type", "(", "responses", "[", "index", "]", ")", "is", "types", ".", "FunctionType", ":", "callback_result", "=", "responses", "[", "index", "]", "(", "locals", "(", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "isinstance", "(", "callback_result", ",", "basestring", ")", ":", "child", ".", "send", "(", "callback_result", ")", "elif", "callback_result", ":", "break", "else", ":", "raise", "TypeError", "(", "'The callback must be a string or function type.'", ")", "event_count", "=", "event_count", "+", "1", "except", "TIMEOUT", ",", "e", ":", "child_result_list", ".", "append", "(", "child", ".", "before", ")", "break", "except", "EOF", ",", "e", ":", "child_result_list", ".", "append", "(", "child", ".", "before", ")", "break", "child_result", "=", "child", ".", "_empty_buffer", ".", "join", "(", "child_result_list", ")", "if", "withexitstatus", ":", "child", ".", "close", "(", ")", "return", "(", "child_result", ",", "child", ".", "exitstatus", ")", "else", ":", "return", "child_result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
which
This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def which (filename): """This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None.""" # Special case where filename already contains a path. if os.path.dirname(filename) != '': if os.access (filename, os.X_OK): return filename if not os.environ.has_key('PATH') or os.environ['PATH'] == '': p = os.defpath else: p = os.environ['PATH'] pathlist = p.split(os.pathsep) for path in pathlist: f = os.path.join(path, filename) if os.access(f, os.X_OK): return f return None
def which (filename): """This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None.""" # Special case where filename already contains a path. if os.path.dirname(filename) != '': if os.access (filename, os.X_OK): return filename if not os.environ.has_key('PATH') or os.environ['PATH'] == '': p = os.defpath else: p = os.environ['PATH'] pathlist = p.split(os.pathsep) for path in pathlist: f = os.path.join(path, filename) if os.access(f, os.X_OK): return f return None
[ "This", "takes", "a", "given", "filename", ";", "tries", "to", "find", "it", "in", "the", "environment", "path", ";", "then", "checks", "if", "it", "is", "executable", ".", "This", "returns", "the", "full", "path", "to", "the", "filename", "if", "found", "and", "executable", ".", "Otherwise", "this", "returns", "None", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1821-L1843
[ "def", "which", "(", "filename", ")", ":", "# Special case where filename already contains a path.", "if", "os", ".", "path", ".", "dirname", "(", "filename", ")", "!=", "''", ":", "if", "os", ".", "access", "(", "filename", ",", "os", ".", "X_OK", ")", ":", "return", "filename", "if", "not", "os", ".", "environ", ".", "has_key", "(", "'PATH'", ")", "or", "os", ".", "environ", "[", "'PATH'", "]", "==", "''", ":", "p", "=", "os", ".", "defpath", "else", ":", "p", "=", "os", ".", "environ", "[", "'PATH'", "]", "pathlist", "=", "p", ".", "split", "(", "os", ".", "pathsep", ")", "for", "path", "in", "pathlist", ":", "f", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "if", "os", ".", "access", "(", "f", ",", "os", ".", "X_OK", ")", ":", "return", "f", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb._spawn
This starts the given command in a child process. This does all the fork/exec type of stuff for a pty. This is called by __init__. If args is empty then command will be parsed (split on spaces) and args will be set to parsed arguments.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def _spawn(self,command,args=[]): """This starts the given command in a child process. This does all the fork/exec type of stuff for a pty. This is called by __init__. If args is empty then command will be parsed (split on spaces) and args will be set to parsed arguments. """ # The pid and child_fd of this object get set by this method. # Note that it is difficult for this method to fail. # You cannot detect if the child process cannot start. # So the only way you can tell if the child process started # or not is to try to read from the file descriptor. If you get # EOF immediately then it means that the child is already dead. # That may not necessarily be bad because you may haved spawned a child # that performs some task; creates no stdout output; and then dies. # If command is an int type then it may represent a file descriptor. if type(command) == type(0): raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.') if type (args) != type([]): raise TypeError ('The argument, args, must be a list.') if args == []: self.args = split_command_line(command) self.command = self.args[0] else: self.args = args[:] # work with a copy self.args.insert (0, command) self.command = command command_with_path = which(self.command) if command_with_path is None: raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command) self.command = command_with_path self.args[0] = self.command self.name = '<' + ' '.join (self.args) + '>' assert self.pid is None, 'The pid member should be None.' assert self.command is not None, 'The command member should not be None.' if self.use_native_pty_fork: try: self.pid, self.child_fd = pty.fork() except OSError, e: raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e)) else: # Use internal __fork_pty self.pid, self.child_fd = self.__fork_pty() if self.pid == 0: # Child try: self.child_fd = sys.stdout.fileno() # used by setwinsize() self.setwinsize(24, 80) except: # Some platforms do not like setwinsize (Cygwin). # This will cause problem when running applications that # are very picky about window size. # This is a serious limitation, but not a show stopper. pass # Do not allow child to inherit open file descriptors from parent. max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] for i in range (3, max_fd): try: os.close (i) except OSError: pass # I don't know why this works, but ignoring SIGHUP fixes a # problem when trying to start a Java daemon with sudo # (specifically, Tomcat). signal.signal(signal.SIGHUP, signal.SIG_IGN) if self.cwd is not None: os.chdir(self.cwd) if self.env is None: os.execv(self.command, self.args) else: os.execvpe(self.command, self.args, self.env) # Parent self.terminated = False self.closed = False
def _spawn(self,command,args=[]): """This starts the given command in a child process. This does all the fork/exec type of stuff for a pty. This is called by __init__. If args is empty then command will be parsed (split on spaces) and args will be set to parsed arguments. """ # The pid and child_fd of this object get set by this method. # Note that it is difficult for this method to fail. # You cannot detect if the child process cannot start. # So the only way you can tell if the child process started # or not is to try to read from the file descriptor. If you get # EOF immediately then it means that the child is already dead. # That may not necessarily be bad because you may haved spawned a child # that performs some task; creates no stdout output; and then dies. # If command is an int type then it may represent a file descriptor. if type(command) == type(0): raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.') if type (args) != type([]): raise TypeError ('The argument, args, must be a list.') if args == []: self.args = split_command_line(command) self.command = self.args[0] else: self.args = args[:] # work with a copy self.args.insert (0, command) self.command = command command_with_path = which(self.command) if command_with_path is None: raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command) self.command = command_with_path self.args[0] = self.command self.name = '<' + ' '.join (self.args) + '>' assert self.pid is None, 'The pid member should be None.' assert self.command is not None, 'The command member should not be None.' if self.use_native_pty_fork: try: self.pid, self.child_fd = pty.fork() except OSError, e: raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e)) else: # Use internal __fork_pty self.pid, self.child_fd = self.__fork_pty() if self.pid == 0: # Child try: self.child_fd = sys.stdout.fileno() # used by setwinsize() self.setwinsize(24, 80) except: # Some platforms do not like setwinsize (Cygwin). # This will cause problem when running applications that # are very picky about window size. # This is a serious limitation, but not a show stopper. pass # Do not allow child to inherit open file descriptors from parent. max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] for i in range (3, max_fd): try: os.close (i) except OSError: pass # I don't know why this works, but ignoring SIGHUP fixes a # problem when trying to start a Java daemon with sudo # (specifically, Tomcat). signal.signal(signal.SIGHUP, signal.SIG_IGN) if self.cwd is not None: os.chdir(self.cwd) if self.env is None: os.execv(self.command, self.args) else: os.execvpe(self.command, self.args, self.env) # Parent self.terminated = False self.closed = False
[ "This", "starts", "the", "given", "command", "in", "a", "child", "process", ".", "This", "does", "all", "the", "fork", "/", "exec", "type", "of", "stuff", "for", "a", "pty", ".", "This", "is", "called", "by", "__init__", ".", "If", "args", "is", "empty", "then", "command", "will", "be", "parsed", "(", "split", "on", "spaces", ")", "and", "args", "will", "be", "set", "to", "parsed", "arguments", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L510-L592
[ "def", "_spawn", "(", "self", ",", "command", ",", "args", "=", "[", "]", ")", ":", "# The pid and child_fd of this object get set by this method.", "# Note that it is difficult for this method to fail.", "# You cannot detect if the child process cannot start.", "# So the only way you can tell if the child process started", "# or not is to try to read from the file descriptor. If you get", "# EOF immediately then it means that the child is already dead.", "# That may not necessarily be bad because you may haved spawned a child", "# that performs some task; creates no stdout output; and then dies.", "# If command is an int type then it may represent a file descriptor.", "if", "type", "(", "command", ")", "==", "type", "(", "0", ")", ":", "raise", "ExceptionPexpect", "(", "'Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.'", ")", "if", "type", "(", "args", ")", "!=", "type", "(", "[", "]", ")", ":", "raise", "TypeError", "(", "'The argument, args, must be a list.'", ")", "if", "args", "==", "[", "]", ":", "self", ".", "args", "=", "split_command_line", "(", "command", ")", "self", ".", "command", "=", "self", ".", "args", "[", "0", "]", "else", ":", "self", ".", "args", "=", "args", "[", ":", "]", "# work with a copy", "self", ".", "args", ".", "insert", "(", "0", ",", "command", ")", "self", ".", "command", "=", "command", "command_with_path", "=", "which", "(", "self", ".", "command", ")", "if", "command_with_path", "is", "None", ":", "raise", "ExceptionPexpect", "(", "'The command was not found or was not executable: %s.'", "%", "self", ".", "command", ")", "self", ".", "command", "=", "command_with_path", "self", ".", "args", "[", "0", "]", "=", "self", ".", "command", "self", ".", "name", "=", "'<'", "+", "' '", ".", "join", "(", "self", ".", "args", ")", "+", "'>'", "assert", "self", ".", "pid", "is", "None", ",", "'The pid member should be None.'", "assert", "self", ".", "command", "is", "not", "None", ",", "'The command member should not be None.'", "if", "self", ".", "use_native_pty_fork", ":", "try", ":", "self", ".", "pid", ",", "self", ".", "child_fd", "=", "pty", ".", "fork", "(", ")", "except", "OSError", ",", "e", ":", "raise", "ExceptionPexpect", "(", "'Error! pty.fork() failed: '", "+", "str", "(", "e", ")", ")", "else", ":", "# Use internal __fork_pty", "self", ".", "pid", ",", "self", ".", "child_fd", "=", "self", ".", "__fork_pty", "(", ")", "if", "self", ".", "pid", "==", "0", ":", "# Child", "try", ":", "self", ".", "child_fd", "=", "sys", ".", "stdout", ".", "fileno", "(", ")", "# used by setwinsize()", "self", ".", "setwinsize", "(", "24", ",", "80", ")", "except", ":", "# Some platforms do not like setwinsize (Cygwin).", "# This will cause problem when running applications that", "# are very picky about window size.", "# This is a serious limitation, but not a show stopper.", "pass", "# Do not allow child to inherit open file descriptors from parent.", "max_fd", "=", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "[", "0", "]", "for", "i", "in", "range", "(", "3", ",", "max_fd", ")", ":", "try", ":", "os", ".", "close", "(", "i", ")", "except", "OSError", ":", "pass", "# I don't know why this works, but ignoring SIGHUP fixes a", "# problem when trying to start a Java daemon with sudo", "# (specifically, Tomcat).", "signal", ".", "signal", "(", "signal", ".", "SIGHUP", ",", "signal", ".", "SIG_IGN", ")", "if", "self", ".", "cwd", "is", "not", "None", ":", "os", ".", "chdir", "(", "self", ".", "cwd", ")", "if", "self", ".", "env", "is", "None", ":", "os", ".", "execv", "(", "self", ".", "command", ",", "self", ".", "args", ")", "else", ":", "os", ".", "execvpe", "(", "self", ".", "command", ",", "self", ".", "args", ",", "self", ".", "env", ")", "# Parent", "self", ".", "terminated", "=", "False", "self", ".", "closed", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.__fork_pty
This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not supporting Solaris, particularly ssh. Based on patch to posixmodule.c authored by Noah Spurrier:: http://mail.python.org/pipermail/python-dev/2003-May/035281.html
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def __fork_pty(self): """This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not supporting Solaris, particularly ssh. Based on patch to posixmodule.c authored by Noah Spurrier:: http://mail.python.org/pipermail/python-dev/2003-May/035281.html """ parent_fd, child_fd = os.openpty() if parent_fd < 0 or child_fd < 0: raise ExceptionPexpect, "Error! Could not open pty with os.openpty()." pid = os.fork() if pid < 0: raise ExceptionPexpect, "Error! Failed os.fork()." elif pid == 0: # Child. os.close(parent_fd) self.__pty_make_controlling_tty(child_fd) os.dup2(child_fd, 0) os.dup2(child_fd, 1) os.dup2(child_fd, 2) if child_fd > 2: os.close(child_fd) else: # Parent. os.close(child_fd) return pid, parent_fd
def __fork_pty(self): """This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not supporting Solaris, particularly ssh. Based on patch to posixmodule.c authored by Noah Spurrier:: http://mail.python.org/pipermail/python-dev/2003-May/035281.html """ parent_fd, child_fd = os.openpty() if parent_fd < 0 or child_fd < 0: raise ExceptionPexpect, "Error! Could not open pty with os.openpty()." pid = os.fork() if pid < 0: raise ExceptionPexpect, "Error! Failed os.fork()." elif pid == 0: # Child. os.close(parent_fd) self.__pty_make_controlling_tty(child_fd) os.dup2(child_fd, 0) os.dup2(child_fd, 1) os.dup2(child_fd, 2) if child_fd > 2: os.close(child_fd) else: # Parent. os.close(child_fd) return pid, parent_fd
[ "This", "implements", "a", "substitute", "for", "the", "forkpty", "system", "call", ".", "This", "should", "be", "more", "portable", "than", "the", "pty", ".", "fork", "()", "function", ".", "Specifically", "this", "should", "work", "on", "Solaris", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L594-L631
[ "def", "__fork_pty", "(", "self", ")", ":", "parent_fd", ",", "child_fd", "=", "os", ".", "openpty", "(", ")", "if", "parent_fd", "<", "0", "or", "child_fd", "<", "0", ":", "raise", "ExceptionPexpect", ",", "\"Error! Could not open pty with os.openpty().\"", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", "<", "0", ":", "raise", "ExceptionPexpect", ",", "\"Error! Failed os.fork().\"", "elif", "pid", "==", "0", ":", "# Child.", "os", ".", "close", "(", "parent_fd", ")", "self", ".", "__pty_make_controlling_tty", "(", "child_fd", ")", "os", ".", "dup2", "(", "child_fd", ",", "0", ")", "os", ".", "dup2", "(", "child_fd", ",", "1", ")", "os", ".", "dup2", "(", "child_fd", ",", "2", ")", "if", "child_fd", ">", "2", ":", "os", ".", "close", "(", "child_fd", ")", "else", ":", "# Parent.", "os", ".", "close", "(", "child_fd", ")", "return", "pid", ",", "parent_fd" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.__pty_make_controlling_tty
This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def __pty_make_controlling_tty(self, tty_fd): """This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. """ child_name = os.ttyname(tty_fd) # Disconnect from controlling tty. Harmless if not already connected. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); if fd >= 0: os.close(fd) except: # Already disconnected. This happens if running inside cron. pass os.setsid() # Verify we are disconnected from controlling tty # by attempting to open it again. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); if fd >= 0: os.close(fd) raise ExceptionPexpect, "Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty." except: # Good! We are disconnected from a controlling tty. pass # Verify we can open child pty. fd = os.open(child_name, os.O_RDWR); if fd < 0: raise ExceptionPexpect, "Error! Could not open child pty, " + child_name else: os.close(fd) # Verify we now have a controlling tty. fd = os.open("/dev/tty", os.O_WRONLY) if fd < 0: raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty" else: os.close(fd)
def __pty_make_controlling_tty(self, tty_fd): """This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. """ child_name = os.ttyname(tty_fd) # Disconnect from controlling tty. Harmless if not already connected. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); if fd >= 0: os.close(fd) except: # Already disconnected. This happens if running inside cron. pass os.setsid() # Verify we are disconnected from controlling tty # by attempting to open it again. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); if fd >= 0: os.close(fd) raise ExceptionPexpect, "Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty." except: # Good! We are disconnected from a controlling tty. pass # Verify we can open child pty. fd = os.open(child_name, os.O_RDWR); if fd < 0: raise ExceptionPexpect, "Error! Could not open child pty, " + child_name else: os.close(fd) # Verify we now have a controlling tty. fd = os.open("/dev/tty", os.O_WRONLY) if fd < 0: raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty" else: os.close(fd)
[ "This", "makes", "the", "pseudo", "-", "terminal", "the", "controlling", "tty", ".", "This", "should", "be", "more", "portable", "than", "the", "pty", ".", "fork", "()", "function", ".", "Specifically", "this", "should", "work", "on", "Solaris", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L633-L675
[ "def", "__pty_make_controlling_tty", "(", "self", ",", "tty_fd", ")", ":", "child_name", "=", "os", ".", "ttyname", "(", "tty_fd", ")", "# Disconnect from controlling tty. Harmless if not already connected.", "try", ":", "fd", "=", "os", ".", "open", "(", "\"/dev/tty\"", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_NOCTTY", ")", "if", "fd", ">=", "0", ":", "os", ".", "close", "(", "fd", ")", "except", ":", "# Already disconnected. This happens if running inside cron.", "pass", "os", ".", "setsid", "(", ")", "# Verify we are disconnected from controlling tty", "# by attempting to open it again.", "try", ":", "fd", "=", "os", ".", "open", "(", "\"/dev/tty\"", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_NOCTTY", ")", "if", "fd", ">=", "0", ":", "os", ".", "close", "(", "fd", ")", "raise", "ExceptionPexpect", ",", "\"Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty.\"", "except", ":", "# Good! We are disconnected from a controlling tty.", "pass", "# Verify we can open child pty.", "fd", "=", "os", ".", "open", "(", "child_name", ",", "os", ".", "O_RDWR", ")", "if", "fd", "<", "0", ":", "raise", "ExceptionPexpect", ",", "\"Error! Could not open child pty, \"", "+", "child_name", "else", ":", "os", ".", "close", "(", "fd", ")", "# Verify we now have a controlling tty.", "fd", "=", "os", ".", "open", "(", "\"/dev/tty\"", ",", "os", ".", "O_WRONLY", ")", "if", "fd", "<", "0", ":", "raise", "ExceptionPexpect", ",", "\"Error! Could not open controlling tty, /dev/tty\"", "else", ":", "os", ".", "close", "(", "fd", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.close
This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT).
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def close (self, force=True): # File-like object. """This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT). """ if not self.closed: self.flush() os.close (self.child_fd) time.sleep(self.delayafterclose) # Give kernel time to update process status. if self.isalive(): if not self.terminate(force): raise ExceptionPexpect ('close() could not terminate the child using terminate()') self.child_fd = -1 self.closed = True
def close (self, force=True): # File-like object. """This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT). """ if not self.closed: self.flush() os.close (self.child_fd) time.sleep(self.delayafterclose) # Give kernel time to update process status. if self.isalive(): if not self.terminate(force): raise ExceptionPexpect ('close() could not terminate the child using terminate()') self.child_fd = -1 self.closed = True
[ "This", "closes", "the", "connection", "with", "the", "child", "application", ".", "Note", "that", "calling", "close", "()", "more", "than", "once", "is", "valid", ".", "This", "emulates", "standard", "Python", "behavior", "with", "files", ".", "Set", "force", "to", "True", "if", "you", "want", "to", "make", "sure", "that", "the", "child", "is", "terminated", "(", "SIGKILL", "is", "sent", "if", "the", "child", "ignores", "SIGHUP", "and", "SIGINT", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L684-L700
[ "def", "close", "(", "self", ",", "force", "=", "True", ")", ":", "# File-like object.", "if", "not", "self", ".", "closed", ":", "self", ".", "flush", "(", ")", "os", ".", "close", "(", "self", ".", "child_fd", ")", "time", ".", "sleep", "(", "self", ".", "delayafterclose", ")", "# Give kernel time to update process status.", "if", "self", ".", "isalive", "(", ")", ":", "if", "not", "self", ".", "terminate", "(", "force", ")", ":", "raise", "ExceptionPexpect", "(", "'close() could not terminate the child using terminate()'", ")", "self", ".", "child_fd", "=", "-", "1", "self", ".", "closed", "=", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.getecho
This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho().
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def getecho (self): """This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). """ attr = termios.tcgetattr(self.child_fd) if attr[3] & termios.ECHO: return True return False
def getecho (self): """This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). """ attr = termios.tcgetattr(self.child_fd) if attr[3] & termios.ECHO: return True return False
[ "This", "returns", "the", "terminal", "echo", "mode", ".", "This", "returns", "True", "if", "echo", "is", "on", "or", "False", "if", "echo", "is", "off", ".", "Child", "applications", "that", "are", "expecting", "you", "to", "enter", "a", "password", "often", "set", "ECHO", "False", ".", "See", "waitnoecho", "()", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L748-L757
[ "def", "getecho", "(", "self", ")", ":", "attr", "=", "termios", ".", "tcgetattr", "(", "self", ".", "child_fd", ")", "if", "attr", "[", "3", "]", "&", "termios", ".", "ECHO", ":", "return", "True", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.setecho
This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.expect (['1234']) p.expect (['1234']) p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['abcd']) p.expect (['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['1234']) p.expect (['1234']) p.expect (['abcd']) p.expect (['wxyz'])
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def setecho (self, state): """This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.expect (['1234']) p.expect (['1234']) p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['abcd']) p.expect (['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['1234']) p.expect (['1234']) p.expect (['abcd']) p.expect (['wxyz']) """ self.child_fd attr = termios.tcgetattr(self.child_fd) if state: attr[3] = attr[3] | termios.ECHO else: attr[3] = attr[3] & ~termios.ECHO # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
def setecho (self, state): """This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.expect (['1234']) p.expect (['1234']) p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['abcd']) p.expect (['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). p.setecho(False) # Turn off tty echo p.sendline ('abcd') # We will set this only once (echoed by cat). p.sendline ('wxyz') # We will set this only once (echoed by cat) p.expect (['1234']) p.expect (['1234']) p.expect (['abcd']) p.expect (['wxyz']) """ self.child_fd attr = termios.tcgetattr(self.child_fd) if state: attr[3] = attr[3] | termios.ECHO else: attr[3] = attr[3] & ~termios.ECHO # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
[ "This", "sets", "the", "terminal", "echo", "mode", "on", "or", "off", ".", "Note", "that", "anything", "the", "child", "sent", "before", "the", "echo", "will", "be", "lost", "so", "you", "should", "be", "sure", "that", "your", "input", "buffer", "is", "empty", "before", "you", "call", "setecho", "()", ".", "For", "example", "the", "following", "will", "work", "as", "expected", "::" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L759-L798
[ "def", "setecho", "(", "self", ",", "state", ")", ":", "self", ".", "child_fd", "attr", "=", "termios", ".", "tcgetattr", "(", "self", ".", "child_fd", ")", "if", "state", ":", "attr", "[", "3", "]", "=", "attr", "[", "3", "]", "|", "termios", ".", "ECHO", "else", ":", "attr", "[", "3", "]", "=", "attr", "[", "3", "]", "&", "~", "termios", ".", "ECHO", "# I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent", "# and blocked on some platforms. TCSADRAIN is probably ideal if it worked.", "termios", ".", "tcsetattr", "(", "self", ".", "child_fd", ",", "termios", ".", "TCSANOW", ",", "attr", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.read_nonblocking
This reads at most size bytes from the child application. It includes a timeout. If the read does not complete within the timeout period then a TIMEOUT exception is raised. If the end of file is read then an EOF exception will be raised. If a log file was set using setlog() then all data will also be written to the log file. If timeout is None then the read may block indefinitely. If timeout is -1 then the self.timeout value is used. If timeout is 0 then the child is polled and if there was no data immediately ready then this will raise a TIMEOUT exception. The timeout refers only to the amount of time to read at least one character. This is not effected by the 'size' parameter, so if you call read_nonblocking(size=100, timeout=30) and only one character is available right away then one character will be returned immediately. It will not wait for 30 seconds for another 99 characters to come in. This is a wrapper around os.read(). It uses select.select() to implement the timeout.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def read_nonblocking (self, size = 1, timeout = -1): """This reads at most size bytes from the child application. It includes a timeout. If the read does not complete within the timeout period then a TIMEOUT exception is raised. If the end of file is read then an EOF exception will be raised. If a log file was set using setlog() then all data will also be written to the log file. If timeout is None then the read may block indefinitely. If timeout is -1 then the self.timeout value is used. If timeout is 0 then the child is polled and if there was no data immediately ready then this will raise a TIMEOUT exception. The timeout refers only to the amount of time to read at least one character. This is not effected by the 'size' parameter, so if you call read_nonblocking(size=100, timeout=30) and only one character is available right away then one character will be returned immediately. It will not wait for 30 seconds for another 99 characters to come in. This is a wrapper around os.read(). It uses select.select() to implement the timeout. """ if self.closed: raise ValueError ('I/O operation on closed file in read_nonblocking().') if timeout == -1: timeout = self.timeout # Note that some systems such as Solaris do not give an EOF when # the child dies. In fact, you can still try to read # from the child_fd -- it will block forever or until TIMEOUT. # For this case, I test isalive() before doing any reading. # If isalive() is false, then I pretend that this is the same as EOF. if not self.isalive(): r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll" if not r: self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.') elif self.__irix_hack: # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive. # This adds a 2 second delay, but only when the child is terminated. r, w, e = self.__select([self.child_fd], [], [], 2) if not r and not self.isalive(): self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.') r,w,e = self.__select([self.child_fd], [], [], timeout) if not r: if not self.isalive(): # Some platforms, such as Irix, will claim that their processes are alive; # then timeout on the select; and then finally admit that they are not alive. self.flag_eof = True raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.') else: raise TIMEOUT ('Timeout exceeded in read_nonblocking().') if self.child_fd in r: try: s = os.read(self.child_fd, size) except OSError, e: # Linux does this self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.') if s == b'': # BSD style self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.') s2 = self._cast_buffer_type(s) if self.logfile is not None: self.logfile.write(s2) self.logfile.flush() if self.logfile_read is not None: self.logfile_read.write(s2) self.logfile_read.flush() return s raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
def read_nonblocking (self, size = 1, timeout = -1): """This reads at most size bytes from the child application. It includes a timeout. If the read does not complete within the timeout period then a TIMEOUT exception is raised. If the end of file is read then an EOF exception will be raised. If a log file was set using setlog() then all data will also be written to the log file. If timeout is None then the read may block indefinitely. If timeout is -1 then the self.timeout value is used. If timeout is 0 then the child is polled and if there was no data immediately ready then this will raise a TIMEOUT exception. The timeout refers only to the amount of time to read at least one character. This is not effected by the 'size' parameter, so if you call read_nonblocking(size=100, timeout=30) and only one character is available right away then one character will be returned immediately. It will not wait for 30 seconds for another 99 characters to come in. This is a wrapper around os.read(). It uses select.select() to implement the timeout. """ if self.closed: raise ValueError ('I/O operation on closed file in read_nonblocking().') if timeout == -1: timeout = self.timeout # Note that some systems such as Solaris do not give an EOF when # the child dies. In fact, you can still try to read # from the child_fd -- it will block forever or until TIMEOUT. # For this case, I test isalive() before doing any reading. # If isalive() is false, then I pretend that this is the same as EOF. if not self.isalive(): r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll" if not r: self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.') elif self.__irix_hack: # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive. # This adds a 2 second delay, but only when the child is terminated. r, w, e = self.__select([self.child_fd], [], [], 2) if not r and not self.isalive(): self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.') r,w,e = self.__select([self.child_fd], [], [], timeout) if not r: if not self.isalive(): # Some platforms, such as Irix, will claim that their processes are alive; # then timeout on the select; and then finally admit that they are not alive. self.flag_eof = True raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.') else: raise TIMEOUT ('Timeout exceeded in read_nonblocking().') if self.child_fd in r: try: s = os.read(self.child_fd, size) except OSError, e: # Linux does this self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.') if s == b'': # BSD style self.flag_eof = True raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.') s2 = self._cast_buffer_type(s) if self.logfile is not None: self.logfile.write(s2) self.logfile.flush() if self.logfile_read is not None: self.logfile_read.write(s2) self.logfile_read.flush() return s raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().')
[ "This", "reads", "at", "most", "size", "bytes", "from", "the", "child", "application", ".", "It", "includes", "a", "timeout", ".", "If", "the", "read", "does", "not", "complete", "within", "the", "timeout", "period", "then", "a", "TIMEOUT", "exception", "is", "raised", ".", "If", "the", "end", "of", "file", "is", "read", "then", "an", "EOF", "exception", "will", "be", "raised", ".", "If", "a", "log", "file", "was", "set", "using", "setlog", "()", "then", "all", "data", "will", "also", "be", "written", "to", "the", "log", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L800-L877
[ "def", "read_nonblocking", "(", "self", ",", "size", "=", "1", ",", "timeout", "=", "-", "1", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "'I/O operation on closed file in read_nonblocking().'", ")", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "# Note that some systems such as Solaris do not give an EOF when", "# the child dies. In fact, you can still try to read", "# from the child_fd -- it will block forever or until TIMEOUT.", "# For this case, I test isalive() before doing any reading.", "# If isalive() is false, then I pretend that this is the same as EOF.", "if", "not", "self", ".", "isalive", "(", ")", ":", "r", ",", "w", ",", "e", "=", "self", ".", "__select", "(", "[", "self", ".", "child_fd", "]", ",", "[", "]", ",", "[", "]", ",", "0", ")", "# timeout of 0 means \"poll\"", "if", "not", "r", ":", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF) in read_nonblocking(). Braindead platform.'", ")", "elif", "self", ".", "__irix_hack", ":", "# This is a hack for Irix. It seems that Irix requires a long delay before checking isalive.", "# This adds a 2 second delay, but only when the child is terminated.", "r", ",", "w", ",", "e", "=", "self", ".", "__select", "(", "[", "self", ".", "child_fd", "]", ",", "[", "]", ",", "[", "]", ",", "2", ")", "if", "not", "r", "and", "not", "self", ".", "isalive", "(", ")", ":", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF) in read_nonblocking(). Pokey platform.'", ")", "r", ",", "w", ",", "e", "=", "self", ".", "__select", "(", "[", "self", ".", "child_fd", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "if", "not", "r", ":", "if", "not", "self", ".", "isalive", "(", ")", ":", "# Some platforms, such as Irix, will claim that their processes are alive;", "# then timeout on the select; and then finally admit that they are not alive.", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End of File (EOF) in read_nonblocking(). Very pokey platform.'", ")", "else", ":", "raise", "TIMEOUT", "(", "'Timeout exceeded in read_nonblocking().'", ")", "if", "self", ".", "child_fd", "in", "r", ":", "try", ":", "s", "=", "os", ".", "read", "(", "self", ".", "child_fd", ",", "size", ")", "except", "OSError", ",", "e", ":", "# Linux does this", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF) in read_nonblocking(). Exception style platform.'", ")", "if", "s", "==", "b''", ":", "# BSD style", "self", ".", "flag_eof", "=", "True", "raise", "EOF", "(", "'End Of File (EOF) in read_nonblocking(). Empty string style platform.'", ")", "s2", "=", "self", ".", "_cast_buffer_type", "(", "s", ")", "if", "self", ".", "logfile", "is", "not", "None", ":", "self", ".", "logfile", ".", "write", "(", "s2", ")", "self", ".", "logfile", ".", "flush", "(", ")", "if", "self", ".", "logfile_read", "is", "not", "None", ":", "self", ".", "logfile_read", ".", "write", "(", "s2", ")", "self", ".", "logfile_read", ".", "flush", "(", ")", "return", "s", "raise", "ExceptionPexpect", "(", "'Reached an unexpected state in read_nonblocking().'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.read
This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def read (self, size = -1): # File-like object. """This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. """ if size == 0: return self._empty_buffer if size < 0: self.expect (self.delimiter) # delimiter default is EOF return self.before # I could have done this more directly by not using expect(), but # I deliberately decided to couple read() to expect() so that # I would catch any bugs early and ensure consistant behavior. # It's a little less efficient, but there is less for me to # worry about if I have to later modify read() or expect(). # Note, it's OK if size==-1 in the regex. That just means it # will never match anything in which case we stop only on EOF. if self._buffer_type is bytes: pat = (u'.{%d}' % size).encode('ascii') else: pat = u'.{%d}' % size cre = re.compile(pat, re.DOTALL) index = self.expect ([cre, self.delimiter]) # delimiter default is EOF if index == 0: return self.after ### self.before should be ''. Should I assert this? return self.before
def read (self, size = -1): # File-like object. """This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. """ if size == 0: return self._empty_buffer if size < 0: self.expect (self.delimiter) # delimiter default is EOF return self.before # I could have done this more directly by not using expect(), but # I deliberately decided to couple read() to expect() so that # I would catch any bugs early and ensure consistant behavior. # It's a little less efficient, but there is less for me to # worry about if I have to later modify read() or expect(). # Note, it's OK if size==-1 in the regex. That just means it # will never match anything in which case we stop only on EOF. if self._buffer_type is bytes: pat = (u'.{%d}' % size).encode('ascii') else: pat = u'.{%d}' % size cre = re.compile(pat, re.DOTALL) index = self.expect ([cre, self.delimiter]) # delimiter default is EOF if index == 0: return self.after ### self.before should be ''. Should I assert this? return self.before
[ "This", "reads", "at", "most", "size", "bytes", "from", "the", "file", "(", "less", "if", "the", "read", "hits", "EOF", "before", "obtaining", "size", "bytes", ")", ".", "If", "the", "size", "argument", "is", "negative", "or", "omitted", "read", "all", "data", "until", "EOF", "is", "reached", ".", "The", "bytes", "are", "returned", "as", "a", "string", "object", ".", "An", "empty", "string", "is", "returned", "when", "EOF", "is", "encountered", "immediately", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L879-L907
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "# File-like object.", "if", "size", "==", "0", ":", "return", "self", ".", "_empty_buffer", "if", "size", "<", "0", ":", "self", ".", "expect", "(", "self", ".", "delimiter", ")", "# delimiter default is EOF", "return", "self", ".", "before", "# I could have done this more directly by not using expect(), but", "# I deliberately decided to couple read() to expect() so that", "# I would catch any bugs early and ensure consistant behavior.", "# It's a little less efficient, but there is less for me to", "# worry about if I have to later modify read() or expect().", "# Note, it's OK if size==-1 in the regex. That just means it", "# will never match anything in which case we stop only on EOF.", "if", "self", ".", "_buffer_type", "is", "bytes", ":", "pat", "=", "(", "u'.{%d}'", "%", "size", ")", ".", "encode", "(", "'ascii'", ")", "else", ":", "pat", "=", "u'.{%d}'", "%", "size", "cre", "=", "re", ".", "compile", "(", "pat", ",", "re", ".", "DOTALL", ")", "index", "=", "self", ".", "expect", "(", "[", "cre", ",", "self", ".", "delimiter", "]", ")", "# delimiter default is EOF", "if", "index", "==", "0", ":", "return", "self", ".", "after", "### self.before should be ''. Should I assert this?", "return", "self", ".", "before" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.readline
This reads and returns one entire line. A trailing newline is kept in the string, but may be absent when a file ends with an incomplete line. Note: This readline() looks for a \\r\\n pair even on UNIX because this is what the pseudo tty device returns. So contrary to what you may expect you will receive the newline as \\r\\n. An empty string is returned when EOF is hit immediately. Currently, the size argument is mostly ignored, so this behavior is not standard for a file-like object. If size is 0 then an empty string is returned.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def readline(self, size = -1): """This reads and returns one entire line. A trailing newline is kept in the string, but may be absent when a file ends with an incomplete line. Note: This readline() looks for a \\r\\n pair even on UNIX because this is what the pseudo tty device returns. So contrary to what you may expect you will receive the newline as \\r\\n. An empty string is returned when EOF is hit immediately. Currently, the size argument is mostly ignored, so this behavior is not standard for a file-like object. If size is 0 then an empty string is returned. """ if size == 0: return self._empty_buffer index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF if index == 0: return self.before + self._pty_newline return self.before
def readline(self, size = -1): """This reads and returns one entire line. A trailing newline is kept in the string, but may be absent when a file ends with an incomplete line. Note: This readline() looks for a \\r\\n pair even on UNIX because this is what the pseudo tty device returns. So contrary to what you may expect you will receive the newline as \\r\\n. An empty string is returned when EOF is hit immediately. Currently, the size argument is mostly ignored, so this behavior is not standard for a file-like object. If size is 0 then an empty string is returned. """ if size == 0: return self._empty_buffer index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF if index == 0: return self.before + self._pty_newline return self.before
[ "This", "reads", "and", "returns", "one", "entire", "line", ".", "A", "trailing", "newline", "is", "kept", "in", "the", "string", "but", "may", "be", "absent", "when", "a", "file", "ends", "with", "an", "incomplete", "line", ".", "Note", ":", "This", "readline", "()", "looks", "for", "a", "\\\\", "r", "\\\\", "n", "pair", "even", "on", "UNIX", "because", "this", "is", "what", "the", "pseudo", "tty", "device", "returns", ".", "So", "contrary", "to", "what", "you", "may", "expect", "you", "will", "receive", "the", "newline", "as", "\\\\", "r", "\\\\", "n", ".", "An", "empty", "string", "is", "returned", "when", "EOF", "is", "hit", "immediately", ".", "Currently", "the", "size", "argument", "is", "mostly", "ignored", "so", "this", "behavior", "is", "not", "standard", "for", "a", "file", "-", "like", "object", ".", "If", "size", "is", "0", "then", "an", "empty", "string", "is", "returned", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L909-L924
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "==", "0", ":", "return", "self", ".", "_empty_buffer", "index", "=", "self", ".", "expect", "(", "[", "self", ".", "_pty_newline", ",", "self", ".", "delimiter", "]", ")", "# delimiter default is EOF", "if", "index", "==", "0", ":", "return", "self", ".", "before", "+", "self", ".", "_pty_newline", "return", "self", ".", "before" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.next
This is to support iterators over a file-like object.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == self._empty_buffer: raise StopIteration return result
def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == self._empty_buffer: raise StopIteration return result
[ "This", "is", "to", "support", "iterators", "over", "a", "file", "-", "like", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L933-L941
[ "def", "next", "(", "self", ")", ":", "# File-like object.", "result", "=", "self", ".", "readline", "(", ")", "if", "result", "==", "self", ".", "_empty_buffer", ":", "raise", "StopIteration", "return", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.send
This sends a string to the child process. This returns the number of bytes written. If a log file was set then the data is also written to the log.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def send(self, s): """This sends a string to the child process. This returns the number of bytes written. If a log file was set then the data is also written to the log. """ time.sleep(self.delaybeforesend) s2 = self._cast_buffer_type(s) if self.logfile is not None: self.logfile.write(s2) self.logfile.flush() if self.logfile_send is not None: self.logfile_send.write(s2) self.logfile_send.flush() c = os.write (self.child_fd, _cast_bytes(s, self.encoding)) return c
def send(self, s): """This sends a string to the child process. This returns the number of bytes written. If a log file was set then the data is also written to the log. """ time.sleep(self.delaybeforesend) s2 = self._cast_buffer_type(s) if self.logfile is not None: self.logfile.write(s2) self.logfile.flush() if self.logfile_send is not None: self.logfile_send.write(s2) self.logfile_send.flush() c = os.write (self.child_fd, _cast_bytes(s, self.encoding)) return c
[ "This", "sends", "a", "string", "to", "the", "child", "process", ".", "This", "returns", "the", "number", "of", "bytes", "written", ".", "If", "a", "log", "file", "was", "set", "then", "the", "data", "is", "also", "written", "to", "the", "log", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L973-L989
[ "def", "send", "(", "self", ",", "s", ")", ":", "time", ".", "sleep", "(", "self", ".", "delaybeforesend", ")", "s2", "=", "self", ".", "_cast_buffer_type", "(", "s", ")", "if", "self", ".", "logfile", "is", "not", "None", ":", "self", ".", "logfile", ".", "write", "(", "s2", ")", "self", ".", "logfile", ".", "flush", "(", ")", "if", "self", ".", "logfile_send", "is", "not", "None", ":", "self", ".", "logfile_send", ".", "write", "(", "s2", ")", "self", ".", "logfile_send", ".", "flush", "(", ")", "c", "=", "os", ".", "write", "(", "self", ".", "child_fd", ",", "_cast_bytes", "(", "s", ",", "self", ".", "encoding", ")", ")", "return", "c" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.sendcontrol
This sends a control character to the child such as Ctrl-C or Ctrl-D. For example, to send a Ctrl-G (ASCII 7):: child.sendcontrol('g') See also, sendintr() and sendeof().
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def sendcontrol(self, char): """This sends a control character to the child such as Ctrl-C or Ctrl-D. For example, to send a Ctrl-G (ASCII 7):: child.sendcontrol('g') See also, sendintr() and sendeof(). """ char = char.lower() a = ord(char) if a>=97 and a<=122: a = a - ord('a') + 1 return self.send (chr(a)) d = {'@':0, '`':0, '[':27, '{':27, '\\':28, '|':28, ']':29, '}': 29, '^':30, '~':30, '_':31, '?':127} if char not in d: return 0 return self.send (chr(d[char]))
def sendcontrol(self, char): """This sends a control character to the child such as Ctrl-C or Ctrl-D. For example, to send a Ctrl-G (ASCII 7):: child.sendcontrol('g') See also, sendintr() and sendeof(). """ char = char.lower() a = ord(char) if a>=97 and a<=122: a = a - ord('a') + 1 return self.send (chr(a)) d = {'@':0, '`':0, '[':27, '{':27, '\\':28, '|':28, ']':29, '}': 29, '^':30, '~':30, '_':31, '?':127} if char not in d: return 0 return self.send (chr(d[char]))
[ "This", "sends", "a", "control", "character", "to", "the", "child", "such", "as", "Ctrl", "-", "C", "or", "Ctrl", "-", "D", ".", "For", "example", "to", "send", "a", "Ctrl", "-", "G", "(", "ASCII", "7", ")", "::" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1000-L1024
[ "def", "sendcontrol", "(", "self", ",", "char", ")", ":", "char", "=", "char", ".", "lower", "(", ")", "a", "=", "ord", "(", "char", ")", "if", "a", ">=", "97", "and", "a", "<=", "122", ":", "a", "=", "a", "-", "ord", "(", "'a'", ")", "+", "1", "return", "self", ".", "send", "(", "chr", "(", "a", ")", ")", "d", "=", "{", "'@'", ":", "0", ",", "'`'", ":", "0", ",", "'['", ":", "27", ",", "'{'", ":", "27", ",", "'\\\\'", ":", "28", ",", "'|'", ":", "28", ",", "']'", ":", "29", ",", "'}'", ":", "29", ",", "'^'", ":", "30", ",", "'~'", ":", "30", ",", "'_'", ":", "31", ",", "'?'", ":", "127", "}", "if", "char", "not", "in", "d", ":", "return", "0", "return", "self", ".", "send", "(", "chr", "(", "d", "[", "char", "]", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.sendeof
This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def sendeof(self): """This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line. """ ### Hmmm... how do I send an EOF? ###C if ((m = write(pty, *buf, p - *buf)) < 0) ###C return (errno == EWOULDBLOCK) ? n : -1; #fd = sys.stdin.fileno() #old = termios.tcgetattr(fd) # remember current state #attr = termios.tcgetattr(fd) #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF #try: # use try/finally to ensure state gets restored # termios.tcsetattr(fd, termios.TCSADRAIN, attr) # if hasattr(termios, 'CEOF'): # os.write (self.child_fd, '%c' % termios.CEOF) # else: # # Silly platform does not define CEOF so assume CTRL-D # os.write (self.child_fd, '%c' % 4) #finally: # restore state # termios.tcsetattr(fd, termios.TCSADRAIN, old) if hasattr(termios, 'VEOF'): char = termios.tcgetattr(self.child_fd)[6][termios.VEOF] else: # platform does not define VEOF so assume CTRL-D char = chr(4) self.send(char)
def sendeof(self): """This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line. """ ### Hmmm... how do I send an EOF? ###C if ((m = write(pty, *buf, p - *buf)) < 0) ###C return (errno == EWOULDBLOCK) ? n : -1; #fd = sys.stdin.fileno() #old = termios.tcgetattr(fd) # remember current state #attr = termios.tcgetattr(fd) #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF #try: # use try/finally to ensure state gets restored # termios.tcsetattr(fd, termios.TCSADRAIN, attr) # if hasattr(termios, 'CEOF'): # os.write (self.child_fd, '%c' % termios.CEOF) # else: # # Silly platform does not define CEOF so assume CTRL-D # os.write (self.child_fd, '%c' % 4) #finally: # restore state # termios.tcsetattr(fd, termios.TCSADRAIN, old) if hasattr(termios, 'VEOF'): char = termios.tcgetattr(self.child_fd)[6][termios.VEOF] else: # platform does not define VEOF so assume CTRL-D char = chr(4) self.send(char)
[ "This", "sends", "an", "EOF", "to", "the", "child", ".", "This", "sends", "a", "character", "which", "causes", "the", "pending", "parent", "output", "buffer", "to", "be", "sent", "to", "the", "waiting", "child", "program", "without", "waiting", "for", "end", "-", "of", "-", "line", ".", "If", "it", "is", "the", "first", "character", "of", "the", "line", "the", "read", "()", "in", "the", "user", "program", "returns", "0", "which", "signifies", "end", "-", "of", "-", "file", ".", "This", "means", "to", "work", "as", "expected", "a", "sendeof", "()", "has", "to", "be", "called", "at", "the", "beginning", "of", "a", "line", ".", "This", "method", "does", "not", "send", "a", "newline", ".", "It", "is", "the", "responsibility", "of", "the", "caller", "to", "ensure", "the", "eof", "is", "sent", "at", "the", "beginning", "of", "a", "line", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1026-L1058
[ "def", "sendeof", "(", "self", ")", ":", "### Hmmm... how do I send an EOF?", "###C if ((m = write(pty, *buf, p - *buf)) < 0)", "###C return (errno == EWOULDBLOCK) ? n : -1;", "#fd = sys.stdin.fileno()", "#old = termios.tcgetattr(fd) # remember current state", "#attr = termios.tcgetattr(fd)", "#attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF", "#try: # use try/finally to ensure state gets restored", "# termios.tcsetattr(fd, termios.TCSADRAIN, attr)", "# if hasattr(termios, 'CEOF'):", "# os.write (self.child_fd, '%c' % termios.CEOF)", "# else:", "# # Silly platform does not define CEOF so assume CTRL-D", "# os.write (self.child_fd, '%c' % 4)", "#finally: # restore state", "# termios.tcsetattr(fd, termios.TCSADRAIN, old)", "if", "hasattr", "(", "termios", ",", "'VEOF'", ")", ":", "char", "=", "termios", ".", "tcgetattr", "(", "self", ".", "child_fd", ")", "[", "6", "]", "[", "termios", ".", "VEOF", "]", "else", ":", "# platform does not define VEOF so assume CTRL-D", "char", "=", "chr", "(", "4", ")", "self", ".", "send", "(", "char", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.sendintr
This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def sendintr(self): """This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. """ if hasattr(termios, 'VINTR'): char = termios.tcgetattr(self.child_fd)[6][termios.VINTR] else: # platform does not define VINTR so assume CTRL-C char = chr(3) self.send (char)
def sendintr(self): """This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. """ if hasattr(termios, 'VINTR'): char = termios.tcgetattr(self.child_fd)[6][termios.VINTR] else: # platform does not define VINTR so assume CTRL-C char = chr(3) self.send (char)
[ "This", "sends", "a", "SIGINT", "to", "the", "child", ".", "It", "does", "not", "require", "the", "SIGINT", "to", "be", "the", "first", "character", "on", "a", "line", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1060-L1070
[ "def", "sendintr", "(", "self", ")", ":", "if", "hasattr", "(", "termios", ",", "'VINTR'", ")", ":", "char", "=", "termios", ".", "tcgetattr", "(", "self", ".", "child_fd", ")", "[", "6", "]", "[", "termios", ".", "VINTR", "]", "else", ":", "# platform does not define VINTR so assume CTRL-C", "char", "=", "chr", "(", "3", ")", "self", ".", "send", "(", "char", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.compile_pattern_list
This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(clp, timeout) ...
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def compile_pattern_list(self, patterns): """This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(clp, timeout) ... """ if patterns is None: return [] if not isinstance(patterns, list): patterns = [patterns] compile_flags = re.DOTALL # Allow dot to match \n if self.ignorecase: compile_flags = compile_flags | re.IGNORECASE compiled_pattern_list = [] for p in patterns: if isinstance(p, (bytes, unicode)): p = self._cast_buffer_type(p) compiled_pattern_list.append(re.compile(p, compile_flags)) elif p is EOF: compiled_pattern_list.append(EOF) elif p is TIMEOUT: compiled_pattern_list.append(TIMEOUT) elif type(p) is re_type: p = self._prepare_regex_pattern(p) compiled_pattern_list.append(p) else: raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p))) return compiled_pattern_list
def compile_pattern_list(self, patterns): """This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(clp, timeout) ... """ if patterns is None: return [] if not isinstance(patterns, list): patterns = [patterns] compile_flags = re.DOTALL # Allow dot to match \n if self.ignorecase: compile_flags = compile_flags | re.IGNORECASE compiled_pattern_list = [] for p in patterns: if isinstance(p, (bytes, unicode)): p = self._cast_buffer_type(p) compiled_pattern_list.append(re.compile(p, compile_flags)) elif p is EOF: compiled_pattern_list.append(EOF) elif p is TIMEOUT: compiled_pattern_list.append(TIMEOUT) elif type(p) is re_type: p = self._prepare_regex_pattern(p) compiled_pattern_list.append(p) else: raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p))) return compiled_pattern_list
[ "This", "compiles", "a", "pattern", "-", "string", "or", "a", "list", "of", "pattern", "-", "strings", ".", "Patterns", "must", "be", "a", "StringType", "EOF", "TIMEOUT", "SRE_Pattern", "or", "a", "list", "of", "those", ".", "Patterns", "may", "also", "be", "None", "which", "results", "in", "an", "empty", "list", "(", "you", "might", "do", "this", "if", "waiting", "for", "an", "EOF", "or", "TIMEOUT", "condition", "without", "expecting", "any", "pattern", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1220-L1268
[ "def", "compile_pattern_list", "(", "self", ",", "patterns", ")", ":", "if", "patterns", "is", "None", ":", "return", "[", "]", "if", "not", "isinstance", "(", "patterns", ",", "list", ")", ":", "patterns", "=", "[", "patterns", "]", "compile_flags", "=", "re", ".", "DOTALL", "# Allow dot to match \\n", "if", "self", ".", "ignorecase", ":", "compile_flags", "=", "compile_flags", "|", "re", ".", "IGNORECASE", "compiled_pattern_list", "=", "[", "]", "for", "p", "in", "patterns", ":", "if", "isinstance", "(", "p", ",", "(", "bytes", ",", "unicode", ")", ")", ":", "p", "=", "self", ".", "_cast_buffer_type", "(", "p", ")", "compiled_pattern_list", ".", "append", "(", "re", ".", "compile", "(", "p", ",", "compile_flags", ")", ")", "elif", "p", "is", "EOF", ":", "compiled_pattern_list", ".", "append", "(", "EOF", ")", "elif", "p", "is", "TIMEOUT", ":", "compiled_pattern_list", ".", "append", "(", "TIMEOUT", ")", "elif", "type", "(", "p", ")", "is", "re_type", ":", "p", "=", "self", ".", "_prepare_regex_pattern", "(", "p", ")", "compiled_pattern_list", ".", "append", "(", "p", ")", "else", ":", "raise", "TypeError", "(", "'Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s'", "%", "str", "(", "type", "(", "p", ")", ")", ")", "return", "compiled_pattern_list" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb._prepare_regex_pattern
Recompile unicode regexes as bytes regexes. Overridden in subclass.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def _prepare_regex_pattern(self, p): "Recompile unicode regexes as bytes regexes. Overridden in subclass." if isinstance(p.pattern, unicode): p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE) return p
def _prepare_regex_pattern(self, p): "Recompile unicode regexes as bytes regexes. Overridden in subclass." if isinstance(p.pattern, unicode): p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE) return p
[ "Recompile", "unicode", "regexes", "as", "bytes", "regexes", ".", "Overridden", "in", "subclass", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1270-L1274
[ "def", "_prepare_regex_pattern", "(", "self", ",", "p", ")", ":", "if", "isinstance", "(", "p", ".", "pattern", ",", "unicode", ")", ":", "p", "=", "re", ".", "compile", "(", "p", ".", "pattern", ".", "encode", "(", "'utf-8'", ")", ",", "p", ".", "flags", "&", "~", "re", ".", "UNICODE", ")", "return", "p" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.expect
This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect (['bar', 'foo', 'foobar']) # returns 1 ('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect (['foobar', 'foo']) # returns 0 ('foobar') if all input is available at once, # but returs 1 ('foo') if parts of the final 'bar' arrive late After a match is found the instance attributes 'before', 'after' and 'match' will be set. You can see all the data read before the match in 'before'. You can see the data that was matched in 'after'. The re.MatchObject used in the re match will be in 'match'. If an error occurred then 'before' will be set to all the data read so far and 'after' and 'match' will be None. If timeout is -1 then timeout will be set to the self.timeout value. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect (['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect (pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list().
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def expect(self, pattern, timeout = -1, searchwindowsize=-1): """This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect (['bar', 'foo', 'foobar']) # returns 1 ('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect (['foobar', 'foo']) # returns 0 ('foobar') if all input is available at once, # but returs 1 ('foo') if parts of the final 'bar' arrive late After a match is found the instance attributes 'before', 'after' and 'match' will be set. You can see all the data read before the match in 'before'. You can see the data that was matched in 'after'. The re.MatchObject used in the re match will be in 'match'. If an error occurred then 'before' will be set to all the data read so far and 'after' and 'match' will be None. If timeout is -1 then timeout will be set to the self.timeout value. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect (['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect (pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list(). """ compiled_pattern_list = self.compile_pattern_list(pattern) return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
def expect(self, pattern, timeout = -1, searchwindowsize=-1): """This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception. If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:: # the input is 'foobar' index = p.expect (['bar', 'foo', 'foobar']) # returns 1 ('foo') even though 'foobar' is a "better" match Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:: # the input is 'foobar' index = p.expect (['foobar', 'foo']) # returns 0 ('foobar') if all input is available at once, # but returs 1 ('foo') if parts of the final 'bar' arrive late After a match is found the instance attributes 'before', 'after' and 'match' will be set. You can see all the data read before the match in 'before'. You can see the data that was matched in 'after'. The re.MatchObject used in the re match will be in 'match'. If an error occurred then 'before' will be set to all the data read so far and 'after' and 'match' will be None. If timeout is -1 then timeout will be set to the self.timeout value. A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute 'after' will be set to the exception type. The attribute 'match' will be None. This allows you to write code like this:: index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: do_something() elif index == 1: do_something_else() elif index == 2: do_some_other_thing() elif index == 3: do_something_completely_different() instead of code like this:: try: index = p.expect (['good', 'bad']) if index == 0: do_something() elif index == 1: do_something_else() except EOF: do_some_other_thing() except TIMEOUT: do_something_completely_different() These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:: p = pexpect.spawn('/bin/ls') p.expect (pexpect.EOF) print p.before If you are trying to optimize for speed then see expect_list(). """ compiled_pattern_list = self.compile_pattern_list(pattern) return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
[ "This", "seeks", "through", "the", "stream", "until", "a", "pattern", "is", "matched", ".", "The", "pattern", "is", "overloaded", "and", "may", "take", "several", "types", ".", "The", "pattern", "can", "be", "a", "StringType", "EOF", "a", "compiled", "re", "or", "a", "list", "of", "any", "of", "those", "types", ".", "Strings", "will", "be", "compiled", "to", "re", "types", ".", "This", "returns", "the", "index", "into", "the", "pattern", "list", ".", "If", "the", "pattern", "was", "not", "a", "list", "this", "returns", "index", "0", "on", "a", "successful", "match", ".", "This", "may", "raise", "exceptions", "for", "EOF", "or", "TIMEOUT", ".", "To", "avoid", "the", "EOF", "or", "TIMEOUT", "exceptions", "add", "EOF", "or", "TIMEOUT", "to", "the", "pattern", "list", ".", "That", "will", "cause", "expect", "to", "match", "an", "EOF", "or", "TIMEOUT", "condition", "instead", "of", "raising", "an", "exception", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1276-L1354
[ "def", "expect", "(", "self", ",", "pattern", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ")", ":", "compiled_pattern_list", "=", "self", ".", "compile_pattern_list", "(", "pattern", ")", "return", "self", ".", "expect_list", "(", "compiled_pattern_list", ",", "timeout", ",", "searchwindowsize", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.expect_list
This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT (which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). If timeout==-1 then the self.timeout value is used. If searchwindowsize==-1 then the self.searchwindowsize value is used.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1): """This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT (which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). If timeout==-1 then the self.timeout value is used. If searchwindowsize==-1 then the self.searchwindowsize value is used. """ return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1): """This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT (which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). If timeout==-1 then the self.timeout value is used. If searchwindowsize==-1 then the self.searchwindowsize value is used. """ return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
[ "This", "takes", "a", "list", "of", "compiled", "regular", "expressions", "and", "returns", "the", "index", "into", "the", "pattern_list", "that", "matched", "the", "child", "output", ".", "The", "list", "may", "also", "contain", "EOF", "or", "TIMEOUT", "(", "which", "are", "not", "compiled", "regular", "expressions", ")", ".", "This", "method", "is", "similar", "to", "the", "expect", "()", "method", "except", "that", "expect_list", "()", "does", "not", "recompile", "the", "pattern", "list", "on", "every", "call", ".", "This", "may", "help", "if", "you", "are", "trying", "to", "optimize", "for", "speed", "otherwise", "just", "use", "the", "expect", "()", "method", ".", "This", "is", "called", "by", "expect", "()", ".", "If", "timeout", "==", "-", "1", "then", "the", "self", ".", "timeout", "value", "is", "used", ".", "If", "searchwindowsize", "==", "-", "1", "then", "the", "self", ".", "searchwindowsize", "value", "is", "used", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1356-L1368
[ "def", "expect_list", "(", "self", ",", "pattern_list", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ")", ":", "return", "self", ".", "expect_loop", "(", "searcher_re", "(", "pattern_list", ")", ",", "timeout", ",", "searchwindowsize", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.expect_exact
This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): """This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match.""" if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF): pattern_list = [pattern_list] return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): """This is similar to expect(), but uses plain string matching instead of compiled regular expressions in 'pattern_list'. The 'pattern_list' may be a string; a list or other sequence of strings; or TIMEOUT and EOF. This call might be faster than expect() for two reasons: string searching is faster than RE matching and it is possible to limit the search to just the end of the input buffer. This method is also useful when you don't want to have to worry about escaping regular expression characters that you want to match.""" if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF): pattern_list = [pattern_list] return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
[ "This", "is", "similar", "to", "expect", "()", "but", "uses", "plain", "string", "matching", "instead", "of", "compiled", "regular", "expressions", "in", "pattern_list", ".", "The", "pattern_list", "may", "be", "a", "string", ";", "a", "list", "or", "other", "sequence", "of", "strings", ";", "or", "TIMEOUT", "and", "EOF", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1370-L1386
[ "def", "expect_exact", "(", "self", ",", "pattern_list", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ")", ":", "if", "isinstance", "(", "pattern_list", ",", "(", "bytes", ",", "unicode", ")", ")", "or", "pattern_list", "in", "(", "TIMEOUT", ",", "EOF", ")", ":", "pattern_list", "=", "[", "pattern_list", "]", "return", "self", ".", "expect_loop", "(", "searcher_string", "(", "pattern_list", ")", ",", "timeout", ",", "searchwindowsize", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.expect_loop
This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1): """This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions. """ self.searcher = searcher if timeout == -1: timeout = self.timeout if timeout is not None: end_time = time.time() + timeout if searchwindowsize == -1: searchwindowsize = self.searchwindowsize try: incoming = self.buffer freshlen = len(incoming) while True: # Keep reading until exception or return. index = searcher.search(incoming, freshlen, searchwindowsize) if index >= 0: self.buffer = incoming[searcher.end : ] self.before = incoming[ : searcher.start] self.after = incoming[searcher.start : searcher.end] self.match = searcher.match self.match_index = index return self.match_index # No match at this point if timeout is not None and timeout < 0: raise TIMEOUT ('Timeout exceeded in expect_any().') # Still have time left, so read more data c = self.read_nonblocking (self.maxread, timeout) freshlen = len(c) time.sleep (0.0001) incoming = incoming + c if timeout is not None: timeout = end_time - time.time() except EOF, e: self.buffer = self._empty_buffer self.before = incoming self.after = EOF index = searcher.eof_index if index >= 0: self.match = EOF self.match_index = index return self.match_index else: self.match = None self.match_index = None raise EOF (str(e) + '\n' + str(self)) except TIMEOUT, e: self.buffer = incoming self.before = incoming self.after = TIMEOUT index = searcher.timeout_index if index >= 0: self.match = TIMEOUT self.match_index = index return self.match_index else: self.match = None self.match_index = None raise TIMEOUT (str(e) + '\n' + str(self)) except: self.before = incoming self.after = None self.match = None self.match_index = None raise
def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1): """This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return value and exceptions. """ self.searcher = searcher if timeout == -1: timeout = self.timeout if timeout is not None: end_time = time.time() + timeout if searchwindowsize == -1: searchwindowsize = self.searchwindowsize try: incoming = self.buffer freshlen = len(incoming) while True: # Keep reading until exception or return. index = searcher.search(incoming, freshlen, searchwindowsize) if index >= 0: self.buffer = incoming[searcher.end : ] self.before = incoming[ : searcher.start] self.after = incoming[searcher.start : searcher.end] self.match = searcher.match self.match_index = index return self.match_index # No match at this point if timeout is not None and timeout < 0: raise TIMEOUT ('Timeout exceeded in expect_any().') # Still have time left, so read more data c = self.read_nonblocking (self.maxread, timeout) freshlen = len(c) time.sleep (0.0001) incoming = incoming + c if timeout is not None: timeout = end_time - time.time() except EOF, e: self.buffer = self._empty_buffer self.before = incoming self.after = EOF index = searcher.eof_index if index >= 0: self.match = EOF self.match_index = index return self.match_index else: self.match = None self.match_index = None raise EOF (str(e) + '\n' + str(self)) except TIMEOUT, e: self.buffer = incoming self.before = incoming self.after = TIMEOUT index = searcher.timeout_index if index >= 0: self.match = TIMEOUT self.match_index = index return self.match_index else: self.match = None self.match_index = None raise TIMEOUT (str(e) + '\n' + str(self)) except: self.before = incoming self.after = None self.match = None self.match_index = None raise
[ "This", "is", "the", "common", "loop", "used", "inside", "expect", ".", "The", "searcher", "should", "be", "an", "instance", "of", "searcher_re", "or", "searcher_string", "which", "describes", "how", "and", "what", "to", "search", "for", "in", "the", "input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1388-L1458
[ "def", "expect_loop", "(", "self", ",", "searcher", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ")", ":", "self", ".", "searcher", "=", "searcher", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "if", "timeout", "is", "not", "None", ":", "end_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "if", "searchwindowsize", "==", "-", "1", ":", "searchwindowsize", "=", "self", ".", "searchwindowsize", "try", ":", "incoming", "=", "self", ".", "buffer", "freshlen", "=", "len", "(", "incoming", ")", "while", "True", ":", "# Keep reading until exception or return.", "index", "=", "searcher", ".", "search", "(", "incoming", ",", "freshlen", ",", "searchwindowsize", ")", "if", "index", ">=", "0", ":", "self", ".", "buffer", "=", "incoming", "[", "searcher", ".", "end", ":", "]", "self", ".", "before", "=", "incoming", "[", ":", "searcher", ".", "start", "]", "self", ".", "after", "=", "incoming", "[", "searcher", ".", "start", ":", "searcher", ".", "end", "]", "self", ".", "match", "=", "searcher", ".", "match", "self", ".", "match_index", "=", "index", "return", "self", ".", "match_index", "# No match at this point", "if", "timeout", "is", "not", "None", "and", "timeout", "<", "0", ":", "raise", "TIMEOUT", "(", "'Timeout exceeded in expect_any().'", ")", "# Still have time left, so read more data", "c", "=", "self", ".", "read_nonblocking", "(", "self", ".", "maxread", ",", "timeout", ")", "freshlen", "=", "len", "(", "c", ")", "time", ".", "sleep", "(", "0.0001", ")", "incoming", "=", "incoming", "+", "c", "if", "timeout", "is", "not", "None", ":", "timeout", "=", "end_time", "-", "time", ".", "time", "(", ")", "except", "EOF", ",", "e", ":", "self", ".", "buffer", "=", "self", ".", "_empty_buffer", "self", ".", "before", "=", "incoming", "self", ".", "after", "=", "EOF", "index", "=", "searcher", ".", "eof_index", "if", "index", ">=", "0", ":", "self", ".", "match", "=", "EOF", "self", ".", "match_index", "=", "index", "return", "self", ".", "match_index", "else", ":", "self", ".", "match", "=", "None", "self", ".", "match_index", "=", "None", "raise", "EOF", "(", "str", "(", "e", ")", "+", "'\\n'", "+", "str", "(", "self", ")", ")", "except", "TIMEOUT", ",", "e", ":", "self", ".", "buffer", "=", "incoming", "self", ".", "before", "=", "incoming", "self", ".", "after", "=", "TIMEOUT", "index", "=", "searcher", ".", "timeout_index", "if", "index", ">=", "0", ":", "self", ".", "match", "=", "TIMEOUT", "self", ".", "match_index", "=", "index", "return", "self", ".", "match_index", "else", ":", "self", ".", "match", "=", "None", "self", ".", "match_index", "=", "None", "raise", "TIMEOUT", "(", "str", "(", "e", ")", "+", "'\\n'", "+", "str", "(", "self", ")", ")", "except", ":", "self", ".", "before", "=", "incoming", "self", ".", "after", "=", "None", "self", ".", "match", "=", "None", "self", ".", "match_index", "=", "None", "raise" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.getwinsize
This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols).
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def getwinsize(self): """This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols). """ TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L) s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) return struct.unpack('HHHH', x)[0:2]
def getwinsize(self): """This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols). """ TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L) s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) return struct.unpack('HHHH', x)[0:2]
[ "This", "returns", "the", "terminal", "window", "size", "of", "the", "child", "tty", ".", "The", "return", "value", "is", "a", "tuple", "of", "(", "rows", "cols", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1460-L1468
[ "def", "getwinsize", "(", "self", ")", ":", "TIOCGWINSZ", "=", "getattr", "(", "termios", ",", "'TIOCGWINSZ'", ",", "1074295912L", ")", "s", "=", "struct", ".", "pack", "(", "'HHHH'", ",", "0", ",", "0", ",", "0", ",", "0", ")", "x", "=", "fcntl", ".", "ioctl", "(", "self", ".", "fileno", "(", ")", ",", "TIOCGWINSZ", ",", "s", ")", "return", "struct", ".", "unpack", "(", "'HHHH'", ",", "x", ")", "[", "0", ":", "2", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.setwinsize
This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def setwinsize(self, r, c): """This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal. """ # Check for buggy platforms. Some Python versions on some platforms # (notably OSF1 Alpha and RedHat 7.1) truncate the value for # termios.TIOCSWINSZ. It is not clear why this happens. # These platforms don't seem to handle the signed int very well; # yet other platforms like OpenBSD have a large negative value for # TIOCSWINSZ and they don't have a truncate problem. # Newer versions of Linux have totally different values for TIOCSWINSZ. # Note that this fix is a hack. TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2. TIOCSWINSZ = -2146929561 # Same bits, but with sign. # Note, assume ws_xpixel and ws_ypixel are zero. s = struct.pack('HHHH', r, c, 0, 0) fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
def setwinsize(self, r, c): """This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal. """ # Check for buggy platforms. Some Python versions on some platforms # (notably OSF1 Alpha and RedHat 7.1) truncate the value for # termios.TIOCSWINSZ. It is not clear why this happens. # These platforms don't seem to handle the signed int very well; # yet other platforms like OpenBSD have a large negative value for # TIOCSWINSZ and they don't have a truncate problem. # Newer versions of Linux have totally different values for TIOCSWINSZ. # Note that this fix is a hack. TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2. TIOCSWINSZ = -2146929561 # Same bits, but with sign. # Note, assume ws_xpixel and ws_ypixel are zero. s = struct.pack('HHHH', r, c, 0, 0) fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
[ "This", "sets", "the", "terminal", "window", "size", "of", "the", "child", "tty", ".", "This", "will", "cause", "a", "SIGWINCH", "signal", "to", "be", "sent", "to", "the", "child", ".", "This", "does", "not", "change", "the", "physical", "window", "size", ".", "It", "changes", "the", "size", "reported", "to", "TTY", "-", "aware", "applications", "like", "vi", "or", "curses", "--", "applications", "that", "respond", "to", "the", "SIGWINCH", "signal", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1470-L1491
[ "def", "setwinsize", "(", "self", ",", "r", ",", "c", ")", ":", "# Check for buggy platforms. Some Python versions on some platforms", "# (notably OSF1 Alpha and RedHat 7.1) truncate the value for", "# termios.TIOCSWINSZ. It is not clear why this happens.", "# These platforms don't seem to handle the signed int very well;", "# yet other platforms like OpenBSD have a large negative value for", "# TIOCSWINSZ and they don't have a truncate problem.", "# Newer versions of Linux have totally different values for TIOCSWINSZ.", "# Note that this fix is a hack.", "TIOCSWINSZ", "=", "getattr", "(", "termios", ",", "'TIOCSWINSZ'", ",", "-", "2146929561", ")", "if", "TIOCSWINSZ", "==", "2148037735L", ":", "# L is not required in Python >= 2.2.", "TIOCSWINSZ", "=", "-", "2146929561", "# Same bits, but with sign.", "# Note, assume ws_xpixel and ws_ypixel are zero.", "s", "=", "struct", ".", "pack", "(", "'HHHH'", ",", "r", ",", "c", ",", "0", ",", "0", ")", "fcntl", ".", "ioctl", "(", "self", ".", "fileno", "(", ")", ",", "TIOCSWINSZ", ",", "s", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.interact
This gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin. When the user types the escape_character this method will stop. The default for escape_character is ^]. This should not be confused with ASCII 27 -- the ESC character. ASCII 29 was chosen for historical merit because this is the character used by 'telnet' as the escape character. The escape_character will not be sent to the child process. You may pass in optional input and output filter functions. These functions should take a string and return a string. The output_filter will be passed all the output from the child process. The input_filter will be passed all the keyboard input from the user. The input_filter is run BEFORE the check for the escape_character. Note that if you change the window size of the parent the SIGWINCH signal will not be passed through to the child. If you want the child window size to change when the parent's window size changes then do something like the following example:: import pexpect, struct, fcntl, termios, signal, sys def sigwinch_passthrough (sig, data): s = struct.pack("HHHH", 0, 0, 0, 0) a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) global p p.setwinsize(a[0],a[1]) p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough. signal.signal(signal.SIGWINCH, sigwinch_passthrough) p.interact()
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None): """This gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin. When the user types the escape_character this method will stop. The default for escape_character is ^]. This should not be confused with ASCII 27 -- the ESC character. ASCII 29 was chosen for historical merit because this is the character used by 'telnet' as the escape character. The escape_character will not be sent to the child process. You may pass in optional input and output filter functions. These functions should take a string and return a string. The output_filter will be passed all the output from the child process. The input_filter will be passed all the keyboard input from the user. The input_filter is run BEFORE the check for the escape_character. Note that if you change the window size of the parent the SIGWINCH signal will not be passed through to the child. If you want the child window size to change when the parent's window size changes then do something like the following example:: import pexpect, struct, fcntl, termios, signal, sys def sigwinch_passthrough (sig, data): s = struct.pack("HHHH", 0, 0, 0, 0) a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) global p p.setwinsize(a[0],a[1]) p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough. signal.signal(signal.SIGWINCH, sigwinch_passthrough) p.interact() """ # Flush the buffer. if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding)) else: self.stdout.write(self.buffer) self.stdout.flush() self.buffer = self._empty_buffer mode = tty.tcgetattr(self.STDIN_FILENO) tty.setraw(self.STDIN_FILENO) try: self.__interact_copy(escape_character, input_filter, output_filter) finally: tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None): """This gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin. When the user types the escape_character this method will stop. The default for escape_character is ^]. This should not be confused with ASCII 27 -- the ESC character. ASCII 29 was chosen for historical merit because this is the character used by 'telnet' as the escape character. The escape_character will not be sent to the child process. You may pass in optional input and output filter functions. These functions should take a string and return a string. The output_filter will be passed all the output from the child process. The input_filter will be passed all the keyboard input from the user. The input_filter is run BEFORE the check for the escape_character. Note that if you change the window size of the parent the SIGWINCH signal will not be passed through to the child. If you want the child window size to change when the parent's window size changes then do something like the following example:: import pexpect, struct, fcntl, termios, signal, sys def sigwinch_passthrough (sig, data): s = struct.pack("HHHH", 0, 0, 0, 0) a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) global p p.setwinsize(a[0],a[1]) p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough. signal.signal(signal.SIGWINCH, sigwinch_passthrough) p.interact() """ # Flush the buffer. if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding)) else: self.stdout.write(self.buffer) self.stdout.flush() self.buffer = self._empty_buffer mode = tty.tcgetattr(self.STDIN_FILENO) tty.setraw(self.STDIN_FILENO) try: self.__interact_copy(escape_character, input_filter, output_filter) finally: tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
[ "This", "gives", "control", "of", "the", "child", "process", "to", "the", "interactive", "user", "(", "the", "human", "at", "the", "keyboard", ")", ".", "Keystrokes", "are", "sent", "to", "the", "child", "process", "and", "the", "stdout", "and", "stderr", "output", "of", "the", "child", "process", "is", "printed", ".", "This", "simply", "echos", "the", "child", "stdout", "and", "child", "stderr", "to", "the", "real", "stdout", "and", "it", "echos", "the", "real", "stdin", "to", "the", "child", "stdin", ".", "When", "the", "user", "types", "the", "escape_character", "this", "method", "will", "stop", ".", "The", "default", "for", "escape_character", "is", "^", "]", ".", "This", "should", "not", "be", "confused", "with", "ASCII", "27", "--", "the", "ESC", "character", ".", "ASCII", "29", "was", "chosen", "for", "historical", "merit", "because", "this", "is", "the", "character", "used", "by", "telnet", "as", "the", "escape", "character", ".", "The", "escape_character", "will", "not", "be", "sent", "to", "the", "child", "process", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1493-L1538
[ "def", "interact", "(", "self", ",", "escape_character", "=", "b'\\x1d'", ",", "input_filter", "=", "None", ",", "output_filter", "=", "None", ")", ":", "# Flush the buffer.", "if", "PY3", ":", "self", ".", "stdout", ".", "write", "(", "_cast_unicode", "(", "self", ".", "buffer", ",", "self", ".", "encoding", ")", ")", "else", ":", "self", ".", "stdout", ".", "write", "(", "self", ".", "buffer", ")", "self", ".", "stdout", ".", "flush", "(", ")", "self", ".", "buffer", "=", "self", ".", "_empty_buffer", "mode", "=", "tty", ".", "tcgetattr", "(", "self", ".", "STDIN_FILENO", ")", "tty", ".", "setraw", "(", "self", ".", "STDIN_FILENO", ")", "try", ":", "self", ".", "__interact_copy", "(", "escape_character", ",", "input_filter", ",", "output_filter", ")", "finally", ":", "tty", ".", "tcsetattr", "(", "self", ".", "STDIN_FILENO", ",", "tty", ".", "TCSAFLUSH", ",", "mode", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.__interact_copy
This is used by the interact() method.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None): """This is used by the interact() method. """ while self.isalive(): r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], []) if self.child_fd in r: data = self.__interact_read(self.child_fd) if output_filter: data = output_filter(data) if self.logfile is not None: self.logfile.write (data) self.logfile.flush() os.write(self.STDOUT_FILENO, data) if self.STDIN_FILENO in r: data = self.__interact_read(self.STDIN_FILENO) if input_filter: data = input_filter(data) i = data.rfind(escape_character) if i != -1: data = data[:i] self.__interact_writen(self.child_fd, data) break self.__interact_writen(self.child_fd, data)
def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None): """This is used by the interact() method. """ while self.isalive(): r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], []) if self.child_fd in r: data = self.__interact_read(self.child_fd) if output_filter: data = output_filter(data) if self.logfile is not None: self.logfile.write (data) self.logfile.flush() os.write(self.STDOUT_FILENO, data) if self.STDIN_FILENO in r: data = self.__interact_read(self.STDIN_FILENO) if input_filter: data = input_filter(data) i = data.rfind(escape_character) if i != -1: data = data[:i] self.__interact_writen(self.child_fd, data) break self.__interact_writen(self.child_fd, data)
[ "This", "is", "used", "by", "the", "interact", "()", "method", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1556-L1578
[ "def", "__interact_copy", "(", "self", ",", "escape_character", "=", "None", ",", "input_filter", "=", "None", ",", "output_filter", "=", "None", ")", ":", "while", "self", ".", "isalive", "(", ")", ":", "r", ",", "w", ",", "e", "=", "self", ".", "__select", "(", "[", "self", ".", "child_fd", ",", "self", ".", "STDIN_FILENO", "]", ",", "[", "]", ",", "[", "]", ")", "if", "self", ".", "child_fd", "in", "r", ":", "data", "=", "self", ".", "__interact_read", "(", "self", ".", "child_fd", ")", "if", "output_filter", ":", "data", "=", "output_filter", "(", "data", ")", "if", "self", ".", "logfile", "is", "not", "None", ":", "self", ".", "logfile", ".", "write", "(", "data", ")", "self", ".", "logfile", ".", "flush", "(", ")", "os", ".", "write", "(", "self", ".", "STDOUT_FILENO", ",", "data", ")", "if", "self", ".", "STDIN_FILENO", "in", "r", ":", "data", "=", "self", ".", "__interact_read", "(", "self", ".", "STDIN_FILENO", ")", "if", "input_filter", ":", "data", "=", "input_filter", "(", "data", ")", "i", "=", "data", ".", "rfind", "(", "escape_character", ")", "if", "i", "!=", "-", "1", ":", "data", "=", "data", "[", ":", "i", "]", "self", ".", "__interact_writen", "(", "self", ".", "child_fd", ",", "data", ")", "break", "self", ".", "__interact_writen", "(", "self", ".", "child_fd", ",", "data", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawnb.__select
This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize).
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def __select (self, iwtd, owtd, ewtd, timeout=None): """This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). """ # if select() is interrupted by a signal (errno==EINTR) then # we loop back and enter the select() again. if timeout is not None: end_time = time.time() + timeout while True: try: return select.select (iwtd, owtd, ewtd, timeout) except select.error as e: if e.args[0] == errno.EINTR: # if we loop back we have to subtract the amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return ([],[],[]) else: # something else caused the select.error, so this really is an exception raise
def __select (self, iwtd, owtd, ewtd, timeout=None): """This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). """ # if select() is interrupted by a signal (errno==EINTR) then # we loop back and enter the select() again. if timeout is not None: end_time = time.time() + timeout while True: try: return select.select (iwtd, owtd, ewtd, timeout) except select.error as e: if e.args[0] == errno.EINTR: # if we loop back we have to subtract the amount of time we already waited. if timeout is not None: timeout = end_time - time.time() if timeout < 0: return ([],[],[]) else: # something else caused the select.error, so this really is an exception raise
[ "This", "is", "a", "wrapper", "around", "select", ".", "select", "()", "that", "ignores", "signals", ".", "If", "select", ".", "select", "raises", "a", "select", ".", "error", "exception", "and", "errno", "is", "an", "EINTR", "error", "then", "it", "is", "ignored", ".", "Mainly", "this", "is", "used", "to", "ignore", "sigwinch", "(", "terminal", "resize", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1580-L1602
[ "def", "__select", "(", "self", ",", "iwtd", ",", "owtd", ",", "ewtd", ",", "timeout", "=", "None", ")", ":", "# if select() is interrupted by a signal (errno==EINTR) then", "# we loop back and enter the select() again.", "if", "timeout", "is", "not", "None", ":", "end_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "True", ":", "try", ":", "return", "select", ".", "select", "(", "iwtd", ",", "owtd", ",", "ewtd", ",", "timeout", ")", "except", "select", ".", "error", "as", "e", ":", "if", "e", ".", "args", "[", "0", "]", "==", "errno", ".", "EINTR", ":", "# if we loop back we have to subtract the amount of time we already waited.", "if", "timeout", "is", "not", "None", ":", "timeout", "=", "end_time", "-", "time", ".", "time", "(", ")", "if", "timeout", "<", "0", ":", "return", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "else", ":", "# something else caused the select.error, so this really is an exception", "raise" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
spawn._prepare_regex_pattern
Recompile bytes regexes as unicode regexes.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def _prepare_regex_pattern(self, p): "Recompile bytes regexes as unicode regexes." if isinstance(p.pattern, bytes): p = re.compile(p.pattern.decode(self.encoding), p.flags) return p
def _prepare_regex_pattern(self, p): "Recompile bytes regexes as unicode regexes." if isinstance(p.pattern, bytes): p = re.compile(p.pattern.decode(self.encoding), p.flags) return p
[ "Recompile", "bytes", "regexes", "as", "unicode", "regexes", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1620-L1624
[ "def", "_prepare_regex_pattern", "(", "self", ",", "p", ")", ":", "if", "isinstance", "(", "p", ".", "pattern", ",", "bytes", ")", ":", "p", "=", "re", ".", "compile", "(", "p", ".", "pattern", ".", "decode", "(", "self", ".", "encoding", ")", ",", "p", ".", "flags", ")", "return", "p" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
searcher_string.search
This searches 'buffer' for the first occurence of one of the search strings. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. It helps to avoid searching the same, possibly big, buffer over and over again. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, this returns -1.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the search strings. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. It helps to avoid searching the same, possibly big, buffer over and over again. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, this returns -1. """ absurd_match = len(buffer) first_match = absurd_match # 'freshlen' helps a lot here. Further optimizations could # possibly include: # # using something like the Boyer-Moore Fast String Searching # Algorithm; pre-compiling the search through a list of # strings into something that can scan the input once to # search for all N strings; realize that if we search for # ['bar', 'baz'] and the input is '...foo' we need not bother # rescanning until we've read three more bytes. # # Sadly, I don't know enough about this interesting topic. /grahn for index, s in self._strings: if searchwindowsize is None: # the match, if any, can only be in the fresh data, # or at the very end of the old data offset = -(freshlen+len(s)) else: # better obey searchwindowsize offset = -searchwindowsize n = buffer.find(s, offset) if n >= 0 and n < first_match: first_match = n best_index, best_match = index, s if first_match == absurd_match: return -1 self.match = best_match self.start = first_match self.end = self.start + len(self.match) return best_index
def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the search strings. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. It helps to avoid searching the same, possibly big, buffer over and over again. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, this returns -1. """ absurd_match = len(buffer) first_match = absurd_match # 'freshlen' helps a lot here. Further optimizations could # possibly include: # # using something like the Boyer-Moore Fast String Searching # Algorithm; pre-compiling the search through a list of # strings into something that can scan the input once to # search for all N strings; realize that if we search for # ['bar', 'baz'] and the input is '...foo' we need not bother # rescanning until we've read three more bytes. # # Sadly, I don't know enough about this interesting topic. /grahn for index, s in self._strings: if searchwindowsize is None: # the match, if any, can only be in the fresh data, # or at the very end of the old data offset = -(freshlen+len(s)) else: # better obey searchwindowsize offset = -searchwindowsize n = buffer.find(s, offset) if n >= 0 and n < first_match: first_match = n best_index, best_match = index, s if first_match == absurd_match: return -1 self.match = best_match self.start = first_match self.end = self.start + len(self.match) return best_index
[ "This", "searches", "buffer", "for", "the", "first", "occurence", "of", "one", "of", "the", "search", "strings", ".", "freshlen", "must", "indicate", "the", "number", "of", "bytes", "at", "the", "end", "of", "buffer", "which", "have", "not", "been", "searched", "before", ".", "It", "helps", "to", "avoid", "searching", "the", "same", "possibly", "big", "buffer", "over", "and", "over", "again", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1688-L1732
[ "def", "search", "(", "self", ",", "buffer", ",", "freshlen", ",", "searchwindowsize", "=", "None", ")", ":", "absurd_match", "=", "len", "(", "buffer", ")", "first_match", "=", "absurd_match", "# 'freshlen' helps a lot here. Further optimizations could", "# possibly include:", "#", "# using something like the Boyer-Moore Fast String Searching", "# Algorithm; pre-compiling the search through a list of", "# strings into something that can scan the input once to", "# search for all N strings; realize that if we search for", "# ['bar', 'baz'] and the input is '...foo' we need not bother", "# rescanning until we've read three more bytes.", "#", "# Sadly, I don't know enough about this interesting topic. /grahn", "for", "index", ",", "s", "in", "self", ".", "_strings", ":", "if", "searchwindowsize", "is", "None", ":", "# the match, if any, can only be in the fresh data,", "# or at the very end of the old data", "offset", "=", "-", "(", "freshlen", "+", "len", "(", "s", ")", ")", "else", ":", "# better obey searchwindowsize", "offset", "=", "-", "searchwindowsize", "n", "=", "buffer", ".", "find", "(", "s", ",", "offset", ")", "if", "n", ">=", "0", "and", "n", "<", "first_match", ":", "first_match", "=", "n", "best_index", ",", "best_match", "=", "index", ",", "s", "if", "first_match", "==", "absurd_match", ":", "return", "-", "1", "self", ".", "match", "=", "best_match", "self", ".", "start", "=", "first_match", "self", ".", "end", "=", "self", ".", "start", "+", "len", "(", "self", ".", "match", ")", "return", "best_index" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
searcher_re.search
This searches 'buffer' for the first occurence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, returns -1.
environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py
def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, returns -1.""" absurd_match = len(buffer) first_match = absurd_match # 'freshlen' doesn't help here -- we cannot predict the # length of a match, and the re module provides no help. if searchwindowsize is None: searchstart = 0 else: searchstart = max(0, len(buffer)-searchwindowsize) for index, s in self._searches: match = s.search(buffer, searchstart) if match is None: continue n = match.start() if n < first_match: first_match = n the_match = match best_index = index if first_match == absurd_match: return -1 self.start = first_match self.match = the_match self.end = self.match.end() return best_index
def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, returns -1.""" absurd_match = len(buffer) first_match = absurd_match # 'freshlen' doesn't help here -- we cannot predict the # length of a match, and the re module provides no help. if searchwindowsize is None: searchstart = 0 else: searchstart = max(0, len(buffer)-searchwindowsize) for index, s in self._searches: match = s.search(buffer, searchstart) if match is None: continue n = match.start() if n < first_match: first_match = n the_match = match best_index = index if first_match == absurd_match: return -1 self.start = first_match self.match = the_match self.end = self.match.end() return best_index
[ "This", "searches", "buffer", "for", "the", "first", "occurence", "of", "one", "of", "the", "regular", "expressions", ".", "freshlen", "must", "indicate", "the", "number", "of", "bytes", "at", "the", "end", "of", "buffer", "which", "have", "not", "been", "searched", "before", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/pexpect/_pexpect.py#L1786-L1819
[ "def", "search", "(", "self", ",", "buffer", ",", "freshlen", ",", "searchwindowsize", "=", "None", ")", ":", "absurd_match", "=", "len", "(", "buffer", ")", "first_match", "=", "absurd_match", "# 'freshlen' doesn't help here -- we cannot predict the", "# length of a match, and the re module provides no help.", "if", "searchwindowsize", "is", "None", ":", "searchstart", "=", "0", "else", ":", "searchstart", "=", "max", "(", "0", ",", "len", "(", "buffer", ")", "-", "searchwindowsize", ")", "for", "index", ",", "s", "in", "self", ".", "_searches", ":", "match", "=", "s", ".", "search", "(", "buffer", ",", "searchstart", ")", "if", "match", "is", "None", ":", "continue", "n", "=", "match", ".", "start", "(", ")", "if", "n", "<", "first_match", ":", "first_match", "=", "n", "the_match", "=", "match", "best_index", "=", "index", "if", "first_match", "==", "absurd_match", ":", "return", "-", "1", "self", ".", "start", "=", "first_match", "self", ".", "match", "=", "the_match", "self", ".", "end", "=", "self", ".", "match", ".", "end", "(", ")", "return", "best_index" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQShellDisplayHook.finish_displayhook
Finish up all displayhook activities.
environment/lib/python2.7/site-packages/IPython/zmq/displayhook.py
def finish_displayhook(self): """Finish up all displayhook activities.""" sys.stdout.flush() sys.stderr.flush() self.session.send(self.pub_socket, self.msg, ident=self.topic) self.msg = None
def finish_displayhook(self): """Finish up all displayhook activities.""" sys.stdout.flush() sys.stderr.flush() self.session.send(self.pub_socket, self.msg, ident=self.topic) self.msg = None
[ "Finish", "up", "all", "displayhook", "activities", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/displayhook.py#L57-L62
[ "def", "finish_displayhook", "(", "self", ")", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "self", ".", "session", ".", "send", "(", "self", ".", "pub_socket", ",", "self", ".", "msg", ",", "ident", "=", "self", ".", "topic", ")", "self", ".", "msg", "=", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
log_listener
Progress Monitor listener that logs all updates to the given logger
progressmonitor/listener.py
def log_listener(log:logging.Logger=None, level=logging.INFO): """Progress Monitor listener that logs all updates to the given logger""" if log is None: log = logging.getLogger("ProgressMonitor") def listen(monitor): name = "{}: ".format(monitor.name) if monitor.name is not None else "" perc = int(monitor.progress * 100) msg = "[{name}{perc:3d}%] {monitor.message}".format(**locals()) log.log(level, msg) return listen
def log_listener(log:logging.Logger=None, level=logging.INFO): """Progress Monitor listener that logs all updates to the given logger""" if log is None: log = logging.getLogger("ProgressMonitor") def listen(monitor): name = "{}: ".format(monitor.name) if monitor.name is not None else "" perc = int(monitor.progress * 100) msg = "[{name}{perc:3d}%] {monitor.message}".format(**locals()) log.log(level, msg) return listen
[ "Progress", "Monitor", "listener", "that", "logs", "all", "updates", "to", "the", "given", "logger" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/listener.py#L13-L22
[ "def", "log_listener", "(", "log", ":", "logging", ".", "Logger", "=", "None", ",", "level", "=", "logging", ".", "INFO", ")", ":", "if", "log", "is", "None", ":", "log", "=", "logging", ".", "getLogger", "(", "\"ProgressMonitor\"", ")", "def", "listen", "(", "monitor", ")", ":", "name", "=", "\"{}: \"", ".", "format", "(", "monitor", ".", "name", ")", "if", "monitor", ".", "name", "is", "not", "None", "else", "\"\"", "perc", "=", "int", "(", "monitor", ".", "progress", "*", "100", ")", "msg", "=", "\"[{name}{perc:3d}%] {monitor.message}\"", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "log", ".", "log", "(", "level", ",", "msg", ")", "return", "listen" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
unpack_directory
Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/archive_util.py
def unpack_directory(filename, extract_dir, progress_filter=default_filter): """"Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory """ if not os.path.isdir(filename): raise UnrecognizedFormat("%s is not a directory" % (filename,)) paths = {filename:('',extract_dir)} for base, dirs, files in os.walk(filename): src,dst = paths[base] for d in dirs: paths[os.path.join(base,d)] = src+d+'/', os.path.join(dst,d) for f in files: name = src+f target = os.path.join(dst,f) target = progress_filter(src+f, target) if not target: continue # skip non-files ensure_directory(target) f = os.path.join(base,f) shutil.copyfile(f, target) shutil.copystat(f, target)
def unpack_directory(filename, extract_dir, progress_filter=default_filter): """"Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory """ if not os.path.isdir(filename): raise UnrecognizedFormat("%s is not a directory" % (filename,)) paths = {filename:('',extract_dir)} for base, dirs, files in os.walk(filename): src,dst = paths[base] for d in dirs: paths[os.path.join(base,d)] = src+d+'/', os.path.join(dst,d) for f in files: name = src+f target = os.path.join(dst,f) target = progress_filter(src+f, target) if not target: continue # skip non-files ensure_directory(target) f = os.path.join(base,f) shutil.copyfile(f, target) shutil.copystat(f, target)
[ "Unpack", "a", "directory", "using", "the", "same", "interface", "as", "for", "archives" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/archive_util.py#L83-L105
[ "def", "unpack_directory", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "raise", "UnrecognizedFormat", "(", "\"%s is not a directory\"", "%", "(", "filename", ",", ")", ")", "paths", "=", "{", "filename", ":", "(", "''", ",", "extract_dir", ")", "}", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "filename", ")", ":", "src", ",", "dst", "=", "paths", "[", "base", "]", "for", "d", "in", "dirs", ":", "paths", "[", "os", ".", "path", ".", "join", "(", "base", ",", "d", ")", "]", "=", "src", "+", "d", "+", "'/'", ",", "os", ".", "path", ".", "join", "(", "dst", ",", "d", ")", "for", "f", "in", "files", ":", "name", "=", "src", "+", "f", "target", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "f", ")", "target", "=", "progress_filter", "(", "src", "+", "f", ",", "target", ")", "if", "not", "target", ":", "continue", "# skip non-files", "ensure_directory", "(", "target", ")", "f", "=", "os", ".", "path", ".", "join", "(", "base", ",", "f", ")", "shutil", ".", "copyfile", "(", "f", ",", "target", ")", "shutil", ".", "copystat", "(", "f", ",", "target", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
unpack_tarfile
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument.
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/archive_util.py
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument. """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise UnrecognizedFormat( "%s is not a compressed or uncompressed tar file" % (filename,) ) try: tarobj.chown = lambda *args: None # don't do any chowning! for member in tarobj: name = member.name # don't extract absolute paths or ones with .. in them if not name.startswith('/') and '..' not in name: prelim_dst = os.path.join(extract_dir, *name.split('/')) final_dst = progress_filter(name, prelim_dst) # If progress_filter returns None, then we do not extract # this file # TODO: Do we really need to limit to just these file types? # tarobj.extract() will handle all files on all platforms, # turning file types that aren't allowed on that platform into # regular files. if final_dst and (member.isfile() or member.isdir() or member.islnk() or member.issym()): tarobj.extract(member, extract_dir) if final_dst != prelim_dst: shutil.move(prelim_dst, final_dst) return True finally: tarobj.close()
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument. """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise UnrecognizedFormat( "%s is not a compressed or uncompressed tar file" % (filename,) ) try: tarobj.chown = lambda *args: None # don't do any chowning! for member in tarobj: name = member.name # don't extract absolute paths or ones with .. in them if not name.startswith('/') and '..' not in name: prelim_dst = os.path.join(extract_dir, *name.split('/')) final_dst = progress_filter(name, prelim_dst) # If progress_filter returns None, then we do not extract # this file # TODO: Do we really need to limit to just these file types? # tarobj.extract() will handle all files on all platforms, # turning file types that aren't allowed on that platform into # regular files. if final_dst and (member.isfile() or member.isdir() or member.islnk() or member.issym()): tarobj.extract(member, extract_dir) if final_dst != prelim_dst: shutil.move(prelim_dst, final_dst) return True finally: tarobj.close()
[ "Unpack", "tar", "/", "tar", ".", "gz", "/", "tar", ".", "bz2", "filename", "to", "extract_dir" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/archive_util.py#L168-L204
[ "def", "unpack_tarfile", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ")", ":", "try", ":", "tarobj", "=", "tarfile", ".", "open", "(", "filename", ")", "except", "tarfile", ".", "TarError", ":", "raise", "UnrecognizedFormat", "(", "\"%s is not a compressed or uncompressed tar file\"", "%", "(", "filename", ",", ")", ")", "try", ":", "tarobj", ".", "chown", "=", "lambda", "*", "args", ":", "None", "# don't do any chowning!", "for", "member", "in", "tarobj", ":", "name", "=", "member", ".", "name", "# don't extract absolute paths or ones with .. in them", "if", "not", "name", ".", "startswith", "(", "'/'", ")", "and", "'..'", "not", "in", "name", ":", "prelim_dst", "=", "os", ".", "path", ".", "join", "(", "extract_dir", ",", "*", "name", ".", "split", "(", "'/'", ")", ")", "final_dst", "=", "progress_filter", "(", "name", ",", "prelim_dst", ")", "# If progress_filter returns None, then we do not extract", "# this file", "# TODO: Do we really need to limit to just these file types?", "# tarobj.extract() will handle all files on all platforms,", "# turning file types that aren't allowed on that platform into", "# regular files.", "if", "final_dst", "and", "(", "member", ".", "isfile", "(", ")", "or", "member", ".", "isdir", "(", ")", "or", "member", ".", "islnk", "(", ")", "or", "member", ".", "issym", "(", ")", ")", ":", "tarobj", ".", "extract", "(", "member", ",", "extract_dir", ")", "if", "final_dst", "!=", "prelim_dst", ":", "shutil", ".", "move", "(", "prelim_dst", ",", "final_dst", ")", "return", "True", "finally", ":", "tarobj", ".", "close", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Context.emit
Emit a message to the user. :param msg: The message to emit. If ``debug`` is ``True``, the message will be emitted to ``stderr`` only if the ``debug`` attribute is ``True``. If ``debug`` is ``False``, the message will be emitted to ``stdout`` under the control of the ``verbose`` attribute. :param level: Ignored if ``debug`` is ``True``. The message will only be emitted if the ``verbose`` attribute is greater than or equal to the value of this parameter. Defaults to 1. :param debug: If ``True``, marks the message as a debugging message. The message will only be emitted if the ``debug`` attribute is ``True``.
timid/context.py
def emit(self, msg, level=1, debug=False): """ Emit a message to the user. :param msg: The message to emit. If ``debug`` is ``True``, the message will be emitted to ``stderr`` only if the ``debug`` attribute is ``True``. If ``debug`` is ``False``, the message will be emitted to ``stdout`` under the control of the ``verbose`` attribute. :param level: Ignored if ``debug`` is ``True``. The message will only be emitted if the ``verbose`` attribute is greater than or equal to the value of this parameter. Defaults to 1. :param debug: If ``True``, marks the message as a debugging message. The message will only be emitted if the ``debug`` attribute is ``True``. """ # Is it a debug message? if debug: if not self.debug: # Debugging not enabled, don't emit the message return stream = sys.stderr else: # Not a debugging message; is verbose high enough? if self.verbose < level: return stream = sys.stdout # Emit the message print(msg, file=stream) stream.flush()
def emit(self, msg, level=1, debug=False): """ Emit a message to the user. :param msg: The message to emit. If ``debug`` is ``True``, the message will be emitted to ``stderr`` only if the ``debug`` attribute is ``True``. If ``debug`` is ``False``, the message will be emitted to ``stdout`` under the control of the ``verbose`` attribute. :param level: Ignored if ``debug`` is ``True``. The message will only be emitted if the ``verbose`` attribute is greater than or equal to the value of this parameter. Defaults to 1. :param debug: If ``True``, marks the message as a debugging message. The message will only be emitted if the ``debug`` attribute is ``True``. """ # Is it a debug message? if debug: if not self.debug: # Debugging not enabled, don't emit the message return stream = sys.stderr else: # Not a debugging message; is verbose high enough? if self.verbose < level: return stream = sys.stdout # Emit the message print(msg, file=stream) stream.flush()
[ "Emit", "a", "message", "to", "the", "user", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/context.py#L55-L88
[ "def", "emit", "(", "self", ",", "msg", ",", "level", "=", "1", ",", "debug", "=", "False", ")", ":", "# Is it a debug message?", "if", "debug", ":", "if", "not", "self", ".", "debug", ":", "# Debugging not enabled, don't emit the message", "return", "stream", "=", "sys", ".", "stderr", "else", ":", "# Not a debugging message; is verbose high enough?", "if", "self", ".", "verbose", "<", "level", ":", "return", "stream", "=", "sys", ".", "stdout", "# Emit the message", "print", "(", "msg", ",", "file", "=", "stream", ")", "stream", ".", "flush", "(", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6