##// 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 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
26 import inspect
27 import os
25 import os
28 import re
26 import re
29 import runpy
27 import runpy
30 import sys
28 import sys
31 import tempfile
29 import tempfile
32 import types
30 import types
33
31 import urllib
34 try:
32 from io import open as io_open
35 from contextlib import nested
36 except:
37 from IPython.utils.nested_context import nested
38
33
39 from IPython.config.configurable import SingletonConfigurable
34 from IPython.config.configurable import SingletonConfigurable
40 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
41 from IPython.core import history as ipcorehist
42 from IPython.core import page
36 from IPython.core import page
43 from IPython.core import prefilter
37 from IPython.core import prefilter
44 from IPython.core import shadowns
38 from IPython.core import shadowns
@@ -50,7 +44,7 b' from IPython.core.compilerop import CachingCompiler'
50 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.display_trap import DisplayTrap
51 from IPython.core.displayhook import DisplayHook
45 from IPython.core.displayhook import DisplayHook
52 from IPython.core.displaypub import DisplayPublisher
46 from IPython.core.displaypub import DisplayPublisher
53 from IPython.core.error import TryNext, UsageError
47 from IPython.core.error import UsageError
54 from IPython.core.extensions import ExtensionManager
48 from IPython.core.extensions import ExtensionManager
55 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
49 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
56 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.formatters import DisplayFormatter
@@ -68,19 +62,20 b' from IPython.core.prompts import PromptManager'
68 from IPython.utils import PyColorize
62 from IPython.utils import PyColorize
69 from IPython.utils import io
63 from IPython.utils import io
70 from IPython.utils import py3compat
64 from IPython.utils import py3compat
65 from IPython.utils import openpy
71 from IPython.utils.doctestreload import doctest_reload
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 from IPython.utils.ipstruct import Struct
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 from IPython.utils.pickleshare import PickleShareDB
70 from IPython.utils.pickleshare import PickleShareDB
76 from IPython.utils.process import system, getoutput
71 from IPython.utils.process import system, getoutput
77 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.strdispatch import StrDispatch
78 from IPython.utils.syspathcontext import prepended_to_syspath
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 DollarFormatter)
75 DollarFormatter)
81 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
76 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
82 List, Unicode, Instance, Type)
77 List, Unicode, Instance, Type)
83 from IPython.utils.warn import warn, error, fatal
78 from IPython.utils.warn import warn, error
84 import IPython.core.hooks
79 import IPython.core.hooks
85
80
86 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
@@ -2742,21 +2737,29 b' class InteractiveShell(SingletonConfigurable, Magic):'
2742 """Show a usage message"""
2737 """Show a usage message"""
2743 page.page(IPython.core.usage.interactive_usage)
2738 page.page(IPython.core.usage.interactive_usage)
2744
2739
2745 def find_user_code(self, target, raw=True):
2740 def find_user_code(self, target, raw=True, py_only=False):
2746 """Get a code string from history, file, or a string or macro.
2741 """Get a code string from history, file, url, or a string or macro.
2747
2742
2748 This is mainly used by magic functions.
2743 This is mainly used by magic functions.
2749
2744
2750 Parameters
2745 Parameters
2751 ----------
2746 ----------
2747
2752 target : str
2748 target : str
2749
2753 A string specifying code to retrieve. This will be tried respectively
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
2751 as: ranges of input history (see %history for syntax), url,
2755 an expression evaluating to a string or Macro in the user namespace.
2752 correspnding .py file, filename, or an expression evaluating to a
2753 string or Macro in the user namespace.
2754
2756 raw : bool
2755 raw : bool
2757 If true (default), retrieve raw history. Has no effect on the other
2756 If true (default), retrieve raw history. Has no effect on the other
2758 retrieval mechanisms.
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 Returns
2763 Returns
2761 -------
2764 -------
2762 A string of code.
2765 A string of code.
@@ -2768,14 +2771,37 b' class InteractiveShell(SingletonConfigurable, Magic):'
2768 code = self.extract_input_lines(target, raw=raw) # Grab history
2771 code = self.extract_input_lines(target, raw=raw) # Grab history
2769 if code:
2772 if code:
2770 return code
2773 return code
2771 if os.path.isfile(target): # Read file
2774 utarget = unquote_filename(target)
2772 return open(target, "r").read()
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 try: # User namespace
2800 try: # User namespace
2775 codeobj = eval(target, self.user_ns)
2801 codeobj = eval(target, self.user_ns)
2776 except Exception:
2802 except Exception:
2777 raise ValueError(("'%s' was not found in history, as a file, nor in"
2803 raise ValueError(("'%s' was not found in history, as a file, url, "
2778 " the user namespace.") % target)
2804 "nor in the user namespace.") % target)
2779 if isinstance(codeobj, basestring):
2805 if isinstance(codeobj, basestring):
2780 return codeobj
2806 return codeobj
2781 elif isinstance(codeobj, Macro):
2807 elif isinstance(codeobj, Macro):
@@ -19,12 +19,10 b' import __builtin__ as builtin_mod'
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import imp
23 import io
22 import io
24 import json
23 import json
25 import os
24 import os
26 import sys
25 import sys
27 import shutil
28 import re
26 import re
29 import time
27 import time
30 import gc
28 import gc
@@ -44,27 +42,23 b' except ImportError:'
44 except ImportError:
42 except ImportError:
45 profile = pstats = None
43 profile = pstats = None
46
44
47 import IPython
48 from IPython.core import debugger, oinspect
45 from IPython.core import debugger, oinspect
49 from IPython.core.error import TryNext
46 from IPython.core.error import TryNext
50 from IPython.core.error import UsageError
47 from IPython.core.error import UsageError
51 from IPython.core.error import StdinNotImplementedError
48 from IPython.core.error import StdinNotImplementedError
52 from IPython.core.fakemodule import FakeModule
53 from IPython.core.profiledir import ProfileDir
54 from IPython.core.macro import Macro
49 from IPython.core.macro import Macro
55 from IPython.core import magic_arguments, page
50 from IPython.core import magic_arguments, page
56 from IPython.core.prefilter import ESC_MAGIC
51 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.core.pylabtools import mpl_runner
52 from IPython.core.pylabtools import mpl_runner
58 from IPython.testing.skipdoctest import skip_doctest
53 from IPython.testing.skipdoctest import skip_doctest
59 from IPython.utils import py3compat
54 from IPython.utils import py3compat
60 from IPython.utils import openpy
61 from IPython.utils.encoding import DEFAULT_ENCODING
55 from IPython.utils.encoding import DEFAULT_ENCODING
62 from IPython.utils.io import file_read, nlprint
56 from IPython.utils.io import file_read, nlprint
63 from IPython.utils.module_paths import find_mod
57 from IPython.utils.module_paths import find_mod
64 from IPython.utils.path import get_py_filename, unquote_filename
58 from IPython.utils.path import get_py_filename, unquote_filename
65 from IPython.utils.process import arg_split, abbrev_cwd
59 from IPython.utils.process import arg_split, abbrev_cwd
66 from IPython.utils.terminal import set_term_title
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 from IPython.utils.timing import clock, clock2
62 from IPython.utils.timing import clock, clock2
69 from IPython.utils.warn import warn, error
63 from IPython.utils.warn import warn, error
70 from IPython.utils.ipstruct import Struct
64 from IPython.utils.ipstruct import Struct
@@ -2219,8 +2213,8 b' Currently the magic system has the following functions:\\n"""'
2219 if not fname.endswith('.py'):
2213 if not fname.endswith('.py'):
2220 fname += '.py'
2214 fname += '.py'
2221 if os.path.isfile(fname):
2215 if os.path.isfile(fname):
2222 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2216 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
2223 if ans.lower() not in ['y','yes']:
2217 if not overwrite :
2224 print 'Operation cancelled.'
2218 print 'Operation cancelled.'
2225 return
2219 return
2226 try:
2220 try:
@@ -2271,27 +2265,54 b' Currently the magic system has the following functions:\\n"""'
2271 return response_data['html_url']
2265 return response_data['html_url']
2272
2266
2273 def magic_loadpy(self, arg_s):
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
2293 %load myscript.py
2279 %loadpy http://www.example.com/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)
2298 opts,args = self.parse_options(arg_s,'y')
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)
2289
2299
2290 # openpy takes care of finding the source encoding (per PEP 263)
2300 contents = self.shell.find_user_code(args)
2291 if remote_url:
2301 l = len(contents)
2292 contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True)
2302
2293 else:
2303 # 200 000 is ~ 2500 full 80 caracter lines
2294 contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True)
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 self.set_next_input(contents)
2317 self.set_next_input(contents)
2297
2318
@@ -3323,22 +3344,26 b' Defaulting color scheme to \'NoColor\'"""'
3323 bkms[args[0]] = args[1]
3344 bkms[args[0]] = args[1]
3324 self.db['bookmarks'] = bkms
3345 self.db['bookmarks'] = bkms
3325
3346
3347
3326 def magic_pycat(self, parameter_s=''):
3348 def magic_pycat(self, parameter_s=''):
3327 """Show a syntax-highlighted file through a pager.
3349 """Show a syntax-highlighted file through a pager.
3328
3350
3329 This magic is similar to the cat utility, but it will assume the file
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 try:
3363 try :
3333 filename = get_py_filename(parameter_s)
3364 cont = self.shell.find_user_code(parameter_s)
3334 cont = file_read(filename)
3365 except ValueError, IOError:
3335 except IOError:
3366 print "Error: no such file, variable, URL, history range or macro"
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"
3342 return
3367 return
3343
3368
3344 page.page(self.shell.pycolorize(cont))
3369 page.page(self.shell.pycolorize(cont))
@@ -41,7 +41,7 b' class NotebookManager(LoggingConfigurable):'
41 save_script = Bool(False, config=True,
41 save_script = Bool(False, config=True,
42 help="""Automatically create a Python script when saving the notebook.
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 <notebook-name>.py script will be created next to any
45 <notebook-name>.py script will be created next to any
46 <notebook-name>.ipynb on each save. This can also be set with the
46 <notebook-name>.ipynb on each save. This can also be set with the
47 short `--script` flag.
47 short `--script` flag.
@@ -597,7 +597,7 b' class MainWindow(QtGui.QMainWindow):'
597
597
598 # list of protected magic that don't like to be called without argument
598 # list of protected magic that don't like to be called without argument
599 # append '?' to the end to print the docstring when called from the menu
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 magics=re.findall('\w+', listofmagic)
601 magics=re.findall('\w+', listofmagic)
602 for magic in magics:
602 for magic in magics:
603 if magic in protected_magic:
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 from __future__ import absolute_import
7 from __future__ import absolute_import
8
8
9 import __builtin__
10 import io
9 import io
11 from io import TextIOWrapper
10 from io import TextIOWrapper
12 import re
11 import re
@@ -190,3 +189,4 b" def read_py_url(url, errors='replace', skip_encoding_cookie=True):"
190 return "".join(strip_encoding_cookie(text))
189 return "".join(strip_encoding_cookie(text))
191 else:
190 else:
192 return text.read()
191 return text.read()
192
@@ -1014,7 +1014,7 b''
1014 "source": [
1014 "source": [
1015 "# Loading external codes",
1015 "# Loading external codes",
1016 "* Drag and drop a ``.py`` in the dashboard",
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 "In this notebook we've kept the output saved so you can see the result, but you should run the next",
1019 "In this notebook we've kept the output saved so you can see the result, but you should run the next",
1020 "cell yourself (with an active internet connection)."
1020 "cell yourself (with an active internet connection)."
@@ -1024,7 +1024,7 b''
1024 "cell_type": "code",
1024 "cell_type": "code",
1025 "collapsed": true,
1025 "collapsed": true,
1026 "input": [
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 "language": "python",
1029 "language": "python",
1030 "outputs": [],
1030 "outputs": [],
@@ -1,7 +1,7 b''
1 """
1 """
2 Run this script in the qtconsole with one of:
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 or
6 or
7 %run hb_gil.py
7 %run hb_gil.py
@@ -33,18 +33,18 b' is not yet configurable.'
33 point in a multiline block, you can force its execution (without having to
33 point in a multiline block, you can force its execution (without having to
34 go to the bottom) with :kbd:`Shift-Enter`.
34 go to the bottom) with :kbd:`Shift-Enter`.
35
35
36 ``%loadpy``
36 ``%load``
37 ===========
37 =========
38
38
39 The new ``%loadpy`` magic takes any python script (must end in '.py'), and
39 The new ``%load`` magic (previously ``%loadpy``) takes any script, and pastes
40 pastes its contents as your next input, so you can edit it before
40 its contents as your next input, so you can edit it before executing. The
41 executing. The script may be on your machine, but you can also specify a url,
41 script may be on your machine, but you can also specify an history range, or a
42 and it will download the script from the web. This is particularly useful for
42 url, and it will download the script from the web. This is particularly useful
43 playing with examples from documentation, such as matplotlib.
43 for playing with examples from documentation, such as matplotlib.
44
44
45 .. sourcecode:: ipython
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 In [7]: from mpl_toolkits.mplot3d import axes3d
49 In [7]: from mpl_toolkits.mplot3d import axes3d
50 ...: import matplotlib.pyplot as plt
50 ...: import matplotlib.pyplot as plt
General Comments 0
You need to be logged in to leave comments. Login now