##// END OF EJS Templates
Merge pull request #1606 from Carreau/loadpycat...
Thomas Kluyver -
r6899:24a3c008 merge
parent child Browse files
Show More
@@ -22,23 +22,17 b' import __future__'
22 22 import abc
23 23 import ast
24 24 import atexit
25 import codeop
26 import inspect
27 25 import os
28 26 import re
29 27 import runpy
30 28 import sys
31 29 import tempfile
32 30 import types
33
34 try:
35 from contextlib import nested
36 except:
37 from IPython.utils.nested_context import nested
31 import urllib
32 from io import open as io_open
38 33
39 34 from IPython.config.configurable import SingletonConfigurable
40 35 from IPython.core import debugger, oinspect
41 from IPython.core import history as ipcorehist
42 36 from IPython.core import page
43 37 from IPython.core import prefilter
44 38 from IPython.core import shadowns
@@ -50,7 +44,7 b' from IPython.core.compilerop import CachingCompiler'
50 44 from IPython.core.display_trap import DisplayTrap
51 45 from IPython.core.displayhook import DisplayHook
52 46 from IPython.core.displaypub import DisplayPublisher
53 from IPython.core.error import TryNext, UsageError
47 from IPython.core.error import UsageError
54 48 from IPython.core.extensions import ExtensionManager
55 49 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
56 50 from IPython.core.formatters import DisplayFormatter
@@ -68,19 +62,20 b' from IPython.core.prompts import PromptManager'
68 62 from IPython.utils import PyColorize
69 63 from IPython.utils import io
70 64 from IPython.utils import py3compat
65 from IPython.utils import openpy
71 66 from IPython.utils.doctestreload import doctest_reload
72 from IPython.utils.io import ask_yes_no, rprint
67 from IPython.utils.io import ask_yes_no
73 68 from IPython.utils.ipstruct import Struct
74 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
69 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
75 70 from IPython.utils.pickleshare import PickleShareDB
76 71 from IPython.utils.process import system, getoutput
77 72 from IPython.utils.strdispatch import StrDispatch
78 73 from IPython.utils.syspathcontext import prepended_to_syspath
79 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
74 from IPython.utils.text import (format_screen, LSString, SList,
80 75 DollarFormatter)
81 76 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
82 77 List, Unicode, Instance, Type)
83 from IPython.utils.warn import warn, error, fatal
78 from IPython.utils.warn import warn, error
84 79 import IPython.core.hooks
85 80
86 81 #-----------------------------------------------------------------------------
@@ -2742,21 +2737,29 b' class InteractiveShell(SingletonConfigurable, Magic):'
2742 2737 """Show a usage message"""
2743 2738 page.page(IPython.core.usage.interactive_usage)
2744 2739
2745 def find_user_code(self, target, raw=True):
2746 """Get a code string from history, file, or a string or macro.
2740 def find_user_code(self, target, raw=True, py_only=False):
2741 """Get a code string from history, file, url, or a string or macro.
2747 2742
2748 2743 This is mainly used by magic functions.
2749 2744
2750 2745 Parameters
2751 2746 ----------
2747
2752 2748 target : str
2749
2753 2750 A string specifying code to retrieve. This will be tried respectively
2754 as: ranges of input history (see %history for syntax), a filename, or
2755 an expression evaluating to a string or Macro in the user namespace.
2751 as: ranges of input history (see %history for syntax), url,
2752 correspnding .py file, filename, or an expression evaluating to a
2753 string or Macro in the user namespace.
2754
2756 2755 raw : bool
2757 2756 If true (default), retrieve raw history. Has no effect on the other
2758 2757 retrieval mechanisms.
2759 2758
2759 py_only : bool (default False)
2760 Only try to fetch python code, do not try alternative methods to decode file
2761 if unicode fails.
2762
2760 2763 Returns
2761 2764 -------
2762 2765 A string of code.
@@ -2768,14 +2771,37 b' class InteractiveShell(SingletonConfigurable, Magic):'
2768 2771 code = self.extract_input_lines(target, raw=raw) # Grab history
2769 2772 if code:
2770 2773 return code
2771 if os.path.isfile(target): # Read file
2772 return open(target, "r").read()
2774 utarget = unquote_filename(target)
2775 try:
2776 if utarget.startswith(('http://', 'https://')):
2777 return openpy.read_py_url(utarget, skip_encoding_cookie=True)
2778 except UnicodeDecodeError:
2779 if not py_only :
2780 response = urllib.urlopen(target)
2781 return response.read().decode('latin1')
2782 raise ValueError(("'%s' seem to be unreadable.") % utarget)
2783
2784 potential_target = [target]
2785 try :
2786 potential_target.insert(0,get_py_filename(target))
2787 except IOError:
2788 pass
2789
2790 for tgt in potential_target :
2791 if os.path.isfile(tgt): # Read file
2792 try :
2793 return openpy.read_py_file(tgt, skip_encoding_cookie=True)
2794 except UnicodeDecodeError :
2795 if not py_only :
2796 with io_open(tgt,'r', encoding='latin1') as f :
2797 return f.read()
2798 raise ValueError(("'%s' seem to be unreadable.") % target)
2773 2799
2774 2800 try: # User namespace
2775 2801 codeobj = eval(target, self.user_ns)
2776 2802 except Exception:
2777 raise ValueError(("'%s' was not found in history, as a file, nor in"
2778 " the user namespace.") % target)
2803 raise ValueError(("'%s' was not found in history, as a file, url, "
2804 "nor in the user namespace.") % target)
2779 2805 if isinstance(codeobj, basestring):
2780 2806 return codeobj
2781 2807 elif isinstance(codeobj, Macro):
@@ -19,12 +19,10 b' import __builtin__ as builtin_mod'
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 import imp
23 22 import io
24 23 import json
25 24 import os
26 25 import sys
27 import shutil
28 26 import re
29 27 import time
30 28 import gc
@@ -44,27 +42,23 b' except ImportError:'
44 42 except ImportError:
45 43 profile = pstats = None
46 44
47 import IPython
48 45 from IPython.core import debugger, oinspect
49 46 from IPython.core.error import TryNext
50 47 from IPython.core.error import UsageError
51 48 from IPython.core.error import StdinNotImplementedError
52 from IPython.core.fakemodule import FakeModule
53 from IPython.core.profiledir import ProfileDir
54 49 from IPython.core.macro import Macro
55 50 from IPython.core import magic_arguments, page
56 51 from IPython.core.prefilter import ESC_MAGIC
57 52 from IPython.core.pylabtools import mpl_runner
58 53 from IPython.testing.skipdoctest import skip_doctest
59 54 from IPython.utils import py3compat
60 from IPython.utils import openpy
61 55 from IPython.utils.encoding import DEFAULT_ENCODING
62 56 from IPython.utils.io import file_read, nlprint
63 57 from IPython.utils.module_paths import find_mod
64 58 from IPython.utils.path import get_py_filename, unquote_filename
65 59 from IPython.utils.process import arg_split, abbrev_cwd
66 60 from IPython.utils.terminal import set_term_title
67 from IPython.utils.text import LSString, SList, format_screen
61 from IPython.utils.text import format_screen
68 62 from IPython.utils.timing import clock, clock2
69 63 from IPython.utils.warn import warn, error
70 64 from IPython.utils.ipstruct import Struct
@@ -2219,8 +2213,8 b' Currently the magic system has the following functions:\\n"""'
2219 2213 if not fname.endswith('.py'):
2220 2214 fname += '.py'
2221 2215 if os.path.isfile(fname):
2222 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2223 if ans.lower() not in ['y','yes']:
2216 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
2217 if not overwrite :
2224 2218 print 'Operation cancelled.'
2225 2219 return
2226 2220 try:
@@ -2271,27 +2265,54 b' Currently the magic system has the following functions:\\n"""'
2271 2265 return response_data['html_url']
2272 2266
2273 2267 def magic_loadpy(self, arg_s):
2274 """Load a .py python script into the GUI console.
2268 """Alias of `%load`
2275 2269
2276 This magic command can either take a local filename or a url::
2270 `%loadpy` has gained some flexibility and droped the requirement of a `.py`
2271 extension. So it has been renamed simply into %load. You can look at
2272 `%load`'s docstring for more info.
2273 """
2274 self.magic_load(arg_s)
2275
2276 def magic_load(self, arg_s):
2277 """Load code into the current frontend.
2278
2279 Usage:\\
2280 %load [options] source
2281
2282 where source can be a filename, URL, input history range or macro
2283
2284 Options:
2285 --------
2286 -y : Don't ask confirmation for loading source above 200 000 characters.
2287
2288 This magic command can either take a local filename, a URL, an history
2289 range (see %history) or a macro as argument, it will prompt for
2290 confirmation before loading source with more than 200 000 characters, unless
2291 -y flag is passed or if the frontend does not support raw_input::
2277 2292
2278 %loadpy myscript.py
2279 %loadpy http://www.example.com/myscript.py
2293 %load myscript.py
2294 %load 7-27
2295 %load myMacro
2296 %load http://www.example.com/myscript.py
2280 2297 """
2281 arg_s = unquote_filename(arg_s)
2282 remote_url = arg_s.startswith(('http://', 'https://'))
2283 local_url = not remote_url
2284 if local_url and not arg_s.endswith('.py'):
2285 # Local files must be .py; for remote URLs it's possible that the
2286 # fetch URL doesn't have a .py in it (many servers have an opaque
2287 # URL, such as scipy-central.org).
2288 raise ValueError('%%loadpy only works with .py files: %s' % arg_s)
2298 opts,args = self.parse_options(arg_s,'y')
2289 2299
2290 # openpy takes care of finding the source encoding (per PEP 263)
2291 if remote_url:
2292 contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True)
2293 else:
2294 contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True)
2300 contents = self.shell.find_user_code(args)
2301 l = len(contents)
2302
2303 # 200 000 is ~ 2500 full 80 caracter lines
2304 # so in average, more than 5000 lines
2305 if l > 200000 and 'y' not in opts:
2306 try:
2307 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
2308 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
2309 except StdinNotImplementedError:
2310 #asume yes if raw input not implemented
2311 ans = True
2312
2313 if ans is False :
2314 print 'Operation cancelled.'
2315 return
2295 2316
2296 2317 self.set_next_input(contents)
2297 2318
@@ -3323,22 +3344,26 b' Defaulting color scheme to \'NoColor\'"""'
3323 3344 bkms[args[0]] = args[1]
3324 3345 self.db['bookmarks'] = bkms
3325 3346
3347
3326 3348 def magic_pycat(self, parameter_s=''):
3327 3349 """Show a syntax-highlighted file through a pager.
3328 3350
3329 3351 This magic is similar to the cat utility, but it will assume the file
3330 to be Python source and will show it with syntax highlighting. """
3352 to be Python source and will show it with syntax highlighting.
3353
3354 This magic command can either take a local filename, an url,
3355 an history range (see %history) or a macro as argument ::
3356
3357 %pycat myscript.py
3358 %pycat 7-27
3359 %pycat myMacro
3360 %pycat http://www.example.com/myscript.py
3361 """
3331 3362
3332 3363 try:
3333 filename = get_py_filename(parameter_s)
3334 cont = file_read(filename)
3335 except IOError:
3336 try:
3337 cont = eval(parameter_s,self.user_ns)
3338 except NameError:
3339 cont = None
3340 if cont is None:
3341 print "Error: no such file or variable"
3364 cont = self.shell.find_user_code(parameter_s)
3365 except ValueError, IOError:
3366 print "Error: no such file, variable, URL, history range or macro"
3342 3367 return
3343 3368
3344 3369 page.page(self.shell.pycolorize(cont))
@@ -41,7 +41,7 b' class NotebookManager(LoggingConfigurable):'
41 41 save_script = Bool(False, config=True,
42 42 help="""Automatically create a Python script when saving the notebook.
43 43
44 For easier use of import, %run and %loadpy across notebooks, a
44 For easier use of import, %run and %load across notebooks, a
45 45 <notebook-name>.py script will be created next to any
46 46 <notebook-name>.ipynb on each save. This can also be set with the
47 47 short `--script` flag.
@@ -597,7 +597,7 b' class MainWindow(QtGui.QMainWindow):'
597 597
598 598 # list of protected magic that don't like to be called without argument
599 599 # append '?' to the end to print the docstring when called from the menu
600 protected_magic = set(["more","less","load_ext","pycat","loadpy","save"])
600 protected_magic = set(["more","less","load_ext","pycat","loadpy","load","save"])
601 601 magics=re.findall('\w+', listofmagic)
602 602 for magic in magics:
603 603 if magic in protected_magic:
@@ -6,7 +6,6 b' Much of the code is taken from the tokenize module in Python 3.2.'
6 6 """
7 7 from __future__ import absolute_import
8 8
9 import __builtin__
10 9 import io
11 10 from io import TextIOWrapper
12 11 import re
@@ -190,3 +189,4 b" def read_py_url(url, errors='replace', skip_encoding_cookie=True):"
190 189 return "".join(strip_encoding_cookie(text))
191 190 else:
192 191 return text.read()
192
@@ -1014,7 +1014,7 b''
1014 1014 "source": [
1015 1015 "# Loading external codes",
1016 1016 "* Drag and drop a ``.py`` in the dashboard",
1017 "* Use ``%loadpy`` with any local or remote url: [the Matplotlib Gallery!](http://matplotlib.sourceforge.net/gallery.html)",
1017 "* Use ``%load`` with any local or remote url: [the Matplotlib Gallery!](http://matplotlib.sourceforge.net/gallery.html)",
1018 1018 "",
1019 1019 "In this notebook we've kept the output saved so you can see the result, but you should run the next",
1020 1020 "cell yourself (with an active internet connection)."
@@ -1024,7 +1024,7 b''
1024 1024 "cell_type": "code",
1025 1025 "collapsed": true,
1026 1026 "input": [
1027 "%loadpy http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py"
1027 "%load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py"
1028 1028 ],
1029 1029 "language": "python",
1030 1030 "outputs": [],
@@ -1,7 +1,7 b''
1 1 """
2 2 Run this script in the qtconsole with one of:
3 3
4 %loadpy hb_gil.py
4 %load hb_gil.py
5 5
6 6 or
7 7 %run hb_gil.py
@@ -33,18 +33,18 b' is not yet configurable.'
33 33 point in a multiline block, you can force its execution (without having to
34 34 go to the bottom) with :kbd:`Shift-Enter`.
35 35
36 ``%loadpy``
37 ===========
36 ``%load``
37 =========
38 38
39 The new ``%loadpy`` magic takes any python script (must end in '.py'), and
40 pastes its contents as your next input, so you can edit it before
41 executing. The script may be on your machine, but you can also specify a url,
42 and it will download the script from the web. This is particularly useful for
43 playing with examples from documentation, such as matplotlib.
39 The new ``%load`` magic (previously ``%loadpy``) takes any script, and pastes
40 its contents as your next input, so you can edit it before executing. The
41 script may be on your machine, but you can also specify an history range, or a
42 url, and it will download the script from the web. This is particularly useful
43 for playing with examples from documentation, such as matplotlib.
44 44
45 45 .. sourcecode:: ipython
46 46
47 In [6]: %loadpy http://matplotlib.sourceforge.net/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
47 In [6]: %load http://matplotlib.sourceforge.net/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
48 48
49 49 In [7]: from mpl_toolkits.mplot3d import axes3d
50 50 ...: import matplotlib.pyplot as plt
General Comments 0
You need to be logged in to leave comments. Login now