Skip to content

Commit

Permalink
Move _get_some_code method to InteractiveShell object; improve docstr…
Browse files Browse the repository at this point in the history
…ing.
  • Loading branch information
takluyver committed Apr 3, 2011
1 parent ed8085a commit 77c9fea
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 30 deletions.
43 changes: 43 additions & 0 deletions IPython/core/interactiveshell.py
Expand Up @@ -50,6 +50,7 @@
from IPython.core.history import HistoryManager
from IPython.core.inputsplitter import IPythonInputSplitter
from IPython.core.logger import Logger
from IPython.core.macro import Macro
from IPython.core.magic import Magic
from IPython.core.payload import PayloadManager
from IPython.core.plugin import PluginManager
Expand Down Expand Up @@ -2503,6 +2504,48 @@ def ask_yes_no(self,prompt,default=True):
def show_usage(self):
"""Show a usage message"""
page.page(IPython.core.usage.interactive_usage)

def _get_some_code(self, target, raw=True):
"""Get a code string from history, file, 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, a filename, and 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.
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
if os.path.isfile(target): # Read file
return open(target, "r").read()

try: # User namespace
codeobj = eval(target, self.user_ns)
except Exception:
raise ValueError(("'%s' was not found in history, as a file, 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)

#-------------------------------------------------------------------------
# Things related to IPython exiting
Expand Down
33 changes: 3 additions & 30 deletions IPython/core/magic.py
Expand Up @@ -2030,7 +2030,7 @@ def magic_macro(self,parameter_s = ''):

#print 'rng',ranges # dbg
try:
lines = self._get_some_code(codefrom, 'r' in opts)
lines = self.shell._get_some_code(codefrom, 'r' in opts)
except (ValueError, TypeError) as e:
print e.args[0]
return
Expand Down Expand Up @@ -2069,7 +2069,7 @@ def magic_save(self,parameter_s = ''):
print 'Operation cancelled.'
return
try:
cmds = self._get_some_code(codefrom, 'r' in opts)
cmds = self.shell._get_some_code(codefrom, 'r' in opts)
except (TypeError, ValueError) as e:
print e.args[0]
return
Expand All @@ -2080,38 +2080,11 @@ def magic_save(self,parameter_s = ''):
f.write(cmds)
print 'The following commands were written to file `%s`:' % fname
print cmds

def _get_some_code(self, target, raw=True):
"""Utility function to get a code string, either from a range of
history lines, a filename, or an expression evaluating to a string or a
Macro in the user namespace.
ValueError is raised if none are 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
if os.path.isfile(target): # Read file
return open(target, "r").read()

try: # User namespace
codeobj = eval(target, self.shell.user_ns)
except Exception:
raise ValueError(("'%s' was not found in history, as a file, 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 magic_pastebin(self, parameter_s = ''):
"""Upload code to the 'Lodge it' paste bin, returning the URL."""
try:
code = self._get_some_code(parameter_s)
code = self.shell._get_some_code(parameter_s)
except (ValueError, TypeError) as e:
print e.args[0]
return
Expand Down

0 comments on commit 77c9fea

Please sign in to comment.