##// END OF EJS Templates
Merge pull request #4438 from takluyver/1codebase...
Paul Ivanov -
r13404:dd39c908 merge
parent child Browse files
Show More
@@ -0,0 +1,122 b''
1 Writing code for Python 2 and 3
2 ===============================
3
4 Iterators
5 ---------
6
7 Many built in functions and methods in Python 2 come in pairs, one
8 returning a list, and one returning an iterator (e.g. :func:`range` and
9 :func:`xrange`). In Python 3, there is usually only the iterator form,
10 but it has the name which gives a list in Python 2 (e.g. :func:`range`).
11
12 The way to write compatible code depends on what you need:
13
14 * A list, e.g. for serialisation, or to test if something is in it.
15 * Iteration, but it will never be used for very many items, so efficiency
16 isn't especially important.
17 * Iteration over many items, where efficiency is important.
18
19 ================ ================= =======================
20 list iteration (small) iteration(large)
21 ================ ================= =======================
22 list(range(n)) range(n) py3compat.xrange(n)
23 list(map(f, it)) map(f, it) --
24 list(zip(a, b)) zip(a, b) --
25 list(d.items()) d.items() py3compat.iteritems(d)
26 list(d.values()) d.values() py3compat.itervalues(d)
27 ================ ================= =======================
28
29 Iterating over a dictionary yields its keys, so there is rarely a need
30 to use :meth:`dict.keys` or :meth:`dict.iterkeys`.
31
32 Avoid using :func:`map` to cause function side effects. This is more
33 clearly written with a simple for loop.
34
35 Changed standard library locations
36 ----------------------------------
37
38 Several parts of the standard library have been renamed and moved. This
39 is a short list of things that we're using. A couple of them have names
40 in :mod:`IPython.utils.py3compat`, so you don't need both
41 imports in each module that uses them.
42
43 ================== ============ ===========
44 Python 2 Python 3 py3compat
45 ================== ============ ===========
46 :func:`raw_input` input input
47 :mod:`__builtin__` builtins builtin_mod
48 :mod:`StringIO` io
49 :mod:`Queue` queue
50 :mod:`cPickle` pickle
51 :mod:`thread` _thread
52 :mod:`copy_reg` copyreg
53 :mod:`urlparse` urllib.parse
54 :mod:`repr` reprlib
55 :mod:`Tkinter` tkinter
56 :mod:`Cookie` http.cookie
57 :mod:`_winreg` winreg
58 ================== ============ ===========
59
60 Be careful with StringIO: :class:`io.StringIO` is available in Python 2.7,
61 but it behaves differently from :class:`StringIO.StringIO`, and much of
62 our code assumes the use of the latter on Python 2. So a try/except on
63 the import may cause problems.
64
65 Unicode
66 -------
67
68 Always be explicit about what is text (unicode) and what is bytes.
69 *Encoding* goes from unicode to bytes, and *decoding* goes from bytes
70 to unicode.
71
72 To open files for reading or writing text, use :func:`io.open`, which is
73 the Python 3 builtin ``open`` function, available on Python 2 as well.
74 We almost always need to specify the encoding parameter, because the
75 default is platform dependent.
76
77 Relative imports
78 ----------------
79
80 ::
81
82 # This makes Python 2 behave like Python 3:
83 from __future__ import absolute_import
84
85 import io # Imports the standard library io module
86 from . import io # Import the io module from the package
87 # containing the current module
88 from .io import foo # foo from the io module next to this module
89 from IPython.utils import io # This still works
90
91 Print function
92 --------------
93
94 ::
95
96 # Support the print function on Python 2:
97 from __future__ import print_function
98
99 print(a, b)
100 print(foo, file=sys.stderr)
101 print(bar, baz, sep='\t', end='')
102
103 Metaclasses
104 -----------
105
106 The syntax for declaring a class with a metaclass is different in
107 Python 2 and 3. In most cases, the helper function
108 :func:`~IPython.utils.py3compat.with_metaclass` (copied from the six
109 library) can be used like this::
110
111 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
112 ...
113
114 Combining inheritance between Qt and the traitlets system, however, does
115 not work with this. Instead, we do this::
116
117 class QtKernelClientMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
118 ...
119
120 This gives the new class a metaclass of :class:`~IPython.qt.util.MetaQObjectHasTraits`,
121 and the parent classes :class:`~IPython.utils.traitlets.HasTraits` and
122 :class:`~IPython.qt.util.SuperQObject`.
@@ -0,0 +1,8 b''
1 Single codebase Python 3 support
2 --------------------------------
3
4 IPython previously supported Python 3 by running 2to3 during setup. We
5 have now switched to a single codebase which runs natively on Python 2.7
6 and 3.3.
7
8 For notes on how to maintain this, see :doc:`/development/pycompat`.
@@ -7,6 +7,7 b' Authors:'
7 * Brian Granger
7 * Brian Granger
8 * Min RK
8 * Min RK
9 """
9 """
10 from __future__ import print_function
10
11
11 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2011 The IPython Development Team
13 # Copyright (C) 2008-2011 The IPython Development Team
@@ -39,6 +40,7 b' from IPython.utils.traitlets import ('
39 from IPython.utils.importstring import import_item
40 from IPython.utils.importstring import import_item
40 from IPython.utils.text import indent, wrap_paragraphs, dedent
41 from IPython.utils.text import indent, wrap_paragraphs, dedent
41 from IPython.utils import py3compat
42 from IPython.utils import py3compat
43 from IPython.utils.py3compat import string_types, iteritems
42
44
43 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
44 # function for re-wrapping a helpstring
46 # function for re-wrapping a helpstring
@@ -154,7 +156,7 b' class Application(SingletonConfigurable):'
154 help="Set the log level by value or name.")
156 help="Set the log level by value or name.")
155 def _log_level_changed(self, name, old, new):
157 def _log_level_changed(self, name, old, new):
156 """Adjust the log level when log_level is set."""
158 """Adjust the log level when log_level is set."""
157 if isinstance(new, basestring):
159 if isinstance(new, string_types):
158 new = getattr(logging, new)
160 new = getattr(logging, new)
159 self.log_level = new
161 self.log_level = new
160 self.log.setLevel(new)
162 self.log.setLevel(new)
@@ -214,10 +216,10 b' class Application(SingletonConfigurable):'
214 flags = Dict()
216 flags = Dict()
215 def _flags_changed(self, name, old, new):
217 def _flags_changed(self, name, old, new):
216 """ensure flags dict is valid"""
218 """ensure flags dict is valid"""
217 for key,value in new.iteritems():
219 for key,value in iteritems(new):
218 assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
220 assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
219 assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
221 assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
220 assert isinstance(value[1], basestring), "Bad flag: %r:%s"%(key,value)
222 assert isinstance(value[1], string_types), "Bad flag: %r:%s"%(key,value)
221
223
222
224
223 # subcommands for launching other applications
225 # subcommands for launching other applications
@@ -274,7 +276,7 b' class Application(SingletonConfigurable):'
274 for c in cls.mro()[:-3]:
276 for c in cls.mro()[:-3]:
275 classdict[c.__name__] = c
277 classdict[c.__name__] = c
276
278
277 for alias, longname in self.aliases.iteritems():
279 for alias, longname in iteritems(self.aliases):
278 classname, traitname = longname.split('.',1)
280 classname, traitname = longname.split('.',1)
279 cls = classdict[classname]
281 cls = classdict[classname]
280
282
@@ -286,7 +288,7 b' class Application(SingletonConfigurable):'
286 help[0] = help[0].replace('--%s='%alias, '-%s '%alias)
288 help[0] = help[0].replace('--%s='%alias, '-%s '%alias)
287 lines.extend(help)
289 lines.extend(help)
288 # lines.append('')
290 # lines.append('')
289 print os.linesep.join(lines)
291 print(os.linesep.join(lines))
290
292
291 def print_flag_help(self):
293 def print_flag_help(self):
292 """Print the flag part of the help."""
294 """Print the flag part of the help."""
@@ -294,12 +296,12 b' class Application(SingletonConfigurable):'
294 return
296 return
295
297
296 lines = []
298 lines = []
297 for m, (cfg,help) in self.flags.iteritems():
299 for m, (cfg,help) in iteritems(self.flags):
298 prefix = '--' if len(m) > 1 else '-'
300 prefix = '--' if len(m) > 1 else '-'
299 lines.append(prefix+m)
301 lines.append(prefix+m)
300 lines.append(indent(dedent(help.strip())))
302 lines.append(indent(dedent(help.strip())))
301 # lines.append('')
303 # lines.append('')
302 print os.linesep.join(lines)
304 print(os.linesep.join(lines))
303
305
304 def print_options(self):
306 def print_options(self):
305 if not self.flags and not self.aliases:
307 if not self.flags and not self.aliases:
@@ -310,10 +312,10 b' class Application(SingletonConfigurable):'
310 for p in wrap_paragraphs(self.option_description):
312 for p in wrap_paragraphs(self.option_description):
311 lines.append(p)
313 lines.append(p)
312 lines.append('')
314 lines.append('')
313 print os.linesep.join(lines)
315 print(os.linesep.join(lines))
314 self.print_flag_help()
316 self.print_flag_help()
315 self.print_alias_help()
317 self.print_alias_help()
316 print
318 print()
317
319
318 def print_subcommands(self):
320 def print_subcommands(self):
319 """Print the subcommand part of the help."""
321 """Print the subcommand part of the help."""
@@ -326,12 +328,12 b' class Application(SingletonConfigurable):'
326 for p in wrap_paragraphs(self.subcommand_description):
328 for p in wrap_paragraphs(self.subcommand_description):
327 lines.append(p)
329 lines.append(p)
328 lines.append('')
330 lines.append('')
329 for subc, (cls, help) in self.subcommands.iteritems():
331 for subc, (cls, help) in iteritems(self.subcommands):
330 lines.append(subc)
332 lines.append(subc)
331 if help:
333 if help:
332 lines.append(indent(dedent(help.strip())))
334 lines.append(indent(dedent(help.strip())))
333 lines.append('')
335 lines.append('')
334 print os.linesep.join(lines)
336 print(os.linesep.join(lines))
335
337
336 def print_help(self, classes=False):
338 def print_help(self, classes=False):
337 """Print the help for each Configurable class in self.classes.
339 """Print the help for each Configurable class in self.classes.
@@ -344,19 +346,19 b' class Application(SingletonConfigurable):'
344
346
345 if classes:
347 if classes:
346 if self.classes:
348 if self.classes:
347 print "Class parameters"
349 print("Class parameters")
348 print "----------------"
350 print("----------------")
349 print
351 print()
350 for p in wrap_paragraphs(self.keyvalue_description):
352 for p in wrap_paragraphs(self.keyvalue_description):
351 print p
353 print(p)
352 print
354 print()
353
355
354 for cls in self.classes:
356 for cls in self.classes:
355 cls.class_print_help()
357 cls.class_print_help()
356 print
358 print()
357 else:
359 else:
358 print "To see all available configurables, use `--help-all`"
360 print("To see all available configurables, use `--help-all`")
359 print
361 print()
360
362
361 self.print_examples()
363 self.print_examples()
362
364
@@ -364,8 +366,8 b' class Application(SingletonConfigurable):'
364 def print_description(self):
366 def print_description(self):
365 """Print the application description."""
367 """Print the application description."""
366 for p in wrap_paragraphs(self.description):
368 for p in wrap_paragraphs(self.description):
367 print p
369 print(p)
368 print
370 print()
369
371
370 def print_examples(self):
372 def print_examples(self):
371 """Print usage and examples.
373 """Print usage and examples.
@@ -374,15 +376,15 b' class Application(SingletonConfigurable):'
374 and should contain examples of the application's usage.
376 and should contain examples of the application's usage.
375 """
377 """
376 if self.examples:
378 if self.examples:
377 print "Examples"
379 print("Examples")
378 print "--------"
380 print("--------")
379 print
381 print()
380 print indent(dedent(self.examples.strip()))
382 print(indent(dedent(self.examples.strip())))
381 print
383 print()
382
384
383 def print_version(self):
385 def print_version(self):
384 """Print the version string."""
386 """Print the version string."""
385 print self.version
387 print(self.version)
386
388
387 def update_config(self, config):
389 def update_config(self, config):
388 """Fire the traits events when the config is updated."""
390 """Fire the traits events when the config is updated."""
@@ -399,7 +401,7 b' class Application(SingletonConfigurable):'
399 """Initialize a subcommand with argv."""
401 """Initialize a subcommand with argv."""
400 subapp,help = self.subcommands.get(subc)
402 subapp,help = self.subcommands.get(subc)
401
403
402 if isinstance(subapp, basestring):
404 if isinstance(subapp, string_types):
403 subapp = import_item(subapp)
405 subapp = import_item(subapp)
404
406
405 # clear existing instances
407 # clear existing instances
@@ -432,7 +434,7 b' class Application(SingletonConfigurable):'
432 # flatten aliases, which have the form:
434 # flatten aliases, which have the form:
433 # { 'alias' : 'Class.trait' }
435 # { 'alias' : 'Class.trait' }
434 aliases = {}
436 aliases = {}
435 for alias, cls_trait in self.aliases.iteritems():
437 for alias, cls_trait in iteritems(self.aliases):
436 cls,trait = cls_trait.split('.',1)
438 cls,trait = cls_trait.split('.',1)
437 children = mro_tree[cls]
439 children = mro_tree[cls]
438 if len(children) == 1:
440 if len(children) == 1:
@@ -443,9 +445,9 b' class Application(SingletonConfigurable):'
443 # flatten flags, which are of the form:
445 # flatten flags, which are of the form:
444 # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
446 # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
445 flags = {}
447 flags = {}
446 for key, (flagdict, help) in self.flags.iteritems():
448 for key, (flagdict, help) in iteritems(self.flags):
447 newflag = {}
449 newflag = {}
448 for cls, subdict in flagdict.iteritems():
450 for cls, subdict in iteritems(flagdict):
449 children = mro_tree[cls]
451 children = mro_tree[cls]
450 # exactly one descendent, promote flag section
452 # exactly one descendent, promote flag section
451 if len(children) == 1:
453 if len(children) == 1:
@@ -13,6 +13,7 b' Authors:'
13 * Fernando Perez
13 * Fernando Perez
14 * Min RK
14 * Min RK
15 """
15 """
16 from __future__ import print_function
16
17
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2011 The IPython Development Team
19 # Copyright (C) 2008-2011 The IPython Development Team
@@ -31,6 +32,7 b' from copy import deepcopy'
31 from .loader import Config, LazyConfigValue
32 from .loader import Config, LazyConfigValue
32 from IPython.utils.traitlets import HasTraits, Instance
33 from IPython.utils.traitlets import HasTraits, Instance
33 from IPython.utils.text import indent, wrap_paragraphs
34 from IPython.utils.text import indent, wrap_paragraphs
35 from IPython.utils.py3compat import iteritems
34
36
35
37
36 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
@@ -147,7 +149,7 b' class Configurable(HasTraits):'
147 section_names = self.section_names()
149 section_names = self.section_names()
148
150
149 my_config = self._find_my_config(cfg)
151 my_config = self._find_my_config(cfg)
150 for name, config_value in my_config.iteritems():
152 for name, config_value in iteritems(my_config):
151 if name in traits:
153 if name in traits:
152 if isinstance(config_value, LazyConfigValue):
154 if isinstance(config_value, LazyConfigValue):
153 # ConfigValue is a wrapper for using append / update on containers
155 # ConfigValue is a wrapper for using append / update on containers
@@ -196,7 +198,7 b' class Configurable(HasTraits):'
196 final_help = []
198 final_help = []
197 final_help.append(u'%s options' % cls.__name__)
199 final_help.append(u'%s options' % cls.__name__)
198 final_help.append(len(final_help[0])*u'-')
200 final_help.append(len(final_help[0])*u'-')
199 for k, v in sorted(cls.class_traits(config=True).iteritems()):
201 for k, v in sorted(cls.class_traits(config=True).items()):
200 help = cls.class_get_trait_help(v, inst)
202 help = cls.class_get_trait_help(v, inst)
201 final_help.append(help)
203 final_help.append(help)
202 return '\n'.join(final_help)
204 return '\n'.join(final_help)
@@ -236,7 +238,7 b' class Configurable(HasTraits):'
236 @classmethod
238 @classmethod
237 def class_print_help(cls, inst=None):
239 def class_print_help(cls, inst=None):
238 """Get the help string for a single trait and print it."""
240 """Get the help string for a single trait and print it."""
239 print cls.class_get_help(inst)
241 print(cls.class_get_help(inst))
240
242
241 @classmethod
243 @classmethod
242 def class_config_section(cls):
244 def class_config_section(cls):
@@ -276,7 +278,7 b' class Configurable(HasTraits):'
276 lines.append(c('%s will inherit config from: %s'%(cls.__name__, pstr)))
278 lines.append(c('%s will inherit config from: %s'%(cls.__name__, pstr)))
277 lines.append('')
279 lines.append('')
278
280
279 for name, trait in cls.class_traits(config=True).iteritems():
281 for name, trait in iteritems(cls.class_traits(config=True)):
280 help = trait.get_metadata('help') or ''
282 help = trait.get_metadata('help') or ''
281 lines.append(c(help))
283 lines.append(c(help))
282 lines.append('# c.%s.%s = %r'%(cls.__name__, name, trait.get_default_value()))
284 lines.append('# c.%s.%s = %r'%(cls.__name__, name, trait.get_default_value()))
@@ -23,7 +23,6 b' Authors'
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 import __builtin__ as builtin_mod
27 import argparse
26 import argparse
28 import copy
27 import copy
29 import os
28 import os
@@ -33,6 +32,7 b' import sys'
33 from IPython.utils.path import filefind, get_ipython_dir
32 from IPython.utils.path import filefind, get_ipython_dir
34 from IPython.utils import py3compat, warn
33 from IPython.utils import py3compat, warn
35 from IPython.utils.encoding import DEFAULT_ENCODING
34 from IPython.utils.encoding import DEFAULT_ENCODING
35 from IPython.utils.py3compat import builtin_mod, unicode_type, iteritems
36 from IPython.utils.traitlets import HasTraits, List, Any, TraitError
36 from IPython.utils.traitlets import HasTraits, List, Any, TraitError
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
@@ -193,7 +193,7 b' class Config(dict):'
193 def merge(self, other):
193 def merge(self, other):
194 """merge another config object into this one"""
194 """merge another config object into this one"""
195 to_update = {}
195 to_update = {}
196 for k, v in other.iteritems():
196 for k, v in iteritems(other):
197 if k not in self:
197 if k not in self:
198 to_update[k] = v
198 to_update[k] = v
199 else: # I have this key
199 else: # I have this key
@@ -242,7 +242,7 b' class Config(dict):'
242
242
243 def __deepcopy__(self, memo):
243 def __deepcopy__(self, memo):
244 import copy
244 import copy
245 return type(self)(copy.deepcopy(self.items()))
245 return type(self)(copy.deepcopy(list(self.items())))
246
246
247 def __getitem__(self, key):
247 def __getitem__(self, key):
248 # We cannot use directly self._is_section_key, because it triggers
248 # We cannot use directly self._is_section_key, because it triggers
@@ -478,14 +478,14 b' class CommandLineConfigLoader(ConfigLoader):'
478 # This case happens if the rhs is a string.
478 # This case happens if the rhs is a string.
479 value = rhs
479 value = rhs
480
480
481 exec u'self.config.%s = value' % lhs
481 exec(u'self.config.%s = value' % lhs)
482
482
483 def _load_flag(self, cfg):
483 def _load_flag(self, cfg):
484 """update self.config from a flag, which can be a dict or Config"""
484 """update self.config from a flag, which can be a dict or Config"""
485 if isinstance(cfg, (dict, Config)):
485 if isinstance(cfg, (dict, Config)):
486 # don't clobber whole config sections, update
486 # don't clobber whole config sections, update
487 # each section from config:
487 # each section from config:
488 for sec,c in cfg.iteritems():
488 for sec,c in iteritems(cfg):
489 self.config[sec].update(c)
489 self.config[sec].update(c)
490 else:
490 else:
491 raise TypeError("Invalid flag: %r" % cfg)
491 raise TypeError("Invalid flag: %r" % cfg)
@@ -567,7 +567,7 b' class KeyValueConfigLoader(CommandLineConfigLoader):'
567 if enc is None:
567 if enc is None:
568 enc = DEFAULT_ENCODING
568 enc = DEFAULT_ENCODING
569 for arg in argv:
569 for arg in argv:
570 if not isinstance(arg, unicode):
570 if not isinstance(arg, unicode_type):
571 # only decode if not already decoded
571 # only decode if not already decoded
572 arg = arg.decode(enc)
572 arg = arg.decode(enc)
573 uargv.append(arg)
573 uargv.append(arg)
@@ -733,8 +733,8 b' class ArgParseConfigLoader(CommandLineConfigLoader):'
733
733
734 def _convert_to_config(self):
734 def _convert_to_config(self):
735 """self.parsed_data->self.config"""
735 """self.parsed_data->self.config"""
736 for k, v in vars(self.parsed_data).iteritems():
736 for k, v in iteritems(vars(self.parsed_data)):
737 exec "self.config.%s = v"%k in locals(), globals()
737 exec("self.config.%s = v"%k, locals(), globals())
738
738
739 class KVArgParseConfigLoader(ArgParseConfigLoader):
739 class KVArgParseConfigLoader(ArgParseConfigLoader):
740 """A config loader that loads aliases and flags with argparse,
740 """A config loader that loads aliases and flags with argparse,
@@ -750,17 +750,17 b' class KVArgParseConfigLoader(ArgParseConfigLoader):'
750 if flags is None:
750 if flags is None:
751 flags = self.flags
751 flags = self.flags
752 paa = self.parser.add_argument
752 paa = self.parser.add_argument
753 for key,value in aliases.iteritems():
753 for key,value in iteritems(aliases):
754 if key in flags:
754 if key in flags:
755 # flags
755 # flags
756 nargs = '?'
756 nargs = '?'
757 else:
757 else:
758 nargs = None
758 nargs = None
759 if len(key) is 1:
759 if len(key) is 1:
760 paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs)
760 paa('-'+key, '--'+key, type=unicode_type, dest=value, nargs=nargs)
761 else:
761 else:
762 paa('--'+key, type=unicode, dest=value, nargs=nargs)
762 paa('--'+key, type=unicode_type, dest=value, nargs=nargs)
763 for key, (value, help) in flags.iteritems():
763 for key, (value, help) in iteritems(flags):
764 if key in self.aliases:
764 if key in self.aliases:
765 #
765 #
766 self.alias_flags[self.aliases[key]] = value
766 self.alias_flags[self.aliases[key]] = value
@@ -779,7 +779,7 b' class KVArgParseConfigLoader(ArgParseConfigLoader):'
779 else:
779 else:
780 subcs = []
780 subcs = []
781
781
782 for k, v in vars(self.parsed_data).iteritems():
782 for k, v in iteritems(vars(self.parsed_data)):
783 if v is None:
783 if v is None:
784 # it was a flag that shares the name of an alias
784 # it was a flag that shares the name of an alias
785 subcs.append(self.alias_flags[k])
785 subcs.append(self.alias_flags[k])
@@ -297,9 +297,9 b' class Containers(Configurable):'
297 class TestConfigContainers(TestCase):
297 class TestConfigContainers(TestCase):
298 def test_extend(self):
298 def test_extend(self):
299 c = Config()
299 c = Config()
300 c.Containers.lis.extend(range(5))
300 c.Containers.lis.extend(list(range(5)))
301 obj = Containers(config=c)
301 obj = Containers(config=c)
302 self.assertEqual(obj.lis, range(-1,5))
302 self.assertEqual(obj.lis, list(range(-1,5)))
303
303
304 def test_insert(self):
304 def test_insert(self):
305 c = Config()
305 c = Config()
@@ -64,7 +64,7 b' class TestPyFileCL(TestCase):'
64 self.assertEqual(config.a, 10)
64 self.assertEqual(config.a, 10)
65 self.assertEqual(config.b, 20)
65 self.assertEqual(config.b, 20)
66 self.assertEqual(config.Foo.Bar.value, 10)
66 self.assertEqual(config.Foo.Bar.value, 10)
67 self.assertEqual(config.Foo.Bam.value, range(10))
67 self.assertEqual(config.Foo.Bam.value, list(range(10)))
68 self.assertEqual(config.D.C.value, 'hi there')
68 self.assertEqual(config.D.C.value, 'hi there')
69
69
70 class MyLoader1(ArgParseConfigLoader):
70 class MyLoader1(ArgParseConfigLoader):
@@ -93,8 +93,8 b' class TestArgParseCL(TestCase):'
93 self.assertEqual(config.n, True)
93 self.assertEqual(config.n, True)
94 self.assertEqual(config.Global.bam, 'wow')
94 self.assertEqual(config.Global.bam, 'wow')
95 config = cl.load_config(['wow'])
95 config = cl.load_config(['wow'])
96 self.assertEqual(config.keys(), ['Global'])
96 self.assertEqual(list(config.keys()), ['Global'])
97 self.assertEqual(config.Global.keys(), ['bam'])
97 self.assertEqual(list(config.Global.keys()), ['bam'])
98 self.assertEqual(config.Global.bam, 'wow')
98 self.assertEqual(config.Global.bam, 'wow')
99
99
100 def test_add_arguments(self):
100 def test_add_arguments(self):
@@ -126,7 +126,7 b' class TestKeyValueCL(TestCase):'
126 self.assertEqual(config.a, 10)
126 self.assertEqual(config.a, 10)
127 self.assertEqual(config.b, 20)
127 self.assertEqual(config.b, 20)
128 self.assertEqual(config.Foo.Bar.value, 10)
128 self.assertEqual(config.Foo.Bar.value, 10)
129 self.assertEqual(config.Foo.Bam.value, range(10))
129 self.assertEqual(config.Foo.Bam.value, list(range(10)))
130 self.assertEqual(config.D.C.value, 'hi there')
130 self.assertEqual(config.D.C.value, 'hi there')
131
131
132 def test_expanduser(self):
132 def test_expanduser(self):
@@ -256,7 +256,7 b' class TestConfig(TestCase):'
256
256
257 def test_builtin(self):
257 def test_builtin(self):
258 c1 = Config()
258 c1 = Config()
259 exec 'foo = True' in c1
259 exec('foo = True', c1)
260 self.assertEqual(c1.foo, True)
260 self.assertEqual(c1.foo, True)
261 c1.format = "json"
261 c1.format = "json"
262
262
@@ -27,6 +27,7 b' import sys'
27 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
28 from IPython.core.error import UsageError
28 from IPython.core.error import UsageError
29
29
30 from IPython.utils.py3compat import string_types
30 from IPython.utils.traitlets import List, Instance
31 from IPython.utils.traitlets import List, Instance
31 from IPython.utils.warn import error
32 from IPython.utils.warn import error
32
33
@@ -131,7 +132,7 b' class Alias(object):'
131 raise InvalidAliasError("The name %s can't be aliased "
132 raise InvalidAliasError("The name %s can't be aliased "
132 "because it is another magic command." % self.name)
133 "because it is another magic command." % self.name)
133
134
134 if not (isinstance(self.cmd, basestring)):
135 if not (isinstance(self.cmd, string_types)):
135 raise InvalidAliasError("An alias command must be a string, "
136 raise InvalidAliasError("An alias command must be a string, "
136 "got: %r" % self.cmd)
137 "got: %r" % self.cmd)
137
138
@@ -18,10 +18,9 b' Authors:'
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 import __builtin__
22
23 from IPython.config.configurable import Configurable
21 from IPython.config.configurable import Configurable
24
22
23 from IPython.utils.py3compat import builtin_mod, iteritems
25 from IPython.utils.traitlets import Instance
24 from IPython.utils.traitlets import Instance
26
25
27 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
@@ -78,7 +77,7 b' class BuiltinTrap(Configurable):'
78
77
79 def add_builtin(self, key, value):
78 def add_builtin(self, key, value):
80 """Add a builtin and save the original."""
79 """Add a builtin and save the original."""
81 bdict = __builtin__.__dict__
80 bdict = builtin_mod.__dict__
82 orig = bdict.get(key, BuiltinUndefined)
81 orig = bdict.get(key, BuiltinUndefined)
83 if value is HideBuiltin:
82 if value is HideBuiltin:
84 if orig is not BuiltinUndefined: #same as 'key in bdict'
83 if orig is not BuiltinUndefined: #same as 'key in bdict'
@@ -91,22 +90,22 b' class BuiltinTrap(Configurable):'
91 def remove_builtin(self, key, orig):
90 def remove_builtin(self, key, orig):
92 """Remove an added builtin and re-set the original."""
91 """Remove an added builtin and re-set the original."""
93 if orig is BuiltinUndefined:
92 if orig is BuiltinUndefined:
94 del __builtin__.__dict__[key]
93 del builtin_mod.__dict__[key]
95 else:
94 else:
96 __builtin__.__dict__[key] = orig
95 builtin_mod.__dict__[key] = orig
97
96
98 def activate(self):
97 def activate(self):
99 """Store ipython references in the __builtin__ namespace."""
98 """Store ipython references in the __builtin__ namespace."""
100
99
101 add_builtin = self.add_builtin
100 add_builtin = self.add_builtin
102 for name, func in self.auto_builtins.iteritems():
101 for name, func in iteritems(self.auto_builtins):
103 add_builtin(name, func)
102 add_builtin(name, func)
104
103
105 def deactivate(self):
104 def deactivate(self):
106 """Remove any builtins which might have been added by add_builtins, or
105 """Remove any builtins which might have been added by add_builtins, or
107 restore overwritten ones to their previous values."""
106 restore overwritten ones to their previous values."""
108 remove_builtin = self.remove_builtin
107 remove_builtin = self.remove_builtin
109 for key, val in self._orig_builtins.iteritems():
108 for key, val in iteritems(self._orig_builtins):
110 remove_builtin(key, val)
109 remove_builtin(key, val)
111 self._orig_builtins.clear()
110 self._orig_builtins.clear()
112 self._builtins_added = False
111 self._builtins_added = False
@@ -66,7 +66,6 b' Notes:'
66 # Imports
66 # Imports
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 import __builtin__
70 import __main__
69 import __main__
71 import glob
70 import glob
72 import inspect
71 import inspect
@@ -83,6 +82,7 b' from IPython.utils import generics'
83 from IPython.utils import io
82 from IPython.utils import io
84 from IPython.utils.dir2 import dir2
83 from IPython.utils.dir2 import dir2
85 from IPython.utils.process import arg_split
84 from IPython.utils.process import arg_split
85 from IPython.utils.py3compat import builtin_mod, string_types
86 from IPython.utils.traitlets import CBool, Enum
86 from IPython.utils.traitlets import CBool, Enum
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
@@ -353,7 +353,7 b' class Completer(Configurable):'
353 match_append = matches.append
353 match_append = matches.append
354 n = len(text)
354 n = len(text)
355 for lst in [keyword.kwlist,
355 for lst in [keyword.kwlist,
356 __builtin__.__dict__.keys(),
356 builtin_mod.__dict__.keys(),
357 self.namespace.keys(),
357 self.namespace.keys(),
358 self.global_namespace.keys()]:
358 self.global_namespace.keys()]:
359 for word in lst:
359 for word in lst:
@@ -423,7 +423,7 b' def get__all__entries(obj):'
423 except:
423 except:
424 return []
424 return []
425
425
426 return [w for w in words if isinstance(w, basestring)]
426 return [w for w in words if isinstance(w, string_types)]
427
427
428
428
429 class IPCompleter(Completer):
429 class IPCompleter(Completer):
@@ -31,6 +31,7 b' from zipimport import zipimporter'
31 from IPython.core.completer import expand_user, compress_user
31 from IPython.core.completer import expand_user, compress_user
32 from IPython.core.error import TryNext
32 from IPython.core.error import TryNext
33 from IPython.utils._process_common import arg_split
33 from IPython.utils._process_common import arg_split
34 from IPython.utils.py3compat import string_types
34
35
35 # FIXME: this should be pulled in with the right call via the component system
36 # FIXME: this should be pulled in with the right call via the component system
36 from IPython import get_ipython
37 from IPython import get_ipython
@@ -189,7 +190,7 b' def quick_completer(cmd, completions):'
189 [d:\ipython]|3> foo ba
190 [d:\ipython]|3> foo ba
190 """
191 """
191
192
192 if isinstance(completions, basestring):
193 if isinstance(completions, string_types):
193 completions = completions.split()
194 completions = completions.split()
194
195
195 def do_complete(self, event):
196 def do_complete(self, event):
@@ -268,7 +269,7 b' def magic_run_completer(self, event):'
268 # should complete on all files, since after the first one other files may
269 # should complete on all files, since after the first one other files may
269 # be arguments to the input script.
270 # be arguments to the input script.
270
271
271 if filter(magic_run_re.match, comps):
272 if any(magic_run_re.match(c) for c in comps):
272 pys = [f.replace('\\','/') for f in lglob('*')]
273 pys = [f.replace('\\','/') for f in lglob('*')]
273 else:
274 else:
274 pys = [f.replace('\\','/')
275 pys = [f.replace('\\','/')
@@ -323,7 +324,7 b' def cd_completer(self, event):'
323 return [compress_user(relpath, tilde_expand, tilde_val)]
324 return [compress_user(relpath, tilde_expand, tilde_val)]
324
325
325 # if no completions so far, try bookmarks
326 # if no completions so far, try bookmarks
326 bks = self.db.get('bookmarks',{}).iterkeys()
327 bks = self.db.get('bookmarks',{})
327 bkmatches = [s for s in bks if s.startswith(event.symbol)]
328 bkmatches = [s for s in bks if s.startswith(event.symbol)]
328 if bkmatches:
329 if bkmatches:
329 return bkmatches
330 return bkmatches
@@ -28,6 +28,7 b' from pprint import pformat'
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.core.release import author_email
29 from IPython.core.release import author_email
30 from IPython.utils.sysinfo import sys_info
30 from IPython.utils.sysinfo import sys_info
31 from IPython.utils.py3compat import input
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Code
34 # Code
@@ -176,7 +177,7 b' class CrashHandler(object):'
176 # Construct report on disk
177 # Construct report on disk
177 report.write(self.make_report(traceback))
178 report.write(self.make_report(traceback))
178 report.close()
179 report.close()
179 raw_input("Hit <Enter> to quit (your terminal may close):")
180 input("Hit <Enter> to quit (your terminal may close):")
180
181
181 def make_report(self,traceback):
182 def make_report(self,traceback):
182 """Return a string containing a crash report."""
183 """Return a string containing a crash report."""
@@ -146,7 +146,10 b' class Tracer(object):'
146 # at least raise that limit to 80 chars, which should be enough for
146 # at least raise that limit to 80 chars, which should be enough for
147 # most interactive uses.
147 # most interactive uses.
148 try:
148 try:
149 from repr import aRepr
149 try:
150 from reprlib import aRepr # Py 3
151 except ImportError:
152 from repr import aRepr # Py 2
150 aRepr.maxstring = 80
153 aRepr.maxstring = 80
151 except:
154 except:
152 # This is only a user-facing convenience, so any error we encounter
155 # This is only a user-facing convenience, so any error we encounter
@@ -331,7 +334,10 b' class Pdb(OldPdb):'
331 # vds: <<
334 # vds: <<
332
335
333 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
336 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
334 import repr
337 try:
338 import reprlib # Py 3
339 except ImportError:
340 import repr as reprlib # Py 2
335
341
336 ret = []
342 ret = []
337
343
@@ -349,7 +355,7 b' class Pdb(OldPdb):'
349 if '__return__' in frame.f_locals:
355 if '__return__' in frame.f_locals:
350 rv = frame.f_locals['__return__']
356 rv = frame.f_locals['__return__']
351 #return_value += '->'
357 #return_value += '->'
352 return_value += repr.repr(rv) + '\n'
358 return_value += reprlib.repr(rv) + '\n'
353 ret.append(return_value)
359 ret.append(return_value)
354
360
355 #s = filename + '(' + `lineno` + ')'
361 #s = filename + '(' + `lineno` + ')'
@@ -364,7 +370,7 b' class Pdb(OldPdb):'
364 call = ''
370 call = ''
365 if func != '?':
371 if func != '?':
366 if '__args__' in frame.f_locals:
372 if '__args__' in frame.f_locals:
367 args = repr.repr(frame.f_locals['__args__'])
373 args = reprlib.repr(frame.f_locals['__args__'])
368 else:
374 else:
369 args = '()'
375 args = '()'
370 call = tpl_call % (func, args)
376 call = tpl_call % (func, args)
@@ -22,7 +22,8 b' from __future__ import print_function'
22 import os
22 import os
23 import struct
23 import struct
24
24
25 from IPython.utils.py3compat import string_types, cast_bytes_py2, cast_unicode
25 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
26 unicode_type)
26
27
27 from .displaypub import publish_display_data
28 from .displaypub import publish_display_data
28
29
@@ -300,7 +301,7 b' class DisplayObject(object):'
300
301
301 self.data = data
302 self.data = data
302 self.url = url
303 self.url = url
303 self.filename = None if filename is None else unicode(filename)
304 self.filename = None if filename is None else unicode_type(filename)
304
305
305 self.reload()
306 self.reload()
306
307
@@ -444,11 +445,11 b' class Javascript(DisplayObject):'
444 The full URLs of the css files should be given. A single css URL
445 The full URLs of the css files should be given. A single css URL
445 can also be given as a string.
446 can also be given as a string.
446 """
447 """
447 if isinstance(lib, basestring):
448 if isinstance(lib, string_types):
448 lib = [lib]
449 lib = [lib]
449 elif lib is None:
450 elif lib is None:
450 lib = []
451 lib = []
451 if isinstance(css, basestring):
452 if isinstance(css, string_types):
452 css = [css]
453 css = [css]
453 elif css is None:
454 elif css is None:
454 css = []
455 css = []
@@ -590,7 +591,7 b' class Image(DisplayObject):'
590 if data[:2] == _JPEG:
591 if data[:2] == _JPEG:
591 format = 'jpeg'
592 format = 'jpeg'
592
593
593 self.format = unicode(format).lower()
594 self.format = unicode_type(format).lower()
594 self.embed = embed if embed is not None else (url is None)
595 self.embed = embed if embed is not None else (url is None)
595
596
596 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
597 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
@@ -654,7 +655,7 b' class Image(DisplayObject):'
654 return self._data_and_metadata()
655 return self._data_and_metadata()
655
656
656 def _find_ext(self, s):
657 def _find_ext(self, s):
657 return unicode(s.split('.')[-1].lower())
658 return unicode_type(s.split('.')[-1].lower())
658
659
659
660
660 def clear_output(wait=False):
661 def clear_output(wait=False):
@@ -23,13 +23,12 b' Authors:'
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 from __future__ import print_function
24 from __future__ import print_function
25
25
26 import __builtin__
27
28 import sys
26 import sys
29
27
30
28
31 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
32 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.py3compat import builtin_mod
33 from IPython.utils.traitlets import Instance
32 from IPython.utils.traitlets import Instance
34 from IPython.utils.warn import warn
33 from IPython.utils.warn import warn
35
34
@@ -90,7 +89,7 b' class DisplayHook(Configurable):'
90 # If something injected a '_' variable in __builtin__, delete
89 # If something injected a '_' variable in __builtin__, delete
91 # ipython's automatic one so we don't clobber that. gettext() in
90 # ipython's automatic one so we don't clobber that. gettext() in
92 # particular uses _, so we need to stay away from it.
91 # particular uses _, so we need to stay away from it.
93 if '_' in __builtin__.__dict__:
92 if '_' in builtin_mod.__dict__:
94 try:
93 try:
95 del self.shell.user_ns['_']
94 del self.shell.user_ns['_']
96 except KeyError:
95 except KeyError:
@@ -206,7 +205,7 b' class DisplayHook(Configurable):'
206 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
205 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
207 # we cause buggy behavior for things like gettext).
206 # we cause buggy behavior for things like gettext).
208
207
209 if '_' not in __builtin__.__dict__:
208 if '_' not in builtin_mod.__dict__:
210 self.___ = self.__
209 self.___ = self.__
211 self.__ = self._
210 self.__ = self._
212 self._ = result
211 self._ = result
@@ -270,7 +269,7 b' class DisplayHook(Configurable):'
270 # Release our own references to objects:
269 # Release our own references to objects:
271 self._, self.__, self.___ = '', '', ''
270 self._, self.__, self.___ = '', '', ''
272
271
273 if '_' not in __builtin__.__dict__:
272 if '_' not in builtin_mod.__dict__:
274 self.shell.user_ns.update({'_':None,'__':None, '___':None})
273 self.shell.user_ns.update({'_':None,'__':None, '___':None})
275 import gc
274 import gc
276 # TODO: Is this really needed?
275 # TODO: Is this really needed?
@@ -31,6 +31,7 b' from __future__ import print_function'
31
31
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33 from IPython.utils import io
33 from IPython.utils import io
34 from IPython.utils.py3compat import string_types
34 from IPython.utils.traitlets import List
35 from IPython.utils.traitlets import List
35
36
36 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
@@ -58,7 +59,7 b' class DisplayPublisher(Configurable):'
58 Any metadata for the data.
59 Any metadata for the data.
59 """
60 """
60
61
61 if not isinstance(source, basestring):
62 if not isinstance(source, string_types):
62 raise TypeError('source must be a str, got: %r' % source)
63 raise TypeError('source must be a str, got: %r' % source)
63 if not isinstance(data, dict):
64 if not isinstance(data, dict):
64 raise TypeError('data must be a dict, got: %r' % data)
65 raise TypeError('data must be a dict, got: %r' % data)
@@ -24,7 +24,7 b' def exception_colors():'
24 >>> ec = exception_colors()
24 >>> ec = exception_colors()
25 >>> ec.active_scheme_name
25 >>> ec.active_scheme_name
26 ''
26 ''
27 >>> print ec.active_colors
27 >>> print(ec.active_colors)
28 None
28 None
29
29
30 Now we activate a color scheme:
30 Now we activate a color scheme:
@@ -170,7 +170,10 b' class ExtensionManager(Configurable):'
170 copy = copyfile
170 copy = copyfile
171 else:
171 else:
172 from urllib import urlretrieve # Deferred imports
172 from urllib import urlretrieve # Deferred imports
173 from urlparse import urlparse
173 try:
174 from urllib.parse import urlparse # Py3
175 except ImportError:
176 from urlparse import urlparse
174 src_filename = urlparse(url).path.split('/')[-1]
177 src_filename = urlparse(url).path.split('/')[-1]
175 copy = urlretrieve
178 copy = urlretrieve
176
179
@@ -27,8 +27,6 b' Authors:'
27 import abc
27 import abc
28 import sys
28 import sys
29 import warnings
29 import warnings
30 # We must use StringIO, as cStringIO doesn't handle unicode properly.
31 from StringIO import StringIO
32
30
33 # Our own imports
31 # Our own imports
34 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
@@ -36,7 +34,12 b' from IPython.lib import pretty'
36 from IPython.utils.traitlets import (
34 from IPython.utils.traitlets import (
37 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
35 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
38 )
36 )
39 from IPython.utils.py3compat import unicode_to_str
37 from IPython.utils.py3compat import unicode_to_str, with_metaclass, PY3
38
39 if PY3:
40 from io import StringIO
41 else:
42 from StringIO import StringIO
40
43
41
44
42 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
@@ -168,7 +171,7 b' class DisplayFormatter(Configurable):'
168 @property
171 @property
169 def format_types(self):
172 def format_types(self):
170 """Return the format types (MIME types) of the active formatters."""
173 """Return the format types (MIME types) of the active formatters."""
171 return self.formatters.keys()
174 return list(self.formatters.keys())
172
175
173
176
174 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
@@ -176,7 +179,7 b' class DisplayFormatter(Configurable):'
176 #-----------------------------------------------------------------------------
179 #-----------------------------------------------------------------------------
177
180
178
181
179 class FormatterABC(object):
182 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
180 """ Abstract base class for Formatters.
183 """ Abstract base class for Formatters.
181
184
182 A formatter is a callable class that is responsible for computing the
185 A formatter is a callable class that is responsible for computing the
@@ -184,7 +187,6 b' class FormatterABC(object):'
184 an HTML formatter would have a format type of `text/html` and would return
187 an HTML formatter would have a format type of `text/html` and would return
185 the HTML representation of the object when called.
188 the HTML representation of the object when called.
186 """
189 """
187 __metaclass__ = abc.ABCMeta
188
190
189 # The format type of the data returned, usually a MIME type.
191 # The format type of the data returned, usually a MIME type.
190 format_type = 'text/plain'
192 format_type = 'text/plain'
@@ -1,13 +1,18 b''
1 import abc
1 import abc
2 import functools
2 import functools
3 import re
3 import re
4 from StringIO import StringIO
5
4
6 from IPython.core.splitinput import LineInfo
5 from IPython.core.splitinput import LineInfo
7 from IPython.utils import tokenize2
6 from IPython.utils import tokenize2
8 from IPython.utils.openpy import cookie_comment_re
7 from IPython.utils.openpy import cookie_comment_re
8 from IPython.utils.py3compat import with_metaclass, PY3
9 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
9 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
10
10
11 if PY3:
12 from io import StringIO
13 else:
14 from StringIO import StringIO
15
11 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
12 # Globals
17 # Globals
13 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
@@ -33,9 +38,8 b' ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\\'
33 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
38 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
34
39
35
40
36 class InputTransformer(object):
41 class InputTransformer(with_metaclass(abc.ABCMeta, object)):
37 """Abstract base class for line-based input transformers."""
42 """Abstract base class for line-based input transformers."""
38 __metaclass__ = abc.ABCMeta
39
43
40 @abc.abstractmethod
44 @abc.abstractmethod
41 def push(self, line):
45 def push(self, line):
@@ -17,7 +17,6 b''
17 from __future__ import absolute_import
17 from __future__ import absolute_import
18 from __future__ import print_function
18 from __future__ import print_function
19
19
20 import __builtin__ as builtin_mod
21 import __future__
20 import __future__
22 import abc
21 import abc
23 import ast
22 import ast
@@ -69,6 +68,8 b' from IPython.utils.ipstruct import Struct'
69 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
70 from IPython.utils.pickleshare import PickleShareDB
69 from IPython.utils.pickleshare import PickleShareDB
71 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 with_metaclass, iteritems)
72 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.text import (format_screen, LSString, SList,
75 from IPython.utils.text import (format_screen, LSString, SList,
@@ -751,7 +752,7 b' class InteractiveShell(SingletonConfigurable):'
751 def restore_sys_module_state(self):
752 def restore_sys_module_state(self):
752 """Restore the state of the sys module."""
753 """Restore the state of the sys module."""
753 try:
754 try:
754 for k, v in self._orig_sys_module_state.iteritems():
755 for k, v in iteritems(self._orig_sys_module_state):
755 setattr(sys, k, v)
756 setattr(sys, k, v)
756 except AttributeError:
757 except AttributeError:
757 pass
758 pass
@@ -1242,7 +1243,7 b' class InteractiveShell(SingletonConfigurable):'
1242 # Also check in output history
1243 # Also check in output history
1243 ns_refs.append(self.history_manager.output_hist)
1244 ns_refs.append(self.history_manager.output_hist)
1244 for ns in ns_refs:
1245 for ns in ns_refs:
1245 to_delete = [n for n, o in ns.iteritems() if o is obj]
1246 to_delete = [n for n, o in iteritems(ns) if o is obj]
1246 for name in to_delete:
1247 for name in to_delete:
1247 del ns[name]
1248 del ns[name]
1248
1249
@@ -1294,8 +1295,8 b' class InteractiveShell(SingletonConfigurable):'
1294 # We need a dict of name/value pairs to do namespace updates.
1295 # We need a dict of name/value pairs to do namespace updates.
1295 if isinstance(variables, dict):
1296 if isinstance(variables, dict):
1296 vdict = variables
1297 vdict = variables
1297 elif isinstance(variables, (basestring, list, tuple)):
1298 elif isinstance(variables, string_types+(list, tuple)):
1298 if isinstance(variables, basestring):
1299 if isinstance(variables, string_types):
1299 vlist = variables.split()
1300 vlist = variables.split()
1300 else:
1301 else:
1301 vlist = variables
1302 vlist = variables
@@ -1334,7 +1335,7 b' class InteractiveShell(SingletonConfigurable):'
1334 variables : dict
1335 variables : dict
1335 A dictionary mapping object names (as strings) to the objects.
1336 A dictionary mapping object names (as strings) to the objects.
1336 """
1337 """
1337 for name, obj in variables.iteritems():
1338 for name, obj in iteritems(variables):
1338 if name in self.user_ns and self.user_ns[name] is obj:
1339 if name in self.user_ns and self.user_ns[name] is obj:
1339 del self.user_ns[name]
1340 del self.user_ns[name]
1340 self.user_ns_hidden.pop(name, None)
1341 self.user_ns_hidden.pop(name, None)
@@ -1589,14 +1590,14 b' class InteractiveShell(SingletonConfigurable):'
1589 msg = "CustomTB must return list of strings, not %r" % stb
1590 msg = "CustomTB must return list of strings, not %r" % stb
1590 if stb is None:
1591 if stb is None:
1591 return []
1592 return []
1592 elif isinstance(stb, basestring):
1593 elif isinstance(stb, string_types):
1593 return [stb]
1594 return [stb]
1594 elif not isinstance(stb, list):
1595 elif not isinstance(stb, list):
1595 raise TypeError(msg)
1596 raise TypeError(msg)
1596 # it's a list
1597 # it's a list
1597 for line in stb:
1598 for line in stb:
1598 # check every element
1599 # check every element
1599 if not isinstance(line, basestring):
1600 if not isinstance(line, string_types):
1600 raise TypeError(msg)
1601 raise TypeError(msg)
1601 return stb
1602 return stb
1602
1603
@@ -2200,7 +2201,7 b' class InteractiveShell(SingletonConfigurable):'
2200
2201
2201 from IPython.core import macro
2202 from IPython.core import macro
2202
2203
2203 if isinstance(themacro, basestring):
2204 if isinstance(themacro, string_types):
2204 themacro = macro.Macro(themacro)
2205 themacro = macro.Macro(themacro)
2205 if not isinstance(themacro, macro.Macro):
2206 if not isinstance(themacro, macro.Macro):
2206 raise ValueError('A macro must be a string or a Macro instance.')
2207 raise ValueError('A macro must be a string or a Macro instance.')
@@ -2383,7 +2384,7 b' class InteractiveShell(SingletonConfigurable):'
2383 exc_info = {
2384 exc_info = {
2384 u'status' : 'error',
2385 u'status' : 'error',
2385 u'traceback' : stb,
2386 u'traceback' : stb,
2386 u'ename' : unicode(etype.__name__),
2387 u'ename' : unicode_type(etype.__name__),
2387 u'evalue' : py3compat.safe_unicode(evalue),
2388 u'evalue' : py3compat.safe_unicode(evalue),
2388 }
2389 }
2389
2390
@@ -2446,7 +2447,7 b' class InteractiveShell(SingletonConfigurable):'
2446 user_ns = self.user_ns
2447 user_ns = self.user_ns
2447 global_ns = self.user_global_ns
2448 global_ns = self.user_global_ns
2448
2449
2449 for key, expr in expressions.iteritems():
2450 for key, expr in iteritems(expressions):
2450 try:
2451 try:
2451 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2452 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2452 except:
2453 except:
@@ -2461,7 +2462,7 b' class InteractiveShell(SingletonConfigurable):'
2461 def ex(self, cmd):
2462 def ex(self, cmd):
2462 """Execute a normal python statement in user namespace."""
2463 """Execute a normal python statement in user namespace."""
2463 with self.builtin_trap:
2464 with self.builtin_trap:
2464 exec cmd in self.user_global_ns, self.user_ns
2465 exec(cmd, self.user_global_ns, self.user_ns)
2465
2466
2466 def ev(self, expr):
2467 def ev(self, expr):
2467 """Evaluate python expression expr in user namespace.
2468 """Evaluate python expression expr in user namespace.
@@ -2686,7 +2687,7 b' class InteractiveShell(SingletonConfigurable):'
2686
2687
2687 # Execute any registered post-execution functions.
2688 # Execute any registered post-execution functions.
2688 # unless we are silent
2689 # unless we are silent
2689 post_exec = [] if silent else self._post_execute.iteritems()
2690 post_exec = [] if silent else iteritems(self._post_execute)
2690
2691
2691 for func, status in post_exec:
2692 for func, status in post_exec:
2692 if self.disable_failing_post_execute and not status:
2693 if self.disable_failing_post_execute and not status:
@@ -2842,7 +2843,7 b' class InteractiveShell(SingletonConfigurable):'
2842 try:
2843 try:
2843 self.hooks.pre_run_code_hook()
2844 self.hooks.pre_run_code_hook()
2844 #rprint('Running code', repr(code_obj)) # dbg
2845 #rprint('Running code', repr(code_obj)) # dbg
2845 exec code_obj in self.user_global_ns, self.user_ns
2846 exec(code_obj, self.user_global_ns, self.user_ns)
2846 finally:
2847 finally:
2847 # Reset our crash handler in place
2848 # Reset our crash handler in place
2848 sys.excepthook = old_excepthook
2849 sys.excepthook = old_excepthook
@@ -3113,7 +3114,7 b' class InteractiveShell(SingletonConfigurable):'
3113 except Exception:
3114 except Exception:
3114 raise ValueError(("'%s' was not found in history, as a file, url, "
3115 raise ValueError(("'%s' was not found in history, as a file, url, "
3115 "nor in the user namespace.") % target)
3116 "nor in the user namespace.") % target)
3116 if isinstance(codeobj, basestring):
3117 if isinstance(codeobj, string_types):
3117 return codeobj
3118 return codeobj
3118 elif isinstance(codeobj, Macro):
3119 elif isinstance(codeobj, Macro):
3119 return codeobj.value
3120 return codeobj.value
@@ -3157,8 +3158,7 b' class InteractiveShell(SingletonConfigurable):'
3157 self.restore_sys_module_state()
3158 self.restore_sys_module_state()
3158
3159
3159
3160
3160 class InteractiveShellABC(object):
3161 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3161 """An abstract base class for InteractiveShell."""
3162 """An abstract base class for InteractiveShell."""
3162 __metaclass__ = abc.ABCMeta
3163
3163
3164 InteractiveShellABC.register(InteractiveShell)
3164 InteractiveShellABC.register(InteractiveShell)
@@ -1,5 +1,6 b''
1 """Logger class for IPython's logging facilities.
1 """Logger class for IPython's logging facilities.
2 """
2 """
3 from __future__ import print_function
3
4
4 #*****************************************************************************
5 #*****************************************************************************
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -137,33 +138,33 b' class Logger(object):'
137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138
139
139 if self.logfile is None:
140 if self.logfile is None:
140 print """
141 print("""
141 Logging hasn't been started yet (use logstart for that).
142 Logging hasn't been started yet (use logstart for that).
142
143
143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 which already exists. But you must first start the logging process with
145 which already exists. But you must first start the logging process with
145 %logstart (optionally giving a logfile name)."""
146 %logstart (optionally giving a logfile name).""")
146
147
147 else:
148 else:
148 if self.log_active == val:
149 if self.log_active == val:
149 print 'Logging is already',label[val]
150 print('Logging is already',label[val])
150 else:
151 else:
151 print 'Switching logging',label[val]
152 print('Switching logging',label[val])
152 self.log_active = not self.log_active
153 self.log_active = not self.log_active
153 self.log_active_out = self.log_active
154 self.log_active_out = self.log_active
154
155
155 def logstate(self):
156 def logstate(self):
156 """Print a status message about the logger."""
157 """Print a status message about the logger."""
157 if self.logfile is None:
158 if self.logfile is None:
158 print 'Logging has not been activated.'
159 print('Logging has not been activated.')
159 else:
160 else:
160 state = self.log_active and 'active' or 'temporarily suspended'
161 state = self.log_active and 'active' or 'temporarily suspended'
161 print 'Filename :',self.logfname
162 print('Filename :', self.logfname)
162 print 'Mode :',self.logmode
163 print('Mode :', self.logmode)
163 print 'Output logging :',self.log_output
164 print('Output logging :', self.log_output)
164 print 'Raw input log :',self.log_raw_input
165 print('Raw input log :', self.log_raw_input)
165 print 'Timestamping :',self.timestamp
166 print('Timestamping :', self.timestamp)
166 print 'State :',state
167 print('State :', state)
167
168
168 def log(self, line_mod, line_ori):
169 def log(self, line_mod, line_ori):
169 """Write the sources to a log.
170 """Write the sources to a log.
@@ -213,7 +214,7 b' which already exists. But you must first start the logging process with'
213 self.logfile.close()
214 self.logfile.close()
214 self.logfile = None
215 self.logfile = None
215 else:
216 else:
216 print "Logging hadn't been started."
217 print("Logging hadn't been started.")
217 self.log_active = False
218 self.log_active = False
218
219
219 # For backwards compatibility, in case anyone was using this.
220 # For backwards compatibility, in case anyone was using this.
@@ -52,6 +52,6 b' class Macro(object):'
52 def __add__(self, other):
52 def __add__(self, other):
53 if isinstance(other, Macro):
53 if isinstance(other, Macro):
54 return Macro(self.value + other.value)
54 return Macro(self.value + other.value)
55 elif isinstance(other, basestring):
55 elif isinstance(other, py3compat.string_types):
56 return Macro(self.value + other)
56 return Macro(self.value + other)
57 raise TypeError
57 raise TypeError
@@ -1,6 +1,7 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4 from __future__ import print_function
4
5
5 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -29,6 +30,7 b' from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2'
29 from IPython.external.decorator import decorator
30 from IPython.external.decorator import decorator
30 from IPython.utils.ipstruct import Struct
31 from IPython.utils.ipstruct import Struct
31 from IPython.utils.process import arg_split
32 from IPython.utils.process import arg_split
33 from IPython.utils.py3compat import string_types, iteritems
32 from IPython.utils.text import dedent
34 from IPython.utils.text import dedent
33 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
35 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
34 from IPython.utils.warn import error
36 from IPython.utils.warn import error
@@ -193,14 +195,14 b' def _method_magic_marker(magic_kind):'
193 if callable(arg):
195 if callable(arg):
194 # "Naked" decorator call (just @foo, no args)
196 # "Naked" decorator call (just @foo, no args)
195 func = arg
197 func = arg
196 name = func.func_name
198 name = func.__name__
197 retval = decorator(call, func)
199 retval = decorator(call, func)
198 record_magic(magics, magic_kind, name, name)
200 record_magic(magics, magic_kind, name, name)
199 elif isinstance(arg, basestring):
201 elif isinstance(arg, string_types):
200 # Decorator called with arguments (@foo('bar'))
202 # Decorator called with arguments (@foo('bar'))
201 name = arg
203 name = arg
202 def mark(func, *a, **kw):
204 def mark(func, *a, **kw):
203 record_magic(magics, magic_kind, name, func.func_name)
205 record_magic(magics, magic_kind, name, func.__name__)
204 return decorator(call, func)
206 return decorator(call, func)
205 retval = mark
207 retval = mark
206 else:
208 else:
@@ -238,10 +240,10 b' def _function_magic_marker(magic_kind):'
238 if callable(arg):
240 if callable(arg):
239 # "Naked" decorator call (just @foo, no args)
241 # "Naked" decorator call (just @foo, no args)
240 func = arg
242 func = arg
241 name = func.func_name
243 name = func.__name__
242 ip.register_magic_function(func, magic_kind, name)
244 ip.register_magic_function(func, magic_kind, name)
243 retval = decorator(call, func)
245 retval = decorator(call, func)
244 elif isinstance(arg, basestring):
246 elif isinstance(arg, string_types):
245 # Decorator called with arguments (@foo('bar'))
247 # Decorator called with arguments (@foo('bar'))
246 name = arg
248 name = arg
247 def mark(func, *a, **kw):
249 def mark(func, *a, **kw):
@@ -347,7 +349,7 b' class MagicsManager(Configurable):'
347 docs = {}
349 docs = {}
348 for m_type in self.magics:
350 for m_type in self.magics:
349 m_docs = {}
351 m_docs = {}
350 for m_name, m_func in self.magics[m_type].iteritems():
352 for m_name, m_func in iteritems(self.magics[m_type]):
351 if m_func.__doc__:
353 if m_func.__doc__:
352 if brief:
354 if brief:
353 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
355 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
@@ -424,7 +426,7 b' class MagicsManager(Configurable):'
424 # Create the new method in the user_magics and register it in the
426 # Create the new method in the user_magics and register it in the
425 # global table
427 # global table
426 validate_type(magic_kind)
428 validate_type(magic_kind)
427 magic_name = func.func_name if magic_name is None else magic_name
429 magic_name = func.__name__ if magic_name is None else magic_name
428 setattr(self.user_magics, magic_name, func)
430 setattr(self.user_magics, magic_name, func)
429 record_magic(self.magics, magic_kind, magic_name, func)
431 record_magic(self.magics, magic_kind, magic_name, func)
430
432
@@ -531,8 +533,8 b' class Magics(Configurable):'
531 for mtype in magic_kinds:
533 for mtype in magic_kinds:
532 tab = self.magics[mtype] = {}
534 tab = self.magics[mtype] = {}
533 cls_tab = class_magics[mtype]
535 cls_tab = class_magics[mtype]
534 for magic_name, meth_name in cls_tab.iteritems():
536 for magic_name, meth_name in iteritems(cls_tab):
535 if isinstance(meth_name, basestring):
537 if isinstance(meth_name, string_types):
536 # it's a method name, grab it
538 # it's a method name, grab it
537 tab[magic_name] = getattr(self, meth_name)
539 tab[magic_name] = getattr(self, meth_name)
538 else:
540 else:
@@ -544,8 +546,8 b' class Magics(Configurable):'
544
546
545 def arg_err(self,func):
547 def arg_err(self,func):
546 """Print docstring if incorrect arguments were passed"""
548 """Print docstring if incorrect arguments were passed"""
547 print 'Error in arguments:'
549 print('Error in arguments:')
548 print oinspect.getdoc(func)
550 print(oinspect.getdoc(func))
549
551
550 def format_latex(self, strng):
552 def format_latex(self, strng):
551 """Format a string for latex inclusion."""
553 """Format a string for latex inclusion."""
@@ -1,5 +1,6 b''
1 """Implementation of magic functions that control various automatic behaviors.
1 """Implementation of magic functions that control various automatic behaviors.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -57,7 +58,7 b' class AutoMagics(Magics):'
57 else:
58 else:
58 val = not mman.auto_magic
59 val = not mman.auto_magic
59 mman.auto_magic = val
60 mman.auto_magic = val
60 print '\n' + self.shell.magics_manager.auto_status()
61 print('\n' + self.shell.magics_manager.auto_status())
61
62
62 @skip_doctest
63 @skip_doctest
63 @line_magic
64 @line_magic
@@ -125,4 +126,4 b' class AutoMagics(Magics):'
125 except AttributeError:
126 except AttributeError:
126 self.shell.autocall = self._magic_state.autocall_save = 1
127 self.shell.autocall = self._magic_state.autocall_save = 1
127
128
128 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
129 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
@@ -27,6 +27,7 b' from IPython.utils.text import format_screen, dedent, indent'
27 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils.ipstruct import Struct
28 from IPython.utils.ipstruct import Struct
29 from IPython.utils.path import unquote_filename
29 from IPython.utils.path import unquote_filename
30 from IPython.utils.py3compat import unicode_type
30 from IPython.utils.warn import warn, error
31 from IPython.utils.warn import warn, error
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
@@ -71,7 +72,7 b' class MagicsDisplay(object):'
71 magic_dict[key] = d
72 magic_dict[key] = d
72 for name, obj in subdict.items():
73 for name, obj in subdict.items():
73 try:
74 try:
74 classname = obj.im_class.__name__
75 classname = obj.__self__.__class__.__name__
75 except AttributeError:
76 except AttributeError:
76 classname = 'Other'
77 classname = 'Other'
77
78
@@ -599,7 +600,7 b' Defaulting color scheme to \'NoColor\'"""'
599 'format. The filename argument gives the name of the source file.'
600 'format. The filename argument gives the name of the source file.'
600 )
601 )
601 @magic_arguments.argument(
602 @magic_arguments.argument(
602 'filename', type=unicode,
603 'filename', type=unicode_type,
603 help='Notebook name or filename'
604 help='Notebook name or filename'
604 )
605 )
605 @line_magic
606 @line_magic
@@ -1,5 +1,6 b''
1 """Implementation of code management magic functions.
1 """Implementation of code management magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -28,6 +29,7 b' from IPython.core.magic import Magics, magics_class, line_magic'
28 from IPython.core.oinspect import find_file, find_source_lines
29 from IPython.core.oinspect import find_file, find_source_lines
29 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 from IPython.utils.py3compat import string_types
31 from IPython.utils.contexts import preserve_keys
33 from IPython.utils.contexts import preserve_keys
32 from IPython.utils.path import get_py_filename, unquote_filename
34 from IPython.utils.path import get_py_filename, unquote_filename
33 from IPython.utils.warn import warn, error
35 from IPython.utils.warn import warn, error
@@ -189,15 +191,15 b' class CodeMagics(Magics):'
189 try:
191 try:
190 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
192 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
191 except StdinNotImplementedError:
193 except StdinNotImplementedError:
192 print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)
194 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
193 return
195 return
194 if not overwrite :
196 if not overwrite :
195 print 'Operation cancelled.'
197 print('Operation cancelled.')
196 return
198 return
197 try:
199 try:
198 cmds = self.shell.find_user_code(codefrom,raw)
200 cmds = self.shell.find_user_code(codefrom,raw)
199 except (TypeError, ValueError) as e:
201 except (TypeError, ValueError) as e:
200 print e.args[0]
202 print(e.args[0])
201 return
203 return
202 out = py3compat.cast_unicode(cmds)
204 out = py3compat.cast_unicode(cmds)
203 with io.open(fname, mode, encoding="utf-8") as f:
205 with io.open(fname, mode, encoding="utf-8") as f:
@@ -207,8 +209,8 b' class CodeMagics(Magics):'
207 # make sure we end on a newline
209 # make sure we end on a newline
208 if not out.endswith(u'\n'):
210 if not out.endswith(u'\n'):
209 f.write(u'\n')
211 f.write(u'\n')
210 print 'The following commands were written to file `%s`:' % fname
212 print('The following commands were written to file `%s`:' % fname)
211 print cmds
213 print(cmds)
212
214
213 @line_magic
215 @line_magic
214 def pastebin(self, parameter_s=''):
216 def pastebin(self, parameter_s=''):
@@ -230,7 +232,7 b' class CodeMagics(Magics):'
230 try:
232 try:
231 code = self.shell.find_user_code(args)
233 code = self.shell.find_user_code(args)
232 except (ValueError, TypeError) as e:
234 except (ValueError, TypeError) as e:
233 print e.args[0]
235 print(e.args[0])
234 return
236 return
235
237
236 from urllib2 import urlopen # Deferred import
238 from urllib2 import urlopen # Deferred import
@@ -337,7 +339,7 b' class CodeMagics(Magics):'
337 ans = True
339 ans = True
338
340
339 if ans is False :
341 if ans is False :
340 print 'Operation cancelled.'
342 print('Operation cancelled.')
341 return
343 return
342
344
343 self.shell.set_next_input(contents)
345 self.shell.set_next_input(contents)
@@ -395,7 +397,7 b' class CodeMagics(Magics):'
395
397
396 #print '*** args',args,'type',type(args) # dbg
398 #print '*** args',args,'type',type(args) # dbg
397 data = eval(args, shell.user_ns)
399 data = eval(args, shell.user_ns)
398 if not isinstance(data, basestring):
400 if not isinstance(data, string_types):
399 raise DataIsObject
401 raise DataIsObject
400
402
401 except (NameError,SyntaxError):
403 except (NameError,SyntaxError):
@@ -459,7 +461,7 b' class CodeMagics(Magics):'
459
461
460 if use_temp:
462 if use_temp:
461 filename = shell.mktempfile(data)
463 filename = shell.mktempfile(data)
462 print 'IPython will make a temporary file named:',filename
464 print('IPython will make a temporary file named:',filename)
463
465
464 # use last_call to remember the state of the previous call, but don't
466 # use last_call to remember the state of the previous call, but don't
465 # let it be clobbered by successive '-p' calls.
467 # let it be clobbered by successive '-p' calls.
@@ -637,7 +639,7 b' class CodeMagics(Magics):'
637 self._edit_macro(args, e.args[0])
639 self._edit_macro(args, e.args[0])
638 return
640 return
639 except InteractivelyDefined as e:
641 except InteractivelyDefined as e:
640 print "Editing In[%i]" % e.index
642 print("Editing In[%i]" % e.index)
641 args = str(e.index)
643 args = str(e.index)
642 filename, lineno, is_temp = self._find_edit_target(self.shell,
644 filename, lineno, is_temp = self._find_edit_target(self.shell,
643 args, opts, last_call)
645 args, opts, last_call)
@@ -647,7 +649,7 b' class CodeMagics(Magics):'
647 return
649 return
648
650
649 # do actual editing here
651 # do actual editing here
650 print 'Editing...',
652 print('Editing...', end=' ')
651 sys.stdout.flush()
653 sys.stdout.flush()
652 try:
654 try:
653 # Quote filenames that may have spaces in them
655 # Quote filenames that may have spaces in them
@@ -665,9 +667,9 b' class CodeMagics(Magics):'
665 self.shell.user_ns['pasted_block'] = f.read()
667 self.shell.user_ns['pasted_block'] = f.read()
666
668
667 if 'x' in opts: # -x prevents actual execution
669 if 'x' in opts: # -x prevents actual execution
668 print
670 print()
669 else:
671 else:
670 print 'done. Executing edited code...'
672 print('done. Executing edited code...')
671 with preserve_keys(self.shell.user_ns, '__file__'):
673 with preserve_keys(self.shell.user_ns, '__file__'):
672 if not is_temp:
674 if not is_temp:
673 self.shell.user_ns['__file__'] = filename
675 self.shell.user_ns['__file__'] = filename
@@ -1,5 +1,6 b''
1 """Implementation of configuration-related magic functions.
1 """Implementation of configuration-related magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -116,9 +117,9 b' class ConfigMagics(Magics):'
116 line = s.strip()
117 line = s.strip()
117 if not line:
118 if not line:
118 # print available configurable names
119 # print available configurable names
119 print "Available objects for config:"
120 print("Available objects for config:")
120 for name in classnames:
121 for name in classnames:
121 print " ", name
122 print(" ", name)
122 return
123 return
123 elif line in classnames:
124 elif line in classnames:
124 # `%config TerminalInteractiveShell` will print trait info for
125 # `%config TerminalInteractiveShell` will print trait info for
@@ -128,7 +129,7 b' class ConfigMagics(Magics):'
128 help = cls.class_get_help(c)
129 help = cls.class_get_help(c)
129 # strip leading '--' from cl-args:
130 # strip leading '--' from cl-args:
130 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
131 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
131 print help
132 print(help)
132 return
133 return
133 elif reg.match(line):
134 elif reg.match(line):
134 cls, attr = line.split('.')
135 cls, attr = line.split('.')
@@ -149,7 +150,7 b' class ConfigMagics(Magics):'
149 # leave quotes on args when splitting, because we want
150 # leave quotes on args when splitting, because we want
150 # unquoted args to eval in user_ns
151 # unquoted args to eval in user_ns
151 cfg = Config()
152 cfg = Config()
152 exec "cfg."+line in locals(), self.shell.user_ns
153 exec("cfg."+line, locals(), self.shell.user_ns)
153
154
154 for configurable in configurables:
155 for configurable in configurables:
155 try:
156 try:
@@ -1,5 +1,6 b''
1 """Deprecated Magic functions.
1 """Deprecated Magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -26,20 +27,20 b' class DeprecatedMagics(Magics):'
26 @line_magic
27 @line_magic
27 def install_profiles(self, parameter_s=''):
28 def install_profiles(self, parameter_s=''):
28 """%install_profiles has been deprecated."""
29 """%install_profiles has been deprecated."""
29 print '\n'.join([
30 print('\n'.join([
30 "%install_profiles has been deprecated.",
31 "%install_profiles has been deprecated.",
31 "Use `ipython profile list` to view available profiles.",
32 "Use `ipython profile list` to view available profiles.",
32 "Requesting a profile with `ipython profile create <name>`",
33 "Requesting a profile with `ipython profile create <name>`",
33 "or `ipython --profile=<name>` will start with the bundled",
34 "or `ipython --profile=<name>` will start with the bundled",
34 "profile of that name if it exists."
35 "profile of that name if it exists."
35 ])
36 ]))
36
37
37 @line_magic
38 @line_magic
38 def install_default_config(self, parameter_s=''):
39 def install_default_config(self, parameter_s=''):
39 """%install_default_config has been deprecated."""
40 """%install_default_config has been deprecated."""
40 print '\n'.join([
41 print('\n'.join([
41 "%install_default_config has been deprecated.",
42 "%install_default_config has been deprecated.",
42 "Use `ipython profile create <name>` to initialize a profile",
43 "Use `ipython profile create <name>` to initialize a profile",
43 "with the default config files.",
44 "with the default config files.",
44 "Add `--reset` to overwrite already existing config files with defaults."
45 "Add `--reset` to overwrite already existing config files with defaults."
45 ])
46 ]))
@@ -1,6 +1,7 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions.
2 """Implementation of execution-related magic functions.
3 """
3 """
4 from __future__ import print_function
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
6 # Copyright (c) 2012 The IPython Development Team.
6 #
7 #
@@ -14,13 +15,11 b''
14 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
15
16
16 # Stdlib
17 # Stdlib
17 import __builtin__ as builtin_mod
18 import ast
18 import ast
19 import bdb
19 import bdb
20 import os
20 import os
21 import sys
21 import sys
22 import time
22 import time
23 from StringIO import StringIO
24
23
25 # cProfile was added in Python2.5
24 # cProfile was added in Python2.5
26 try:
25 try:
@@ -43,6 +42,7 b' from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,'
43 line_cell_magic, on_off, needs_local_scope)
42 line_cell_magic, on_off, needs_local_scope)
44 from IPython.testing.skipdoctest import skip_doctest
43 from IPython.testing.skipdoctest import skip_doctest
45 from IPython.utils import py3compat
44 from IPython.utils import py3compat
45 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
46 from IPython.utils.contexts import preserve_keys
46 from IPython.utils.contexts import preserve_keys
47 from IPython.utils.io import capture_output
47 from IPython.utils.io import capture_output
48 from IPython.utils.ipstruct import Struct
48 from IPython.utils.ipstruct import Struct
@@ -51,6 +51,10 b' from IPython.utils.path import get_py_filename, unquote_filename, shellglob'
51 from IPython.utils.timing import clock, clock2
51 from IPython.utils.timing import clock, clock2
52 from IPython.utils.warn import warn, error
52 from IPython.utils.warn import warn, error
53
53
54 if PY3:
55 from io import StringIO
56 else:
57 from StringIO import StringIO
54
58
55 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
56 # Magic implementation classes
60 # Magic implementation classes
@@ -85,6 +89,29 b' class TimeitResult(object):'
85 p.text(u'<TimeitResult : '+unic+u'>')
89 p.text(u'<TimeitResult : '+unic+u'>')
86
90
87
91
92 class TimeitTemplateFiller(ast.NodeTransformer):
93 """Fill in the AST template for timing execution.
94
95 This is quite closely tied to the template definition, which is in
96 :meth:`ExecutionMagics.timeit`.
97 """
98 def __init__(self, ast_setup, ast_stmt):
99 self.ast_setup = ast_setup
100 self.ast_stmt = ast_stmt
101
102 def visit_FunctionDef(self, node):
103 "Fill in the setup statement"
104 self.generic_visit(node)
105 if node.name == "inner":
106 node.body[:1] = self.ast_setup.body
107
108 return node
109
110 def visit_For(self, node):
111 "Fill in the statement to be timed"
112 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
113 node.body = self.ast_stmt.body
114 return node
88
115
89
116
90 @magics_class
117 @magics_class
@@ -277,22 +304,22 b' python-profiler package from non-free.""")'
277
304
278 if 'q' not in opts:
305 if 'q' not in opts:
279 page.page(output)
306 page.page(output)
280 print sys_exit,
307 print(sys_exit, end=' ')
281
308
282 dump_file = opts.D[0]
309 dump_file = opts.D[0]
283 text_file = opts.T[0]
310 text_file = opts.T[0]
284 if dump_file:
311 if dump_file:
285 dump_file = unquote_filename(dump_file)
312 dump_file = unquote_filename(dump_file)
286 prof.dump_stats(dump_file)
313 prof.dump_stats(dump_file)
287 print '\n*** Profile stats marshalled to file',\
314 print('\n*** Profile stats marshalled to file',\
288 repr(dump_file)+'.',sys_exit
315 repr(dump_file)+'.',sys_exit)
289 if text_file:
316 if text_file:
290 text_file = unquote_filename(text_file)
317 text_file = unquote_filename(text_file)
291 pfile = open(text_file,'w')
318 pfile = open(text_file,'w')
292 pfile.write(output)
319 pfile.write(output)
293 pfile.close()
320 pfile.close()
294 print '\n*** Profile printout saved to text file',\
321 print('\n*** Profile printout saved to text file',\
295 repr(text_file)+'.',sys_exit
322 repr(text_file)+'.',sys_exit)
296
323
297 if 'r' in opts:
324 if 'r' in opts:
298 return stats
325 return stats
@@ -332,7 +359,7 b' python-profiler package from non-free.""")'
332
359
333 # set on the shell
360 # set on the shell
334 self.shell.call_pdb = new_pdb
361 self.shell.call_pdb = new_pdb
335 print 'Automatic pdb calling has been turned',on_off(new_pdb)
362 print('Automatic pdb calling has been turned',on_off(new_pdb))
336
363
337 @skip_doctest
364 @skip_doctest
338 @magic_arguments.magic_arguments()
365 @magic_arguments.magic_arguments()
@@ -558,7 +585,7 b' python-profiler package from non-free.""")'
558 filename = file_finder(arg_lst[0])
585 filename = file_finder(arg_lst[0])
559 except IndexError:
586 except IndexError:
560 warn('you must provide at least a filename.')
587 warn('you must provide at least a filename.')
561 print '\n%run:\n', oinspect.getdoc(self.run)
588 print('\n%run:\n', oinspect.getdoc(self.run))
562 return
589 return
563 except IOError as e:
590 except IOError as e:
564 try:
591 try:
@@ -775,7 +802,7 b' python-profiler package from non-free.""")'
775 deb.mainpyfile = deb.canonic(filename)
802 deb.mainpyfile = deb.canonic(filename)
776
803
777 # Start file run
804 # Start file run
778 print "NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt
805 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
779 try:
806 try:
780 if filename:
807 if filename:
781 # save filename so it can be used by methods on the deb object
808 # save filename so it can be used by methods on the deb object
@@ -809,9 +836,9 b' python-profiler package from non-free.""")'
809 t1 = clock2()
836 t1 = clock2()
810 t_usr = t1[0] - t0[0]
837 t_usr = t1[0] - t0[0]
811 t_sys = t1[1] - t0[1]
838 t_sys = t1[1] - t0[1]
812 print "\nIPython CPU timings (estimated):"
839 print("\nIPython CPU timings (estimated):")
813 print " User : %10.2f s." % t_usr
840 print(" User : %10.2f s." % t_usr)
814 print " System : %10.2f s." % t_sys
841 print(" System : %10.2f s." % t_sys)
815 else:
842 else:
816 runs = range(nruns)
843 runs = range(nruns)
817 t0 = clock2()
844 t0 = clock2()
@@ -820,13 +847,13 b' python-profiler package from non-free.""")'
820 t1 = clock2()
847 t1 = clock2()
821 t_usr = t1[0] - t0[0]
848 t_usr = t1[0] - t0[0]
822 t_sys = t1[1] - t0[1]
849 t_sys = t1[1] - t0[1]
823 print "\nIPython CPU timings (estimated):"
850 print("\nIPython CPU timings (estimated):")
824 print "Total runs performed:", nruns
851 print("Total runs performed:", nruns)
825 print " Times : %10s %10s" % ('Total', 'Per run')
852 print(" Times : %10s %10s" % ('Total', 'Per run'))
826 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
853 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
827 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
854 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
828 twall1 = time.time()
855 twall1 = time.time()
829 print "Wall time: %10.2f s." % (twall1 - twall0)
856 print("Wall time: %10.2f s." % (twall1 - twall0))
830
857
831 @skip_doctest
858 @skip_doctest
832 @line_cell_magic
859 @line_cell_magic
@@ -948,23 +975,7 b' python-profiler package from non-free.""")'
948 ' _t1 = _timer()\n'
975 ' _t1 = _timer()\n'
949 ' return _t1 - _t0\n')
976 ' return _t1 - _t0\n')
950
977
951 class TimeitTemplateFiller(ast.NodeTransformer):
978 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
952 "This is quite tightly tied to the template definition above."
953 def visit_FunctionDef(self, node):
954 "Fill in the setup statement"
955 self.generic_visit(node)
956 if node.name == "inner":
957 node.body[:1] = ast_setup.body
958
959 return node
960
961 def visit_For(self, node):
962 "Fill in the statement to be timed"
963 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
964 node.body = ast_stmt.body
965 return node
966
967 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
968 timeit_ast = ast.fix_missing_locations(timeit_ast)
979 timeit_ast = ast.fix_missing_locations(timeit_ast)
969
980
970 # Track compilation time so it can be reported if too long
981 # Track compilation time so it can be reported if too long
@@ -976,7 +987,7 b' python-profiler package from non-free.""")'
976 tc = clock()-t0
987 tc = clock()-t0
977
988
978 ns = {}
989 ns = {}
979 exec code in self.shell.user_ns, ns
990 exec(code, self.shell.user_ns, ns)
980 timer.inner = ns["inner"]
991 timer.inner = ns["inner"]
981
992
982 if number == 0:
993 if number == 0:
@@ -989,10 +1000,10 b' python-profiler package from non-free.""")'
989 all_runs = timer.repeat(repeat, number)
1000 all_runs = timer.repeat(repeat, number)
990 best = min(all_runs) / number
1001 best = min(all_runs) / number
991 if not quiet :
1002 if not quiet :
992 print u"%d loops, best of %d: %s per loop" % (number, repeat,
1003 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
993 _format_time(best, precision))
1004 _format_time(best, precision)))
994 if tc > tc_min:
1005 if tc > tc_min:
995 print "Compiler time: %.2f s" % tc
1006 print("Compiler time: %.2f s" % tc)
996 if return_result:
1007 if return_result:
997 return TimeitResult(number, repeat, best, all_runs, tc, precision)
1008 return TimeitResult(number, repeat, best, all_runs, tc, precision)
998
1009
@@ -1099,7 +1110,7 b' python-profiler package from non-free.""")'
1099 end = clock2()
1110 end = clock2()
1100 else:
1111 else:
1101 st = clock2()
1112 st = clock2()
1102 exec code in glob, local_ns
1113 exec(code, glob, local_ns)
1103 end = clock2()
1114 end = clock2()
1104 out = None
1115 out = None
1105 wall_end = wtime()
1116 wall_end = wtime()
@@ -1110,13 +1121,13 b' python-profiler package from non-free.""")'
1110 cpu_tot = cpu_user+cpu_sys
1121 cpu_tot = cpu_user+cpu_sys
1111 # On windows cpu_sys is always zero, so no new information to the next print
1122 # On windows cpu_sys is always zero, so no new information to the next print
1112 if sys.platform != 'win32':
1123 if sys.platform != 'win32':
1113 print "CPU times: user %s, sys: %s, total: %s" % \
1124 print("CPU times: user %s, sys: %s, total: %s" % \
1114 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))
1125 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1115 print "Wall time: %s" % _format_time(wall_time)
1126 print("Wall time: %s" % _format_time(wall_time))
1116 if tc > tc_min:
1127 if tc > tc_min:
1117 print "Compiler : %s" % _format_time(tc)
1128 print("Compiler : %s" % _format_time(tc))
1118 if tp > tp_min:
1129 if tp > tp_min:
1119 print "Parser : %s" % _format_time(tp)
1130 print("Parser : %s" % _format_time(tp))
1120 return out
1131 return out
1121
1132
1122 @skip_doctest
1133 @skip_doctest
@@ -1184,7 +1195,7 b' python-profiler package from non-free.""")'
1184 """
1195 """
1185 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1196 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1186 if not args: # List existing macros
1197 if not args: # List existing macros
1187 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1198 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1188 isinstance(v, Macro))
1199 isinstance(v, Macro))
1189 if len(args) == 1:
1200 if len(args) == 1:
1190 raise UsageError(
1201 raise UsageError(
@@ -1195,14 +1206,14 b' python-profiler package from non-free.""")'
1195 try:
1206 try:
1196 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1207 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1197 except (ValueError, TypeError) as e:
1208 except (ValueError, TypeError) as e:
1198 print e.args[0]
1209 print(e.args[0])
1199 return
1210 return
1200 macro = Macro(lines)
1211 macro = Macro(lines)
1201 self.shell.define_macro(name, macro)
1212 self.shell.define_macro(name, macro)
1202 if not ( 'q' in opts) :
1213 if not ( 'q' in opts) :
1203 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1214 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1204 print '=== Macro contents: ==='
1215 print('=== Macro contents: ===')
1205 print macro,
1216 print(macro, end=' ')
1206
1217
1207 @magic_arguments.magic_arguments()
1218 @magic_arguments.magic_arguments()
1208 @magic_arguments.argument('output', type=str, default='', nargs='?',
1219 @magic_arguments.argument('output', type=str, default='', nargs='?',
@@ -1,5 +1,6 b''
1 """Implementation of magic functions for the extension machinery.
1 """Implementation of magic functions for the extension machinery.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -46,12 +47,12 b' class ExtensionMagics(Magics):'
46 filename = self.shell.extension_manager.install_extension(args,
47 filename = self.shell.extension_manager.install_extension(args,
47 opts.get('n'))
48 opts.get('n'))
48 except ValueError as e:
49 except ValueError as e:
49 print e
50 print(e)
50 return
51 return
51
52
52 filename = os.path.basename(filename)
53 filename = os.path.basename(filename)
53 print "Installed %s. To use it, type:" % filename
54 print("Installed %s. To use it, type:" % filename)
54 print " %%load_ext %s" % os.path.splitext(filename)[0]
55 print(" %%load_ext %s" % os.path.splitext(filename)[0])
55
56
56
57
57 @line_magic
58 @line_magic
@@ -62,10 +63,10 b' class ExtensionMagics(Magics):'
62 res = self.shell.extension_manager.load_extension(module_str)
63 res = self.shell.extension_manager.load_extension(module_str)
63
64
64 if res == 'already loaded':
65 if res == 'already loaded':
65 print "The %s extension is already loaded. To reload it, use:" % module_str
66 print("The %s extension is already loaded. To reload it, use:" % module_str)
66 print " %reload_ext", module_str
67 print(" %reload_ext", module_str)
67 elif res == 'no load function':
68 elif res == 'no load function':
68 print "The %s module is not an IPython extension." % module_str
69 print("The %s module is not an IPython extension." % module_str)
69
70
70 @line_magic
71 @line_magic
71 def unload_ext(self, module_str):
72 def unload_ext(self, module_str):
@@ -80,9 +81,9 b' class ExtensionMagics(Magics):'
80 res = self.shell.extension_manager.unload_extension(module_str)
81 res = self.shell.extension_manager.unload_extension(module_str)
81
82
82 if res == 'no unload function':
83 if res == 'no unload function':
83 print "The %s extension doesn't define how to unload it." % module_str
84 print("The %s extension doesn't define how to unload it." % module_str)
84 elif res == "not loaded":
85 elif res == "not loaded":
85 print "The %s extension is not loaded." % module_str
86 print("The %s extension is not loaded." % module_str)
86
87
87 @line_magic
88 @line_magic
88 def reload_ext(self, module_str):
89 def reload_ext(self, module_str):
@@ -1,5 +1,6 b''
1 """Implementation of namespace-related magic functions.
1 """Implementation of namespace-related magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -25,6 +26,7 b' from IPython.testing.skipdoctest import skip_doctest'
25 from IPython.utils.encoding import DEFAULT_ENCODING
26 from IPython.utils.encoding import DEFAULT_ENCODING
26 from IPython.utils.openpy import read_py_file
27 from IPython.utils.openpy import read_py_file
27 from IPython.utils.path import get_py_filename
28 from IPython.utils.path import get_py_filename
29 from IPython.utils.py3compat import unicode_type
28
30
29 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
30 # Magic implementation classes
32 # Magic implementation classes
@@ -117,7 +119,7 b' class NamespaceMagics(Magics):'
117 try:
119 try:
118 filename = get_py_filename(parameter_s)
120 filename = get_py_filename(parameter_s)
119 except IOError as msg:
121 except IOError as msg:
120 print msg
122 print(msg)
121 return
123 return
122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
124 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123
125
@@ -204,7 +206,7 b' class NamespaceMagics(Magics):'
204 try:
206 try:
205 parameter_s.encode('ascii')
207 parameter_s.encode('ascii')
206 except UnicodeEncodeError:
208 except UnicodeEncodeError:
207 print 'Python identifiers can only contain ascii characters.'
209 print('Python identifiers can only contain ascii characters.')
208 return
210 return
209
211
210 # default namespaces to be searched
212 # default namespaces to be searched
@@ -327,20 +329,20 b' class NamespaceMagics(Magics):'
327 varlist = self.who_ls(parameter_s)
329 varlist = self.who_ls(parameter_s)
328 if not varlist:
330 if not varlist:
329 if parameter_s:
331 if parameter_s:
330 print 'No variables match your requested type.'
332 print('No variables match your requested type.')
331 else:
333 else:
332 print 'Interactive namespace is empty.'
334 print('Interactive namespace is empty.')
333 return
335 return
334
336
335 # if we have variables, move on...
337 # if we have variables, move on...
336 count = 0
338 count = 0
337 for i in varlist:
339 for i in varlist:
338 print i+'\t',
340 print(i+'\t', end=' ')
339 count += 1
341 count += 1
340 if count > 8:
342 if count > 8:
341 count = 0
343 count = 0
342 print
344 print()
343 print
345 print()
344
346
345 @skip_doctest
347 @skip_doctest
346 @line_magic
348 @line_magic
@@ -378,9 +380,9 b' class NamespaceMagics(Magics):'
378 varnames = self.who_ls(parameter_s)
380 varnames = self.who_ls(parameter_s)
379 if not varnames:
381 if not varnames:
380 if parameter_s:
382 if parameter_s:
381 print 'No variables match your requested type.'
383 print('No variables match your requested type.')
382 else:
384 else:
383 print 'Interactive namespace is empty.'
385 print('Interactive namespace is empty.')
384 return
386 return
385
387
386 # if we have variables, move on...
388 # if we have variables, move on...
@@ -399,8 +401,6 b' class NamespaceMagics(Magics):'
399 ndarray_type = ndarray.__name__
401 ndarray_type = ndarray.__name__
400
402
401 # Find all variable names and types so we can figure out column sizes
403 # Find all variable names and types so we can figure out column sizes
402 def get_vars(i):
403 return self.shell.user_ns[i]
404
404
405 # some types are well known and can be shorter
405 # some types are well known and can be shorter
406 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
406 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
@@ -408,7 +408,7 b' class NamespaceMagics(Magics):'
408 tn = type(v).__name__
408 tn = type(v).__name__
409 return abbrevs.get(tn,tn)
409 return abbrevs.get(tn,tn)
410
410
411 varlist = map(get_vars,varnames)
411 varlist = [self.shell.user_ns[n] for n in varnames]
412
412
413 typelist = []
413 typelist = []
414 for vv in varlist:
414 for vv in varlist:
@@ -432,15 +432,15 b' class NamespaceMagics(Magics):'
432 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
432 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
433 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
433 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
434 # table header
434 # table header
435 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
435 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
436 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
436 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
437 # and the table itself
437 # and the table itself
438 kb = 1024
438 kb = 1024
439 Mb = 1048576 # kb**2
439 Mb = 1048576 # kb**2
440 for vname,var,vtype in zip(varnames,varlist,typelist):
440 for vname,var,vtype in zip(varnames,varlist,typelist):
441 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
441 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
442 if vtype in seq_types:
442 if vtype in seq_types:
443 print "n="+str(len(var))
443 print("n="+str(len(var)))
444 elif vtype == ndarray_type:
444 elif vtype == ndarray_type:
445 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
445 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
446 if vtype==ndarray_type:
446 if vtype==ndarray_type:
@@ -450,26 +450,26 b' class NamespaceMagics(Magics):'
450 vdtype = var.dtype
450 vdtype = var.dtype
451
451
452 if vbytes < 100000:
452 if vbytes < 100000:
453 print aformat % (vshape, vsize, vdtype, vbytes)
453 print(aformat % (vshape, vsize, vdtype, vbytes))
454 else:
454 else:
455 print aformat % (vshape, vsize, vdtype, vbytes),
455 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
456 if vbytes < Mb:
456 if vbytes < Mb:
457 print '(%s kb)' % (vbytes/kb,)
457 print('(%s kb)' % (vbytes/kb,))
458 else:
458 else:
459 print '(%s Mb)' % (vbytes/Mb,)
459 print('(%s Mb)' % (vbytes/Mb,))
460 else:
460 else:
461 try:
461 try:
462 vstr = str(var)
462 vstr = str(var)
463 except UnicodeEncodeError:
463 except UnicodeEncodeError:
464 vstr = unicode(var).encode(DEFAULT_ENCODING,
464 vstr = unicode_type(var).encode(DEFAULT_ENCODING,
465 'backslashreplace')
465 'backslashreplace')
466 except:
466 except:
467 vstr = "<object with id %d (str() failed)>" % id(var)
467 vstr = "<object with id %d (str() failed)>" % id(var)
468 vstr = vstr.replace('\n', '\\n')
468 vstr = vstr.replace('\n', '\\n')
469 if len(vstr) < 50:
469 if len(vstr) < 50:
470 print vstr
470 print(vstr)
471 else:
471 else:
472 print vstr[:25] + "<...>" + vstr[-25:]
472 print(vstr[:25] + "<...>" + vstr[-25:])
473
473
474 @line_magic
474 @line_magic
475 def reset(self, parameter_s=''):
475 def reset(self, parameter_s=''):
@@ -540,7 +540,7 b' class NamespaceMagics(Magics):'
540 except StdinNotImplementedError:
540 except StdinNotImplementedError:
541 ans = True
541 ans = True
542 if not ans:
542 if not ans:
543 print 'Nothing done.'
543 print('Nothing done.')
544 return
544 return
545
545
546 if 's' in opts: # Soft reset
546 if 's' in opts: # Soft reset
@@ -557,11 +557,11 b' class NamespaceMagics(Magics):'
557 for target in args:
557 for target in args:
558 target = target.lower() # make matches case insensitive
558 target = target.lower() # make matches case insensitive
559 if target == 'out':
559 if target == 'out':
560 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
560 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
561 self.shell.displayhook.flush()
561 self.shell.displayhook.flush()
562
562
563 elif target == 'in':
563 elif target == 'in':
564 print "Flushing input history"
564 print("Flushing input history")
565 pc = self.shell.displayhook.prompt_count + 1
565 pc = self.shell.displayhook.prompt_count + 1
566 for n in range(1, pc):
566 for n in range(1, pc):
567 key = '_i'+repr(n)
567 key = '_i'+repr(n)
@@ -581,19 +581,19 b' class NamespaceMagics(Magics):'
581 from numpy import ndarray
581 from numpy import ndarray
582 # This must be done with items and not iteritems because
582 # This must be done with items and not iteritems because
583 # we're going to modify the dict in-place.
583 # we're going to modify the dict in-place.
584 for x,val in user_ns.items():
584 for x,val in list(user_ns.items()):
585 if isinstance(val,ndarray):
585 if isinstance(val,ndarray):
586 del user_ns[x]
586 del user_ns[x]
587 except ImportError:
587 except ImportError:
588 print "reset array only works if Numpy is available."
588 print("reset array only works if Numpy is available.")
589
589
590 elif target == 'dhist':
590 elif target == 'dhist':
591 print "Flushing directory history"
591 print("Flushing directory history")
592 del user_ns['_dh'][:]
592 del user_ns['_dh'][:]
593
593
594 else:
594 else:
595 print "Don't know how to reset ",
595 print("Don't know how to reset ", end=' ')
596 print target + ", please run `%reset?` for details"
596 print(target + ", please run `%reset?` for details")
597
597
598 gc.collect()
598 gc.collect()
599
599
@@ -670,11 +670,11 b' class NamespaceMagics(Magics):'
670 except StdinNotImplementedError:
670 except StdinNotImplementedError:
671 ans = True
671 ans = True
672 if not ans:
672 if not ans:
673 print 'Nothing done.'
673 print('Nothing done.')
674 return
674 return
675 user_ns = self.shell.user_ns
675 user_ns = self.shell.user_ns
676 if not regex:
676 if not regex:
677 print 'No regex pattern specified. Nothing done.'
677 print('No regex pattern specified. Nothing done.')
678 return
678 return
679 else:
679 else:
680 try:
680 try:
@@ -701,4 +701,4 b' class NamespaceMagics(Magics):'
701 try:
701 try:
702 self.shell.del_var(varname, ('n' in opts))
702 self.shell.del_var(varname, ('n' in opts))
703 except (NameError, ValueError) as e:
703 except (NameError, ValueError) as e:
704 print type(e).__name__ +": "+ str(e)
704 print(type(e).__name__ +": "+ str(e))
@@ -3,6 +3,7 b''
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 builtin.
4 builtin.
5 """
5 """
6 from __future__ import print_function
6 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
7 # Copyright (c) 2012 The IPython Development Team.
8 # Copyright (c) 2012 The IPython Development Team.
8 #
9 #
@@ -35,6 +36,7 b' from IPython.testing.skipdoctest import skip_doctest'
35 from IPython.utils.openpy import source_to_unicode
36 from IPython.utils.openpy import source_to_unicode
36 from IPython.utils.path import unquote_filename
37 from IPython.utils.path import unquote_filename
37 from IPython.utils.process import abbrev_cwd
38 from IPython.utils.process import abbrev_cwd
39 from IPython.utils.py3compat import unicode_type
38 from IPython.utils.terminal import set_term_title
40 from IPython.utils.terminal import set_term_title
39
41
40 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
@@ -107,7 +109,7 b' class OSMagics(Magics):'
107 # for k, v in stored:
109 # for k, v in stored:
108 # atab.append(k, v[0])
110 # atab.append(k, v[0])
109
111
110 print "Total number of aliases:", len(aliases)
112 print("Total number of aliases:", len(aliases))
111 sys.stdout.flush()
113 sys.stdout.flush()
112 return aliases
114 return aliases
113
115
@@ -137,7 +139,7 b' class OSMagics(Magics):'
137
139
138 stored = self.shell.db.get('stored_aliases', {} )
140 stored = self.shell.db.get('stored_aliases', {} )
139 if aname in stored:
141 if aname in stored:
140 print "Removing %stored alias",aname
142 print("Removing %stored alias",aname)
141 del stored[aname]
143 del stored[aname]
142 self.shell.db['stored_aliases'] = stored
144 self.shell.db['stored_aliases'] = stored
143
145
@@ -284,7 +286,7 b' class OSMagics(Magics):'
284 try:
286 try:
285 ps = self.shell.user_ns['_dh'][nn]
287 ps = self.shell.user_ns['_dh'][nn]
286 except IndexError:
288 except IndexError:
287 print 'The requested directory does not exist in history.'
289 print('The requested directory does not exist in history.')
288 return
290 return
289 else:
291 else:
290 opts = {}
292 opts = {}
@@ -307,7 +309,7 b' class OSMagics(Magics):'
307 ps = fallback
309 ps = fallback
308
310
309 if ps is None:
311 if ps is None:
310 print "No matching entry in directory history"
312 print("No matching entry in directory history")
311 return
313 return
312 else:
314 else:
313 opts = {}
315 opts = {}
@@ -331,7 +333,7 b' class OSMagics(Magics):'
331
333
332 if ps in bkms:
334 if ps in bkms:
333 target = bkms[ps]
335 target = bkms[ps]
334 print '(bookmark:%s) -> %s' % (ps, target)
336 print('(bookmark:%s) -> %s' % (ps, target))
335 ps = target
337 ps = target
336 else:
338 else:
337 if 'b' in opts:
339 if 'b' in opts:
@@ -347,7 +349,7 b' class OSMagics(Magics):'
347 if hasattr(self.shell, 'term_title') and self.shell.term_title:
349 if hasattr(self.shell, 'term_title') and self.shell.term_title:
348 set_term_title('IPython: ' + abbrev_cwd())
350 set_term_title('IPython: ' + abbrev_cwd())
349 except OSError:
351 except OSError:
350 print sys.exc_info()[1]
352 print(sys.exc_info()[1])
351 else:
353 else:
352 cwd = os.getcwdu()
354 cwd = os.getcwdu()
353 dhist = self.shell.user_ns['_dh']
355 dhist = self.shell.user_ns['_dh']
@@ -366,7 +368,7 b' class OSMagics(Magics):'
366 dhist.append(cwd)
368 dhist.append(cwd)
367 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
369 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
368 if not 'q' in opts and self.shell.user_ns['_dh']:
370 if not 'q' in opts and self.shell.user_ns['_dh']:
369 print self.shell.user_ns['_dh'][-1]
371 print(self.shell.user_ns['_dh'][-1])
370
372
371
373
372 @line_magic
374 @line_magic
@@ -399,7 +401,7 b' class OSMagics(Magics):'
399 raise UsageError("%popd on empty stack")
401 raise UsageError("%popd on empty stack")
400 top = self.shell.dir_stack.pop(0)
402 top = self.shell.dir_stack.pop(0)
401 self.cd(top)
403 self.cd(top)
402 print "popd ->",top
404 print("popd ->",top)
403
405
404 @line_magic
406 @line_magic
405 def dirs(self, parameter_s=''):
407 def dirs(self, parameter_s=''):
@@ -441,9 +443,9 b' class OSMagics(Magics):'
441 return
443 return
442 else:
444 else:
443 ini,fin = 0,len(dh)
445 ini,fin = 0,len(dh)
444 print 'Directory history (kept in _dh)'
446 print('Directory history (kept in _dh)')
445 for i in range(ini, fin):
447 for i in range(ini, fin):
446 print "%d: %s" % (i, dh[i])
448 print("%d: %s" % (i, dh[i]))
447
449
448 @skip_doctest
450 @skip_doctest
449 @line_magic
451 @line_magic
@@ -555,7 +557,7 b' class OSMagics(Magics):'
555 split = 'l' in opts
557 split = 'l' in opts
556 out = self.shell.getoutput(cmd, split=split)
558 out = self.shell.getoutput(cmd, split=split)
557 if 'v' in opts:
559 if 'v' in opts:
558 print '%s ==\n%s' % (var, pformat(out))
560 print('%s ==\n%s' % (var, pformat(out)))
559 if var:
561 if var:
560 self.shell.user_ns.update({var:out})
562 self.shell.user_ns.update({var:out})
561 else:
563 else:
@@ -667,9 +669,9 b' class OSMagics(Magics):'
667 else:
669 else:
668 size = 0
670 size = 0
669 fmt = '%-'+str(size)+'s -> %s'
671 fmt = '%-'+str(size)+'s -> %s'
670 print 'Current bookmarks:'
672 print('Current bookmarks:')
671 for bk in bks:
673 for bk in bks:
672 print fmt % (bk, bkms[bk])
674 print(fmt % (bk, bkms[bk]))
673 else:
675 else:
674 if not args:
676 if not args:
675 raise UsageError("%bookmark: You must specify the bookmark name")
677 raise UsageError("%bookmark: You must specify the bookmark name")
@@ -701,7 +703,7 b' class OSMagics(Magics):'
701 try :
703 try :
702 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
704 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
703 except (ValueError, IOError):
705 except (ValueError, IOError):
704 print "Error: no such file, variable, URL, history range or macro"
706 print("Error: no such file, variable, URL, history range or macro")
705 return
707 return
706
708
707 page.page(self.shell.pycolorize(source_to_unicode(cont)))
709 page.page(self.shell.pycolorize(source_to_unicode(cont)))
@@ -713,7 +715,7 b' class OSMagics(Magics):'
713 'The file will be created if it does not exist.'
715 'The file will be created if it does not exist.'
714 )
716 )
715 @magic_arguments.argument(
717 @magic_arguments.argument(
716 'filename', type=unicode,
718 'filename', type=unicode_type,
717 help='file to write'
719 help='file to write'
718 )
720 )
719 @cell_magic
721 @cell_magic
@@ -727,11 +729,11 b' class OSMagics(Magics):'
727
729
728 if os.path.exists(filename):
730 if os.path.exists(filename):
729 if args.append:
731 if args.append:
730 print "Appending to %s" % filename
732 print("Appending to %s" % filename)
731 else:
733 else:
732 print "Overwriting %s" % filename
734 print("Overwriting %s" % filename)
733 else:
735 else:
734 print "Writing %s" % filename
736 print("Writing %s" % filename)
735
737
736 mode = 'a' if args.append else 'w'
738 mode = 'a' if args.append else 'w'
737 with io.open(filename, mode, encoding='utf-8') as f:
739 with io.open(filename, mode, encoding='utf-8') as f:
@@ -1,5 +1,6 b''
1 """Implementation of magic functions for matplotlib/pylab support.
1 """Implementation of magic functions for matplotlib/pylab support.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -139,5 +140,4 b' class PylabMagics(Magics):'
139 def _show_matplotlib_backend(self, gui, backend):
140 def _show_matplotlib_backend(self, gui, backend):
140 """show matplotlib message backend message"""
141 """show matplotlib message backend message"""
141 if not gui or gui == 'auto':
142 if not gui or gui == 'auto':
142 print ("Using matplotlib backend: %s" % backend)
143 print("Using matplotlib backend: %s" % backend)
143
@@ -1,4 +1,5 b''
1 """Magic functions for running cells in various scripts."""
1 """Magic functions for running cells in various scripts."""
2 from __future__ import print_function
2 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
3 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
4 #
5 #
@@ -186,7 +187,7 b' class ScriptMagics(Magics):'
186 p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
187 p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
187 except OSError as e:
188 except OSError as e:
188 if e.errno == errno.ENOENT:
189 if e.errno == errno.ENOENT:
189 print "Couldn't find program: %r" % cmd[0]
190 print("Couldn't find program: %r" % cmd[0])
190 return
191 return
191 else:
192 else:
192 raise
193 raise
@@ -211,20 +212,20 b' class ScriptMagics(Magics):'
211 p.send_signal(signal.SIGINT)
212 p.send_signal(signal.SIGINT)
212 time.sleep(0.1)
213 time.sleep(0.1)
213 if p.poll() is not None:
214 if p.poll() is not None:
214 print "Process is interrupted."
215 print("Process is interrupted.")
215 return
216 return
216 p.terminate()
217 p.terminate()
217 time.sleep(0.1)
218 time.sleep(0.1)
218 if p.poll() is not None:
219 if p.poll() is not None:
219 print "Process is terminated."
220 print("Process is terminated.")
220 return
221 return
221 p.kill()
222 p.kill()
222 print "Process is killed."
223 print("Process is killed.")
223 except OSError:
224 except OSError:
224 pass
225 pass
225 except Exception as e:
226 except Exception as e:
226 print "Error while terminating subprocess (pid=%i): %s" \
227 print("Error while terminating subprocess (pid=%i): %s" \
227 % (p.pid, e)
228 % (p.pid, e))
228 return
229 return
229 out = py3compat.bytes_to_str(out)
230 out = py3compat.bytes_to_str(out)
230 err = py3compat.bytes_to_str(err)
231 err = py3compat.bytes_to_str(err)
@@ -249,7 +250,7 b' class ScriptMagics(Magics):'
249 def killbgscripts(self, _nouse_=''):
250 def killbgscripts(self, _nouse_=''):
250 """Kill all BG processes started by %%script and its family."""
251 """Kill all BG processes started by %%script and its family."""
251 self.kill_bg_processes()
252 self.kill_bg_processes()
252 print "All background processes were killed."
253 print("All background processes were killed.")
253
254
254 def kill_bg_processes(self):
255 def kill_bg_processes(self):
255 """Kill all BG processes which are still running."""
256 """Kill all BG processes which are still running."""
@@ -40,7 +40,7 b' from IPython.utils.dir2 import safe_hasattr'
40 from IPython.utils.text import indent
40 from IPython.utils.text import indent
41 from IPython.utils.wildcard import list_namespace
41 from IPython.utils.wildcard import list_namespace
42 from IPython.utils.coloransi import *
42 from IPython.utils.coloransi import *
43 from IPython.utils.py3compat import cast_unicode
43 from IPython.utils.py3compat import cast_unicode, string_types
44
44
45 #****************************************************************************
45 #****************************************************************************
46 # Builtin color schemes
46 # Builtin color schemes
@@ -130,7 +130,7 b' def getdoc(obj):'
130 pass
130 pass
131 else:
131 else:
132 # if we get extra info, we add it to the normal docstring.
132 # if we get extra info, we add it to the normal docstring.
133 if isinstance(ds, basestring):
133 if isinstance(ds, string_types):
134 return inspect.cleandoc(ds)
134 return inspect.cleandoc(ds)
135
135
136 try:
136 try:
@@ -188,13 +188,13 b' def getargspec(obj):'
188 if inspect.isfunction(obj):
188 if inspect.isfunction(obj):
189 func_obj = obj
189 func_obj = obj
190 elif inspect.ismethod(obj):
190 elif inspect.ismethod(obj):
191 func_obj = obj.im_func
191 func_obj = obj.__func__
192 elif hasattr(obj, '__call__'):
192 elif hasattr(obj, '__call__'):
193 func_obj = obj.__call__
193 func_obj = obj.__call__
194 else:
194 else:
195 raise TypeError('arg is not a Python function')
195 raise TypeError('arg is not a Python function')
196 args, varargs, varkw = inspect.getargs(func_obj.func_code)
196 args, varargs, varkw = inspect.getargs(func_obj.__code__)
197 return args, varargs, varkw, func_obj.func_defaults
197 return args, varargs, varkw, func_obj.__defaults__
198
198
199
199
200 def format_argspec(argspec):
200 def format_argspec(argspec):
@@ -314,7 +314,7 b" if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':"
314 return result
314 return result
315 else:
315 else:
316 def page_more():
316 def page_more():
317 ans = raw_input('---Return to continue, q to quit--- ')
317 ans = py3compat.input('---Return to continue, q to quit--- ')
318 if ans.lower().startswith('q'):
318 if ans.lower().startswith('q'):
319 return False
319 return False
320 else:
320 else:
@@ -345,6 +345,6 b" def snip_print(str,width = 75,print_full = 0,header = ''):"
345 print(str[:whalf] + ' <...> ' + str[-whalf:])
345 print(str[:whalf] + ' <...> ' + str[-whalf:])
346 snip = 1
346 snip = 1
347 if snip and print_full == 2:
347 if snip and print_full == 2:
348 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
348 if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
349 page(str)
349 page(str)
350 return snip
350 return snip
@@ -9,6 +9,7 b' Authors:'
9 * Min RK
9 * Min RK
10
10
11 """
11 """
12 from __future__ import print_function
12
13
13 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008 The IPython Development Team
15 # Copyright (C) 2008 The IPython Development Team
@@ -129,7 +130,7 b' class ProfileLocate(BaseIPythonApplication):'
129 self.profile = self.extra_args[0]
130 self.profile = self.extra_args[0]
130
131
131 def start(self):
132 def start(self):
132 print self.profile_dir.location
133 print(self.profile_dir.location)
133
134
134
135
135 class ProfileList(Application):
136 class ProfileList(Application):
@@ -160,35 +161,35 b' class ProfileList(Application):'
160 def _print_profiles(self, profiles):
161 def _print_profiles(self, profiles):
161 """print list of profiles, indented."""
162 """print list of profiles, indented."""
162 for profile in profiles:
163 for profile in profiles:
163 print ' %s' % profile
164 print(' %s' % profile)
164
165
165 def list_profile_dirs(self):
166 def list_profile_dirs(self):
166 profiles = list_bundled_profiles()
167 profiles = list_bundled_profiles()
167 if profiles:
168 if profiles:
168 print
169 print()
169 print "Available profiles in IPython:"
170 print("Available profiles in IPython:")
170 self._print_profiles(profiles)
171 self._print_profiles(profiles)
171 print
172 print()
172 print " The first request for a bundled profile will copy it"
173 print(" The first request for a bundled profile will copy it")
173 print " into your IPython directory (%s)," % self.ipython_dir
174 print(" into your IPython directory (%s)," % self.ipython_dir)
174 print " where you can customize it."
175 print(" where you can customize it.")
175
176
176 profiles = list_profiles_in(self.ipython_dir)
177 profiles = list_profiles_in(self.ipython_dir)
177 if profiles:
178 if profiles:
178 print
179 print()
179 print "Available profiles in %s:" % self.ipython_dir
180 print("Available profiles in %s:" % self.ipython_dir)
180 self._print_profiles(profiles)
181 self._print_profiles(profiles)
181
182
182 profiles = list_profiles_in(os.getcwdu())
183 profiles = list_profiles_in(os.getcwdu())
183 if profiles:
184 if profiles:
184 print
185 print()
185 print "Available profiles in current directory (%s):" % os.getcwdu()
186 print("Available profiles in current directory (%s):" % os.getcwdu())
186 self._print_profiles(profiles)
187 self._print_profiles(profiles)
187
188
188 print
189 print()
189 print "To use any of the above profiles, start IPython with:"
190 print("To use any of the above profiles, start IPython with:")
190 print " ipython --profile=<name>"
191 print(" ipython --profile=<name>")
191 print
192 print()
192
193
193 def start(self):
194 def start(self):
194 self.list_profile_dirs()
195 self.list_profile_dirs()
@@ -304,8 +305,8 b' class ProfileApp(Application):'
304
305
305 def start(self):
306 def start(self):
306 if self.subapp is None:
307 if self.subapp is None:
307 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
308 print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()))
308 print
309 print()
309 self.print_description()
310 self.print_description()
310 self.print_subcommands()
311 self.print_subcommands()
311 self.exit(1)
312 self.exit(1)
@@ -98,7 +98,7 b' class LazyEvaluate(object):'
98 return str(self())
98 return str(self())
99
99
100 def __unicode__(self):
100 def __unicode__(self):
101 return unicode(self())
101 return py3compat.unicode_type(self())
102
102
103 def __format__(self, format_spec):
103 def __format__(self, format_spec):
104 return format(self(), format_spec)
104 return format(self(), format_spec)
@@ -7,6 +7,7 b' Authors'
7 * Fernando Perez.
7 * Fernando Perez.
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10 from __future__ import print_function
10
11
11 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
12 # Copyright (C) 2009 The IPython Development Team
13 # Copyright (C) 2009 The IPython Development Team
@@ -274,12 +275,12 b' def import_pylab(user_ns, import_all=True):'
274 "np = numpy\n"
275 "np = numpy\n"
275 "plt = pyplot\n"
276 "plt = pyplot\n"
276 )
277 )
277 exec s in user_ns
278 exec(s, user_ns)
278
279
279 if import_all:
280 if import_all:
280 s = ("from matplotlib.pylab import *\n"
281 s = ("from matplotlib.pylab import *\n"
281 "from numpy import *\n")
282 "from numpy import *\n")
282 exec s in user_ns
283 exec(s, user_ns)
283
284
284 # IPython symbols to add
285 # IPython symbols to add
285 user_ns['figsize'] = figsize
286 user_ns['figsize'] = figsize
@@ -21,6 +21,7 b' Authors'
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from __future__ import absolute_import
23 from __future__ import absolute_import
24 from __future__ import print_function
24
25
25 import glob
26 import glob
26 import os
27 import os
@@ -248,7 +249,7 b' class InteractiveShellApp(Configurable):'
248 self.log.info("Enabling GUI event loop integration, "
249 self.log.info("Enabling GUI event loop integration, "
249 "eventloop=%s, matplotlib=%s", gui, backend)
250 "eventloop=%s, matplotlib=%s", gui, backend)
250 if key == "auto":
251 if key == "auto":
251 print ("Using matplotlib backend: %s" % backend)
252 print("Using matplotlib backend: %s" % backend)
252 else:
253 else:
253 gui = r
254 gui = r
254 self.log.info("Enabling GUI event loop integration, "
255 self.log.info("Enabling GUI event loop integration, "
@@ -1,2 +1,3 b''
1 from __future__ import print_function
1 import sys
2 import sys
2 print sys.argv[1:]
3 print(sys.argv[1:])
@@ -12,6 +12,7 b' This script is meant to be called by other parts of the test suite that call it'
12 via %run as if it were executed interactively by the user. As of 2011-05-29,
12 via %run as if it were executed interactively by the user. As of 2011-05-29,
13 test_run.py calls it.
13 test_run.py calls it.
14 """
14 """
15 from __future__ import print_function
15
16
16 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
17 # Module imports
18 # Module imports
@@ -44,4 +45,4 b" if __name__ == '__main__':"
44
45
45 def call_f():
46 def call_f():
46 for func in cache:
47 for func in cache:
47 print 'lowercased:',func().lower()
48 print('lowercased:',func().lower())
@@ -18,6 +18,7 b' from IPython.core import completer'
18 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
19 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
21 from IPython.utils.py3compat import string_types, unicode_type
21
22
22 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
23 # Test functions
24 # Test functions
@@ -64,7 +65,7 b' def check_line_split(splitter, test_specs):'
64
65
65
66
66 def test_line_split():
67 def test_line_split():
67 """Basice line splitter test with default specs."""
68 """Basic line splitter test with default specs."""
68 sp = completer.CompletionSplitter()
69 sp = completer.CompletionSplitter()
69 # The format of the test specs is: part1, part2, expected answer. Parts 1
70 # The format of the test specs is: part1, part2, expected answer. Parts 1
70 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
71 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
@@ -83,7 +84,7 b' def test_line_split():'
83 check_line_split(sp, t)
84 check_line_split(sp, t)
84 # Ensure splitting works OK with unicode by re-running the tests with
85 # Ensure splitting works OK with unicode by re-running the tests with
85 # all inputs turned into unicode
86 # all inputs turned into unicode
86 check_line_split(sp, [ map(unicode, p) for p in t] )
87 check_line_split(sp, [ map(unicode_type, p) for p in t] )
87
88
88
89
89 def test_custom_completion_error():
90 def test_custom_completion_error():
@@ -104,13 +105,13 b' def test_unicode_completions():'
104 # Some strings that trigger different types of completion. Check them both
105 # Some strings that trigger different types of completion. Check them both
105 # in str and unicode forms
106 # in str and unicode forms
106 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
107 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
107 for t in s + map(unicode, s):
108 for t in s + list(map(unicode_type, s)):
108 # We don't need to check exact completion values (they may change
109 # We don't need to check exact completion values (they may change
109 # depending on the state of the namespace, but at least no exceptions
110 # depending on the state of the namespace, but at least no exceptions
110 # should be thrown and the return value should be a pair of text, list
111 # should be thrown and the return value should be a pair of text, list
111 # values.
112 # values.
112 text, matches = ip.complete(t)
113 text, matches = ip.complete(t)
113 nt.assert_true(isinstance(text, basestring))
114 nt.assert_true(isinstance(text, string_types))
114 nt.assert_true(isinstance(matches, list))
115 nt.assert_true(isinstance(matches, list))
115
116
116
117
@@ -158,7 +159,7 b' def test_abspath_file_completions():'
158 ip = get_ipython()
159 ip = get_ipython()
159 with TemporaryDirectory() as tmpdir:
160 with TemporaryDirectory() as tmpdir:
160 prefix = os.path.join(tmpdir, 'foo')
161 prefix = os.path.join(tmpdir, 'foo')
161 suffixes = map(str, [1,2])
162 suffixes = ['1', '2']
162 names = [prefix+s for s in suffixes]
163 names = [prefix+s for s in suffixes]
163 for n in names:
164 for n in names:
164 open(n, 'w').close()
165 open(n, 'w').close()
@@ -181,7 +182,7 b' def test_local_file_completions():'
181 with TemporaryDirectory() as tmpdir:
182 with TemporaryDirectory() as tmpdir:
182 os.chdir(tmpdir)
183 os.chdir(tmpdir)
183 prefix = './foo'
184 prefix = './foo'
184 suffixes = map(str, [1,2])
185 suffixes = ['1', '2']
185 names = [prefix+s for s in suffixes]
186 names = [prefix+s for s in suffixes]
186 for n in names:
187 for n in names:
187 open(n, 'w').close()
188 open(n, 'w').close()
@@ -205,7 +206,7 b' def test_greedy_completions():'
205 greedy_original = ip.Completer.greedy
206 greedy_original = ip.Completer.greedy
206 try:
207 try:
207 ip.Completer.greedy = False
208 ip.Completer.greedy = False
208 ip.ex('a=range(5)')
209 ip.ex('a=list(range(5))')
209 _,c = ip.complete('.',line='a[0].')
210 _,c = ip.complete('.',line='a[0].')
210 nt.assert_false('a[0].real' in c,
211 nt.assert_false('a[0].real' in c,
211 "Shouldn't have completed on a[0]: %s"%c)
212 "Shouldn't have completed on a[0]: %s"%c)
@@ -226,18 +227,18 b' def test_omit__names():'
226 cfg.IPCompleter.omit__names = 0
227 cfg.IPCompleter.omit__names = 0
227 c.update_config(cfg)
228 c.update_config(cfg)
228 s,matches = c.complete('ip.')
229 s,matches = c.complete('ip.')
229 nt.assert_true('ip.__str__' in matches)
230 nt.assert_in('ip.__str__', matches)
230 nt.assert_true('ip._hidden_attr' in matches)
231 nt.assert_in('ip._hidden_attr', matches)
231 cfg.IPCompleter.omit__names = 1
232 cfg.IPCompleter.omit__names = 1
232 c.update_config(cfg)
233 c.update_config(cfg)
233 s,matches = c.complete('ip.')
234 s,matches = c.complete('ip.')
234 nt.assert_false('ip.__str__' in matches)
235 nt.assert_not_in('ip.__str__', matches)
235 nt.assert_true('ip._hidden_attr' in matches)
236 nt.assert_in('ip._hidden_attr', matches)
236 cfg.IPCompleter.omit__names = 2
237 cfg.IPCompleter.omit__names = 2
237 c.update_config(cfg)
238 c.update_config(cfg)
238 s,matches = c.complete('ip.')
239 s,matches = c.complete('ip.')
239 nt.assert_false('ip.__str__' in matches)
240 nt.assert_not_in('ip.__str__', matches)
240 nt.assert_false('ip._hidden_attr' in matches)
241 nt.assert_not_in('ip._hidden_attr', matches)
241 del ip._hidden_attr
242 del ip._hidden_attr
242
243
243
244
@@ -250,7 +251,7 b' def test_limit_to__all__False_ok():'
250 cfg.IPCompleter.limit_to__all__ = False
251 cfg.IPCompleter.limit_to__all__ = False
251 c.update_config(cfg)
252 c.update_config(cfg)
252 s, matches = c.complete('d.')
253 s, matches = c.complete('d.')
253 nt.assert_true('d.x' in matches)
254 nt.assert_in('d.x', matches)
254
255
255
256
256 def test_limit_to__all__True_ok():
257 def test_limit_to__all__True_ok():
@@ -263,8 +264,8 b' def test_limit_to__all__True_ok():'
263 cfg.IPCompleter.limit_to__all__ = True
264 cfg.IPCompleter.limit_to__all__ = True
264 c.update_config(cfg)
265 c.update_config(cfg)
265 s, matches = c.complete('d.')
266 s, matches = c.complete('d.')
266 nt.assert_true('d.z' in matches)
267 nt.assert_in('d.z', matches)
267 nt.assert_false('d.x' in matches)
268 nt.assert_not_in('d.x', matches)
268
269
269
270
270 def test_get__all__entries_ok():
271 def test_get__all__entries_ok():
@@ -1,5 +1,6 b''
1 """Tests for debugging machinery.
1 """Tests for debugging machinery.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012, The IPython Development Team.
5 # Copyright (c) 2012, The IPython Development Team.
5 #
6 #
@@ -36,7 +37,7 b' class _FakeInput(object):'
36
37
37 def readline(self):
38 def readline(self):
38 line = next(self.lines)
39 line = next(self.lines)
39 print line
40 print(line)
40 return line+'\n'
41 return line+'\n'
41
42
42 class PdbTestInput(object):
43 class PdbTestInput(object):
@@ -57,7 +58,10 b' class PdbTestInput(object):'
57 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
58
59
59 def test_longer_repr():
60 def test_longer_repr():
60 from repr import repr as trepr
61 try:
62 from reprlib import repr as trepr # Py 3
63 except ImportError:
64 from repr import repr as trepr # Py 2
61
65
62 a = '1234567890'* 7
66 a = '1234567890'* 7
63 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
67 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
@@ -43,9 +43,9 b' def test_history():'
43
43
44 # Detailed tests for _get_range_session
44 # Detailed tests for _get_range_session
45 grs = ip.history_manager._get_range_session
45 grs = ip.history_manager._get_range_session
46 nt.assert_equal(list(grs(start=2,stop=-1)), zip([0], [2], hist[1:-1]))
46 nt.assert_equal(list(grs(start=2,stop=-1)), list(zip([0], [2], hist[1:-1])))
47 nt.assert_equal(list(grs(start=-2)), zip([0,0], [2,3], hist[-2:]))
47 nt.assert_equal(list(grs(start=-2)), list(zip([0,0], [2,3], hist[-2:])))
48 nt.assert_equal(list(grs(output=True)), zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam'])))
48 nt.assert_equal(list(grs(output=True)), list(zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam']))))
49
49
50 # Check whether specifying a range beyond the end of the current
50 # Check whether specifying a range beyond the end of the current
51 # session results in an error (gh-804)
51 # session results in an error (gh-804)
@@ -66,10 +66,10 b' def test_history():'
66 for i, cmd in enumerate(newcmds, start=1):
66 for i, cmd in enumerate(newcmds, start=1):
67 ip.history_manager.store_inputs(i, cmd)
67 ip.history_manager.store_inputs(i, cmd)
68 gothist = ip.history_manager.get_range(start=1, stop=4)
68 gothist = ip.history_manager.get_range(start=1, stop=4)
69 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
69 nt.assert_equal(list(gothist), list(zip([0,0,0],[1,2,3], newcmds)))
70 # Previous session:
70 # Previous session:
71 gothist = ip.history_manager.get_range(-1, 1, 4)
71 gothist = ip.history_manager.get_range(-1, 1, 4)
72 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
72 nt.assert_equal(list(gothist), list(zip([1,1,1],[1,2,3], hist)))
73
73
74 newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)]
74 newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)]
75
75
@@ -6,6 +6,7 b' Authors'
6 * Fernando Perez
6 * Fernando Perez
7 * Robert Kern
7 * Robert Kern
8 """
8 """
9 from __future__ import print_function
9 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010-2011 The IPython Development Team
11 # Copyright (C) 2010-2011 The IPython Development Team
11 #
12 #
@@ -28,6 +29,7 b' from IPython.core import inputsplitter as isp'
28 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
29 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
29 from IPython.testing import tools as tt
30 from IPython.testing import tools as tt
30 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 from IPython.utils.py3compat import string_types, input
31
33
32 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
33 # Semi-complete examples (also used as tests)
35 # Semi-complete examples (also used as tests)
@@ -112,7 +114,7 b' def test_remove_comments():'
112
114
113 def test_get_input_encoding():
115 def test_get_input_encoding():
114 encoding = isp.get_input_encoding()
116 encoding = isp.get_input_encoding()
115 nt.assert_true(isinstance(encoding, basestring))
117 nt.assert_true(isinstance(encoding, string_types))
116 # simple-minded check that at least encoding a simple string works with the
118 # simple-minded check that at least encoding a simple string works with the
117 # encoding we got.
119 # encoding we got.
118 nt.assert_equal(u'test'.encode(encoding), b'test')
120 nt.assert_equal(u'test'.encode(encoding), b'test')
@@ -365,11 +367,11 b' class InteractiveLoopTestCase(unittest.TestCase):'
365 """
367 """
366 src = mini_interactive_loop(pseudo_input(lines))
368 src = mini_interactive_loop(pseudo_input(lines))
367 test_ns = {}
369 test_ns = {}
368 exec src in test_ns
370 exec(src, test_ns)
369 # We can't check that the provided ns is identical to the test_ns,
371 # We can't check that the provided ns is identical to the test_ns,
370 # because Python fills test_ns with extra keys (copyright, etc). But
372 # because Python fills test_ns with extra keys (copyright, etc). But
371 # we can check that the given dict is *contained* in test_ns
373 # we can check that the given dict is *contained* in test_ns
372 for k,v in ns.iteritems():
374 for k,v in ns.items():
373 self.assertEqual(test_ns[k], v)
375 self.assertEqual(test_ns[k], v)
374
376
375 def test_simple(self):
377 def test_simple(self):
@@ -404,7 +406,7 b' class IPythonInputTestCase(InputSplitterTestCase):'
404 def test_syntax(self):
406 def test_syntax(self):
405 """Call all single-line syntax tests from the main object"""
407 """Call all single-line syntax tests from the main object"""
406 isp = self.isp
408 isp = self.isp
407 for example in syntax.itervalues():
409 for example in syntax.values():
408 for raw, out_t in example:
410 for raw, out_t in example:
409 if raw.startswith(' '):
411 if raw.startswith(' '):
410 continue
412 continue
@@ -417,7 +419,7 b' class IPythonInputTestCase(InputSplitterTestCase):'
417
419
418 def test_syntax_multiline(self):
420 def test_syntax_multiline(self):
419 isp = self.isp
421 isp = self.isp
420 for example in syntax_ml.itervalues():
422 for example in syntax_ml.values():
421 for line_pairs in example:
423 for line_pairs in example:
422 out_t_parts = []
424 out_t_parts = []
423 raw_parts = []
425 raw_parts = []
@@ -437,7 +439,7 b' class IPythonInputTestCase(InputSplitterTestCase):'
437
439
438 def test_syntax_multiline_cell(self):
440 def test_syntax_multiline_cell(self):
439 isp = self.isp
441 isp = self.isp
440 for example in syntax_ml.itervalues():
442 for example in syntax_ml.values():
441
443
442 out_t_parts = []
444 out_t_parts = []
443 for line_pairs in example:
445 for line_pairs in example:
@@ -487,9 +489,9 b" if __name__ == '__main__':"
487 while isp.push_accepts_more():
489 while isp.push_accepts_more():
488 indent = ' '*isp.indent_spaces
490 indent = ' '*isp.indent_spaces
489 if autoindent:
491 if autoindent:
490 line = indent + raw_input(prompt+indent)
492 line = indent + input(prompt+indent)
491 else:
493 else:
492 line = raw_input(prompt)
494 line = input(prompt)
493 isp.push(line)
495 isp.push(line)
494 prompt = '... '
496 prompt = '... '
495
497
@@ -497,10 +499,10 b" if __name__ == '__main__':"
497 # real interpreter would instead send it for execution somewhere.
499 # real interpreter would instead send it for execution somewhere.
498 #src = isp.source; raise EOFError # dbg
500 #src = isp.source; raise EOFError # dbg
499 src, raw = isp.source_raw_reset()
501 src, raw = isp.source_raw_reset()
500 print 'Input source was:\n', src
502 print('Input source was:\n', src)
501 print 'Raw source was:\n', raw
503 print('Raw source was:\n', raw)
502 except EOFError:
504 except EOFError:
503 print 'Bye'
505 print('Bye')
504
506
505 # Tests for cell magics support
507 # Tests for cell magics support
506
508
@@ -28,7 +28,6 b' import sys'
28 import tempfile
28 import tempfile
29 import unittest
29 import unittest
30 from os.path import join
30 from os.path import join
31 from StringIO import StringIO
32
31
33 # third-party
32 # third-party
34 import nose.tools as nt
33 import nose.tools as nt
@@ -37,6 +36,12 b' import nose.tools as nt'
37 from IPython.testing.decorators import skipif, skip_win32, onlyif_unicode_paths
36 from IPython.testing.decorators import skipif, skip_win32, onlyif_unicode_paths
38 from IPython.testing import tools as tt
37 from IPython.testing import tools as tt
39 from IPython.utils import io
38 from IPython.utils import io
39 from IPython.utils.py3compat import unicode_type, PY3
40
41 if PY3:
42 from io import StringIO
43 else:
44 from StringIO import StringIO
40
45
41 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
42 # Globals
47 # Globals
@@ -140,7 +145,7 b' class InteractiveShellTestCase(unittest.TestCase):'
140 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
145 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
141 ip.run_cell('from __future__ import unicode_literals')
146 ip.run_cell('from __future__ import unicode_literals')
142 ip.run_cell(u'unicode_str = "a"')
147 ip.run_cell(u'unicode_str = "a"')
143 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
148 assert isinstance(ip.user_ns['unicode_str'], unicode_type) # strings literals are now unicode
144 finally:
149 finally:
145 # Reset compiler flags so we don't mess up other tests.
150 # Reset compiler flags so we don't mess up other tests.
146 ip.compile.reset_compiler_flags()
151 ip.compile.reset_compiler_flags()
@@ -154,7 +159,7 b' class InteractiveShellTestCase(unittest.TestCase):'
154 " list.__init__(self,x)"))
159 " list.__init__(self,x)"))
155 ip.run_cell("w=Mylist([1,2,3])")
160 ip.run_cell("w=Mylist([1,2,3])")
156
161
157 from cPickle import dumps
162 from pickle import dumps
158
163
159 # We need to swap in our main module - this is only necessary
164 # We need to swap in our main module - this is only necessary
160 # inside the test framework, because IPython puts the interactive module
165 # inside the test framework, because IPython puts the interactive module
@@ -12,7 +12,6 b' from __future__ import absolute_import'
12 import io
12 import io
13 import os
13 import os
14 import sys
14 import sys
15 from StringIO import StringIO
16 from unittest import TestCase
15 from unittest import TestCase
17
16
18 try:
17 try:
@@ -38,6 +37,11 b' from IPython.utils.io import capture_output'
38 from IPython.utils.tempdir import TemporaryDirectory
37 from IPython.utils.tempdir import TemporaryDirectory
39 from IPython.utils.process import find_cmd
38 from IPython.utils.process import find_cmd
40
39
40 if py3compat.PY3:
41 from io import StringIO
42 else:
43 from StringIO import StringIO
44
41 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
42 # Test functions begin
46 # Test functions begin
43 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
@@ -290,18 +294,18 b' def test_reset_out():'
290 _ip.run_cell("parrot = 'dead'", store_history=True)
294 _ip.run_cell("parrot = 'dead'", store_history=True)
291 # test '%reset -f out', make an Out prompt
295 # test '%reset -f out', make an Out prompt
292 _ip.run_cell("parrot", store_history=True)
296 _ip.run_cell("parrot", store_history=True)
293 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
297 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
294 _ip.magic('reset -f out')
298 _ip.magic('reset -f out')
295 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
299 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
296 nt.assert_equal(len(_ip.user_ns['Out']), 0)
300 nt.assert_equal(len(_ip.user_ns['Out']), 0)
297
301
298 def test_reset_in():
302 def test_reset_in():
299 "Test '%reset in' magic"
303 "Test '%reset in' magic"
300 # test '%reset -f in'
304 # test '%reset -f in'
301 _ip.run_cell("parrot", store_history=True)
305 _ip.run_cell("parrot", store_history=True)
302 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
306 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
303 _ip.magic('%reset -f in')
307 _ip.magic('%reset -f in')
304 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
308 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
305 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
309 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
306
310
307 def test_reset_dhist():
311 def test_reset_dhist():
@@ -830,9 +834,9 b' def test_multiple_magics():'
830 foo2 = FooFoo(ip)
834 foo2 = FooFoo(ip)
831 mm = ip.magics_manager
835 mm = ip.magics_manager
832 mm.register(foo1)
836 mm.register(foo1)
833 nt.assert_true(mm.magics['line']['foo'].im_self is foo1)
837 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
834 mm.register(foo2)
838 mm.register(foo2)
835 nt.assert_true(mm.magics['line']['foo'].im_self is foo2)
839 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
836
840
837 def test_alias_magic():
841 def test_alias_magic():
838 """Test %alias_magic."""
842 """Test %alias_magic."""
@@ -9,12 +9,17 b' from __future__ import absolute_import'
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import sys
11 import sys
12 from StringIO import StringIO
13 from unittest import TestCase
12 from unittest import TestCase
14
13
15 import nose.tools as nt
14 import nose.tools as nt
16
15
17 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
17 from IPython.utils.py3compat import PY3
18
19 if PY3:
20 from io import StringIO
21 else:
22 from StringIO import StringIO
18
23
19 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
20 # Globals
25 # Globals
@@ -9,6 +9,7 b' from IPython.testing import tools as tt, decorators as dec'
9 from IPython.core.prompts import PromptManager, LazyEvaluate
9 from IPython.core.prompts import PromptManager, LazyEvaluate
10 from IPython.testing.globalipapp import get_ipython
10 from IPython.testing.globalipapp import get_ipython
11 from IPython.utils.tempdir import TemporaryDirectory
11 from IPython.utils.tempdir import TemporaryDirectory
12 from IPython.utils.py3compat import unicode_type
12
13
13 ip = get_ipython()
14 ip = get_ipython()
14
15
@@ -77,7 +78,7 b' class PromptTests(unittest.TestCase):'
77 u = u'ΓΌnicΓΈdΓ©'
78 u = u'ΓΌnicΓΈdΓ©'
78 lz = LazyEvaluate(lambda : u)
79 lz = LazyEvaluate(lambda : u)
79 # str(lz) would fail
80 # str(lz) would fail
80 self.assertEqual(unicode(lz), u)
81 self.assertEqual(unicode_type(lz), u)
81 self.assertEqual(format(lz), u)
82 self.assertEqual(format(lz), u)
82
83
83 def test_lazy_eval_nonascii_bytes(self):
84 def test_lazy_eval_nonascii_bytes(self):
@@ -93,7 +94,7 b' class PromptTests(unittest.TestCase):'
93 lz = LazyEvaluate(lambda : f)
94 lz = LazyEvaluate(lambda : f)
94
95
95 self.assertEqual(str(lz), str(f))
96 self.assertEqual(str(lz), str(f))
96 self.assertEqual(unicode(lz), unicode(f))
97 self.assertEqual(unicode_type(lz), unicode_type(f))
97 self.assertEqual(format(lz), str(f))
98 self.assertEqual(format(lz), str(f))
98 self.assertEqual(format(lz, '.1'), '0.5')
99 self.assertEqual(format(lz, '.1'), '0.5')
99
100
@@ -79,6 +79,7 b' Inheritance diagram:'
79 #*****************************************************************************
79 #*****************************************************************************
80
80
81 from __future__ import unicode_literals
81 from __future__ import unicode_literals
82 from __future__ import print_function
82
83
83 import inspect
84 import inspect
84 import keyword
85 import keyword
@@ -195,9 +196,9 b' def findsource(object):'
195 raise IOError('could not find class definition')
196 raise IOError('could not find class definition')
196
197
197 if ismethod(object):
198 if ismethod(object):
198 object = object.im_func
199 object = object.__func__
199 if isfunction(object):
200 if isfunction(object):
200 object = object.func_code
201 object = object.__code__
201 if istraceback(object):
202 if istraceback(object):
202 object = object.tb_frame
203 object = object.tb_frame
203 if isframe(object):
204 if isframe(object):
@@ -942,7 +943,7 b' class VerboseTB(TBTools):'
942 ColorsNormal, py3compat.cast_unicode(evalue_str))]
943 ColorsNormal, py3compat.cast_unicode(evalue_str))]
943 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
944 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
944 try:
945 try:
945 names = [w for w in dir(evalue) if isinstance(w, basestring)]
946 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
946 except:
947 except:
947 # Every now and then, an object with funny inernals blows up
948 # Every now and then, an object with funny inernals blows up
948 # when dir() is called on it. We do the best we can to report
949 # when dir() is called on it. We do the best we can to report
@@ -1035,7 +1036,7 b' class VerboseTB(TBTools):'
1035 try:
1036 try:
1036 self.debugger()
1037 self.debugger()
1037 except KeyboardInterrupt:
1038 except KeyboardInterrupt:
1038 print "\nKeyboardInterrupt"
1039 print("\nKeyboardInterrupt")
1039
1040
1040 #----------------------------------------------------------------------------
1041 #----------------------------------------------------------------------------
1041 class FormattedTB(VerboseTB, ListTB):
1042 class FormattedTB(VerboseTB, ListTB):
@@ -1166,7 +1167,7 b' class AutoFormattedTB(FormattedTB):'
1166 try:
1167 try:
1167 self.debugger()
1168 self.debugger()
1168 except KeyboardInterrupt:
1169 except KeyboardInterrupt:
1169 print "\nKeyboardInterrupt"
1170 print("\nKeyboardInterrupt")
1170
1171
1171 def structured_traceback(self, etype=None, value=None, tb=None,
1172 def structured_traceback(self, etype=None, value=None, tb=None,
1172 tb_offset=None, context=5):
1173 tb_offset=None, context=5):
@@ -1240,27 +1241,27 b' if __name__ == "__main__":'
1240 i = f - g
1241 i = f - g
1241 return h / i
1242 return h / i
1242
1243
1243 print ''
1244 print('')
1244 print '*** Before ***'
1245 print('*** Before ***')
1245 try:
1246 try:
1246 print spam(1, (2, 3))
1247 print(spam(1, (2, 3)))
1247 except:
1248 except:
1248 traceback.print_exc()
1249 traceback.print_exc()
1249 print ''
1250 print('')
1250
1251
1251 handler = ColorTB()
1252 handler = ColorTB()
1252 print '*** ColorTB ***'
1253 print('*** ColorTB ***')
1253 try:
1254 try:
1254 print spam(1, (2, 3))
1255 print(spam(1, (2, 3)))
1255 except:
1256 except:
1256 handler(*sys.exc_info())
1257 handler(*sys.exc_info())
1257 print ''
1258 print('')
1258
1259
1259 handler = VerboseTB()
1260 handler = VerboseTB()
1260 print '*** VerboseTB ***'
1261 print('*** VerboseTB ***')
1261 try:
1262 try:
1262 print spam(1, (2, 3))
1263 print(spam(1, (2, 3)))
1263 except:
1264 except:
1264 handler(*sys.exc_info())
1265 handler(*sys.exc_info())
1265 print ''
1266 print('')
1266
1267
@@ -186,9 +186,9 b' class ModuleReloader(object):'
186 return
186 return
187
187
188 if check_all or self.check_all:
188 if check_all or self.check_all:
189 modules = sys.modules.keys()
189 modules = list(sys.modules.keys())
190 else:
190 else:
191 modules = self.modules.keys()
191 modules = list(self.modules.keys())
192
192
193 for modname in modules:
193 for modname in modules:
194 m = sys.modules.get(modname, None)
194 m = sys.modules.get(modname, None)
@@ -258,7 +258,7 b' def update_function(old, new):'
258 def update_class(old, new):
258 def update_class(old, new):
259 """Replace stuff in the __dict__ of a class, and upgrade
259 """Replace stuff in the __dict__ of a class, and upgrade
260 method code objects"""
260 method code objects"""
261 for key in old.__dict__.keys():
261 for key in list(old.__dict__.keys()):
262 old_obj = getattr(old, key)
262 old_obj = getattr(old, key)
263
263
264 try:
264 try:
@@ -308,7 +308,7 b' else:'
308 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
308 UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
309 update_class),
309 update_class),
310 (lambda a, b: isinstance2(a, b, types.MethodType),
310 (lambda a, b: isinstance2(a, b, types.MethodType),
311 lambda a, b: update_function(a.im_func, b.im_func)),
311 lambda a, b: update_function(a.__func__, b.__func__)),
312 ])
312 ])
313
313
314
314
@@ -339,7 +339,7 b' def superreload(module, reload=reload, old_objects={}):'
339 """
339 """
340
340
341 # collect old objects in the module
341 # collect old objects in the module
342 for name, obj in module.__dict__.items():
342 for name, obj in list(module.__dict__.items()):
343 if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
343 if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
344 continue
344 continue
345 key = (module.__name__, name)
345 key = (module.__name__, name)
@@ -370,7 +370,7 b' def superreload(module, reload=reload, old_objects={}):'
370 raise
370 raise
371
371
372 # iterate over all objects and update functions & classes
372 # iterate over all objects and update functions & classes
373 for name, new_obj in module.__dict__.items():
373 for name, new_obj in list(module.__dict__.items()):
374 key = (module.__name__, name)
374 key = (module.__name__, name)
375 if key not in old_objects: continue
375 if key not in old_objects: continue
376
376
@@ -473,10 +473,8 b' class AutoreloadMagics(Magics):'
473 """
473 """
474 modname = parameter_s
474 modname = parameter_s
475 if not modname:
475 if not modname:
476 to_reload = self._reloader.modules.keys()
476 to_reload = sorted(self._reloader.modules.keys())
477 to_reload.sort()
477 to_skip = sorted(self._reloader.skip_modules.keys())
478 to_skip = self._reloader.skip_modules.keys()
479 to_skip.sort()
480 if stream is None:
478 if stream is None:
481 stream = sys.stdout
479 stream = sys.stdout
482 if self._reloader.check_all:
480 if self._reloader.check_all:
@@ -35,6 +35,7 b' To enable the magics below, execute ``%load_ext rmagic``.'
35 {RGET_DOC}
35 {RGET_DOC}
36
36
37 """
37 """
38 from __future__ import print_function
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Copyright (C) 2012 The IPython Development Team
41 # Copyright (C) 2012 The IPython Development Team
@@ -9,6 +9,7 b' To automatically restore stored variables at startup, add this to your'
9
9
10 c.StoreMagic.autorestore = True
10 c.StoreMagic.autorestore = True
11 """
11 """
12 from __future__ import print_function
12 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
13 # Copyright (c) 2012, The IPython Development Team.
14 # Copyright (c) 2012, The IPython Development Team.
14 #
15 #
@@ -29,6 +30,7 b' from IPython.core.error import UsageError'
29 from IPython.core.magic import Magics, magics_class, line_magic
30 from IPython.core.magic import Magics, magics_class, line_magic
30 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.utils.traitlets import Bool
32 from IPython.utils.traitlets import Bool
33 from IPython.utils.py3compat import string_types
32
34
33 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
34 # Functions and classes
36 # Functions and classes
@@ -50,8 +52,8 b' def refresh_variables(ip):'
50 try:
52 try:
51 obj = db[key]
53 obj = db[key]
52 except KeyError:
54 except KeyError:
53 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
55 print("Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey)
54 print "The error was:", sys.exc_info()[0]
56 print("The error was:", sys.exc_info()[0])
55 else:
57 else:
56 #print "restored",justkey,"=",obj #dbg
58 #print "restored",justkey,"=",obj #dbg
57 ip.user_ns[justkey] = obj
59 ip.user_ns[justkey] = obj
@@ -155,7 +157,7 b' class StoreMagics(Magics):'
155 try:
157 try:
156 obj = db['autorestore/' + arg]
158 obj = db['autorestore/' + arg]
157 except KeyError:
159 except KeyError:
158 print "no stored variable %s" % arg
160 print("no stored variable %s" % arg)
159 else:
161 else:
160 ip.user_ns[arg] = obj
162 ip.user_ns[arg] = obj
161 else:
163 else:
@@ -170,13 +172,13 b' class StoreMagics(Magics):'
170 else:
172 else:
171 size = 0
173 size = 0
172
174
173 print 'Stored variables and their in-db values:'
175 print('Stored variables and their in-db values:')
174 fmt = '%-'+str(size)+'s -> %s'
176 fmt = '%-'+str(size)+'s -> %s'
175 get = db.get
177 get = db.get
176 for var in vars:
178 for var in vars:
177 justkey = os.path.basename(var)
179 justkey = os.path.basename(var)
178 # print 30 first characters from every var
180 # print 30 first characters from every var
179 print fmt % (justkey, repr(get(var, '<unavailable>'))[:50])
181 print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50]))
180
182
181 # default action - store the variable
183 # default action - store the variable
182 else:
184 else:
@@ -188,11 +190,11 b' class StoreMagics(Magics):'
188 else:
190 else:
189 fil = open(fnam, 'w')
191 fil = open(fnam, 'w')
190 obj = ip.ev(args[0])
192 obj = ip.ev(args[0])
191 print "Writing '%s' (%s) to file '%s'." % (args[0],
193 print("Writing '%s' (%s) to file '%s'." % (args[0],
192 obj.__class__.__name__, fnam)
194 obj.__class__.__name__, fnam))
193
195
194
196
195 if not isinstance (obj, basestring):
197 if not isinstance (obj, string_types):
196 from pprint import pprint
198 from pprint import pprint
197 pprint(obj, fil)
199 pprint(obj, fil)
198 else:
200 else:
@@ -217,22 +219,22 b' class StoreMagics(Magics):'
217 staliases = db.get('stored_aliases',{})
219 staliases = db.get('stored_aliases',{})
218 staliases[name] = cmd
220 staliases[name] = cmd
219 db['stored_aliases'] = staliases
221 db['stored_aliases'] = staliases
220 print "Alias stored: %s (%s)" % (name, cmd)
222 print("Alias stored: %s (%s)" % (name, cmd))
221 return
223 return
222
224
223 else:
225 else:
224 modname = getattr(inspect.getmodule(obj), '__name__', '')
226 modname = getattr(inspect.getmodule(obj), '__name__', '')
225 if modname == '__main__':
227 if modname == '__main__':
226 print textwrap.dedent("""\
228 print(textwrap.dedent("""\
227 Warning:%s is %s
229 Warning:%s is %s
228 Proper storage of interactively declared classes (or instances
230 Proper storage of interactively declared classes (or instances
229 of those classes) is not possible! Only instances
231 of those classes) is not possible! Only instances
230 of classes in real modules on file system can be %%store'd.
232 of classes in real modules on file system can be %%store'd.
231 """ % (args[0], obj) )
233 """ % (args[0], obj) ))
232 return
234 return
233 #pickled = pickle.dumps(obj)
235 #pickled = pickle.dumps(obj)
234 db[ 'autorestore/' + args[0] ] = obj
236 db[ 'autorestore/' + args[0] ] = obj
235 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
237 print("Stored '%s' (%s)" % (args[0], obj.__class__.__name__))
236
238
237
239
238 def load_ipython_extension(ip):
240 def load_ipython_extension(ip):
@@ -27,6 +27,7 b' maintained here for backwards compatablitiy with old SymPy versions.'
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29 from IPython.lib.latextools import latex_to_png
29 from IPython.lib.latextools import latex_to_png
30 from IPython.utils.py3compat import string_types
30
31
31 try:
32 try:
32 from sympy import pretty, latex
33 from sympy import pretty, latex
@@ -85,7 +86,7 b' def can_print_latex(o):'
85 if isinstance(o, (list, tuple, set, frozenset)):
86 if isinstance(o, (list, tuple, set, frozenset)):
86 return all(can_print_latex(i) for i in o)
87 return all(can_print_latex(i) for i in o)
87 elif isinstance(o, dict):
88 elif isinstance(o, dict):
88 return all((isinstance(i, basestring) or can_print_latex(i)) and can_print_latex(o[i]) for i in o)
89 return all((isinstance(i, string_types) or can_print_latex(i)) and can_print_latex(o[i]) for i in o)
89 elif isinstance(o,(sympy.Basic, sympy.matrices.Matrix, int, long, float)):
90 elif isinstance(o,(sympy.Basic, sympy.matrices.Matrix, int, long, float)):
90 return True
91 return True
91 return False
92 return False
@@ -18,13 +18,18 b' import tempfile'
18 import shutil
18 import shutil
19 import random
19 import random
20 import time
20 import time
21 from StringIO import StringIO
22
21
23 import nose.tools as nt
22 import nose.tools as nt
24 import IPython.testing.tools as tt
23 import IPython.testing.tools as tt
25
24
26 from IPython.extensions.autoreload import AutoreloadMagics
25 from IPython.extensions.autoreload import AutoreloadMagics
27 from IPython.core.hooks import TryNext
26 from IPython.core.hooks import TryNext
27 from IPython.utils.py3compat import PY3
28
29 if PY3:
30 from io import StringIO
31 else:
32 from StringIO import StringIO
28
33
29 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
30 # Test fixture
35 # Test fixture
@@ -45,7 +50,7 b' class FakeShell(object):'
45 self.auto_magics.pre_run_code_hook(self)
50 self.auto_magics.pre_run_code_hook(self)
46 except TryNext:
51 except TryNext:
47 pass
52 pass
48 exec code in self.ns
53 exec(code, self.ns)
49
54
50 def push(self, items):
55 def push(self, items):
51 self.ns.update(items)
56 self.ns.update(items)
@@ -1,11 +1,15 b''
1 from StringIO import StringIO
2
3 import numpy as np
1 import numpy as np
4 from IPython.testing.decorators import skip_without
2 from IPython.testing.decorators import skip_without
5 from IPython.extensions import rmagic
3 from IPython.extensions import rmagic
4 from IPython.utils.py3compat import PY3
6 from rpy2 import rinterface
5 from rpy2 import rinterface
7 import nose.tools as nt
6 import nose.tools as nt
8
7
8 if PY3:
9 from io import StringIO
10 else:
11 from StringIO import StringIO
12
9 ip = get_ipython()
13 ip = get_ipython()
10 ip.magic('load_ext rmagic')
14 ip.magic('load_ext rmagic')
11
15
@@ -1,4 +1,4 b''
1 try:
1 try:
2 from decorator import *
2 from decorator import *
3 except ImportError:
3 except ImportError:
4 from _decorator import *
4 from ._decorator import *
@@ -31,6 +31,7 b''
31 Decorator module, see http://pypi.python.org/pypi/decorator
31 Decorator module, see http://pypi.python.org/pypi/decorator
32 for the documentation.
32 for the documentation.
33 """
33 """
34 from __future__ import print_function
34
35
35 __version__ = '3.3.3'
36 __version__ = '3.3.3'
36
37
@@ -135,7 +136,7 b' class FunctionMaker(object):'
135 func.__name__ = self.name
136 func.__name__ = self.name
136 func.__doc__ = getattr(self, 'doc', None)
137 func.__doc__ = getattr(self, 'doc', None)
137 func.__dict__ = getattr(self, 'dict', {})
138 func.__dict__ = getattr(self, 'dict', {})
138 func.func_defaults = getattr(self, 'defaults', ())
139 func.__defaults__ = getattr(self, 'defaults', ())
139 func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
140 func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
140 func.__annotations__ = getattr(self, 'annotations', None)
141 func.__annotations__ = getattr(self, 'annotations', None)
141 callermodule = sys._getframe(3).f_globals.get('__name__', '?')
142 callermodule = sys._getframe(3).f_globals.get('__name__', '?')
@@ -160,10 +161,10 b' class FunctionMaker(object):'
160 try:
161 try:
161 code = compile(src, '<string>', 'single')
162 code = compile(src, '<string>', 'single')
162 # print >> sys.stderr, 'Compiling %s' % src
163 # print >> sys.stderr, 'Compiling %s' % src
163 exec code in evaldict
164 exec(code, evaldict)
164 except:
165 except:
165 print >> sys.stderr, 'Error in generated code:'
166 print('Error in generated code:', file=sys.stderr)
166 print >> sys.stderr, src
167 print(src, file=sys.stderr)
167 raise
168 raise
168 func = evaldict[name]
169 func = evaldict[name]
169 if addsource:
170 if addsource:
@@ -199,7 +200,7 b' def decorator(caller, func=None):'
199 decorator(caller, func) decorates a function using a caller.
200 decorator(caller, func) decorates a function using a caller.
200 """
201 """
201 if func is not None: # returns a decorated function
202 if func is not None: # returns a decorated function
202 evaldict = func.func_globals.copy()
203 evaldict = func.__globals__.copy()
203 evaldict['_call_'] = caller
204 evaldict['_call_'] = caller
204 evaldict['_func_'] = func
205 evaldict['_func_'] = func
205 return FunctionMaker.create(
206 return FunctionMaker.create(
@@ -210,7 +211,7 b' def decorator(caller, func=None):'
210 return partial(decorator, caller)
211 return partial(decorator, caller)
211 # otherwise assume caller is a function
212 # otherwise assume caller is a function
212 first = inspect.getargspec(caller)[0][0] # first arg
213 first = inspect.getargspec(caller)[0][0] # first arg
213 evaldict = caller.func_globals.copy()
214 evaldict = caller.__globals__.copy()
214 evaldict['_call_'] = caller
215 evaldict['_call_'] = caller
215 evaldict['decorator'] = decorator
216 evaldict['decorator'] = decorator
216 return FunctionMaker.create(
217 return FunctionMaker.create(
@@ -2,8 +2,8 b' try:'
2 from numpy.testing.decorators import *
2 from numpy.testing.decorators import *
3 from numpy.testing.noseclasses import KnownFailure
3 from numpy.testing.noseclasses import KnownFailure
4 except ImportError:
4 except ImportError:
5 from _decorators import *
5 from ._decorators import *
6 try:
6 try:
7 from _numpy_testing_noseclasses import KnownFailure
7 from ._numpy_testing_noseclasses import KnownFailure
8 except ImportError:
8 except ImportError:
9 pass
9 pass
@@ -20,9 +20,9 b' import warnings'
20 #from numpy.testing.utils import \
20 #from numpy.testing.utils import \
21 # WarningManager, WarningMessage
21 # WarningManager, WarningMessage
22 # Our version:
22 # Our version:
23 from _numpy_testing_utils import WarningManager
23 from ._numpy_testing_utils import WarningManager
24 try:
24 try:
25 from _numpy_testing_noseclasses import KnownFailureTest
25 from ._numpy_testing_noseclasses import KnownFailureTest
26 except:
26 except:
27 pass
27 pass
28
28
@@ -1,4 +1,4 b''
1 try:
1 try:
2 from jsonpointer import *
2 from jsonpointer import *
3 except ImportError :
3 except ImportError :
4 from _jsonpointer import *
4 from ._jsonpointer import *
@@ -1,4 +1,4 b''
1 try:
1 try:
2 from jsonschema import *
2 from jsonschema import *
3 except ImportError :
3 except ImportError :
4 from _jsonschema import *
4 from ._jsonschema import *
@@ -38,6 +38,7 b' To find the directory where IPython would like MathJax installed:'
38 $ python -m IPython.external.mathjax -d
38 $ python -m IPython.external.mathjax -d
39
39
40 """
40 """
41 from __future__ import print_function
41
42
42
43
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
@@ -86,14 +87,14 b' def prepare_dest(dest, replace=False):'
86
87
87 if os.path.exists(dest):
88 if os.path.exists(dest):
88 if replace:
89 if replace:
89 print "removing existing MathJax at %s" % dest
90 print("removing existing MathJax at %s" % dest)
90 shutil.rmtree(dest)
91 shutil.rmtree(dest)
91 return True
92 return True
92 else:
93 else:
93 mathjax_js = os.path.join(dest, 'MathJax.js')
94 mathjax_js = os.path.join(dest, 'MathJax.js')
94 if not os.path.exists(mathjax_js):
95 if not os.path.exists(mathjax_js):
95 raise IOError("%s exists, but does not contain MathJax.js" % dest)
96 raise IOError("%s exists, but does not contain MathJax.js" % dest)
96 print "%s already exists" % mathjax_js
97 print("%s already exists" % mathjax_js)
97 return False
98 return False
98 else:
99 else:
99 return True
100 return True
@@ -165,11 +166,11 b" def install_mathjax(tag='v2.2', dest=default_dest, replace=False, file=None, ext"
165 if file is None:
166 if file is None:
166 # download mathjax
167 # download mathjax
167 mathjax_url = "https://github.com/mathjax/MathJax/archive/%s.tar.gz" %tag
168 mathjax_url = "https://github.com/mathjax/MathJax/archive/%s.tar.gz" %tag
168 print "Downloading mathjax source from %s" % mathjax_url
169 print("Downloading mathjax source from %s" % mathjax_url)
169 response = urllib2.urlopen(mathjax_url)
170 response = urllib2.urlopen(mathjax_url)
170 file = response.fp
171 file = response.fp
171
172
172 print "Extracting to %s" % dest
173 print("Extracting to %s" % dest)
173 extractor(file, dest)
174 extractor(file, dest)
174 return 0
175 return 0
175
176
@@ -205,7 +206,7 b' def main():'
205 dest = os.path.join(pargs.install_dir, 'mathjax')
206 dest = os.path.join(pargs.install_dir, 'mathjax')
206
207
207 if pargs.print_dest:
208 if pargs.print_dest:
208 print dest
209 print(dest)
209 return
210 return
210
211
211 # remove/replace existing mathjax?
212 # remove/replace existing mathjax?
This diff has been collapsed as it changes many lines, (774 lines changed) Show them Hide them
@@ -1,56 +1,149 b''
1 #
2 # Copyright (c) 2010 Mikhail Gusarov
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining a copy
5 # of this software and associated documentation files (the "Software"), to deal
6 # in the Software without restriction, including without limitation the rights
7 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 # copies of the Software, and to permit persons to whom the Software is
9 # furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice shall be included in
12 # all copies or substantial portions of the Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 # SOFTWARE.
21 #
22
1 """ path.py - An object representing a path to a file or directory.
23 """ path.py - An object representing a path to a file or directory.
2
24
3 Example:
25 Original author:
26 Jason Orendorff <jason.orendorff\x40gmail\x2ecom>
27
28 Current maintainer:
29 Jason R. Coombs <jaraco@jaraco.com>
4
30
5 from IPython.external.path import path
31 Contributors:
6 d = path('/home/guido/bin')
32 Mikhail Gusarov <dottedmag@dottedmag.net>
7 for f in d.files('*.py'):
33 Marc Abramowitz <marc@marc-abramowitz.com>
8 f.chmod(0755)
34 Jason R. Coombs <jaraco@jaraco.com>
35 Jason Chu <jchu@xentac.net>
36 Vojislav Stojkovic <vstojkovic@syntertainment.com>
9
37
10 This module requires Python 2.5 or later.
38 Example::
11
39
40 from path import path
41 d = path('/home/guido/bin')
42 for f in d.files('*.py'):
43 f.chmod(0755)
12
44
13 URL: http://pypi.python.org/pypi/path.py
45 path.py requires Python 2.5 or later.
14 Author: Jason Orendorff <jason.orendorff\x40gmail\x2ecom> (and others - see the url!)
15 Date: 9 Mar 2007
16 """
46 """
17
47
48 from __future__ import with_statement
49
50 import sys
51 import warnings
52 import os
53 import fnmatch
54 import glob
55 import shutil
56 import codecs
57 import hashlib
58 import errno
59 import tempfile
60 import functools
61 import operator
62 import re
63
64 try:
65 import win32security
66 except ImportError:
67 pass
18
68
19 # TODO
69 try:
20 # - Tree-walking functions don't avoid symlink loops. Matt Harrison
70 import pwd
21 # sent me a patch for this.
71 except ImportError:
22 # - Bug in write_text(). It doesn't support Universal newline mode.
72 pass
23 # - Better error message in listdir() when self isn't a
24 # directory. (On Windows, the error message really sucks.)
25 # - Make sure everything has a good docstring.
26 # - Add methods for regex find and replace.
27 # - guess_content_type() method?
28 # - Perhaps support arguments to touch().
29
73
30 from __future__ import generators
74 ################################
75 # Monkey patchy python 3 support
76 try:
77 basestring
78 except NameError:
79 basestring = str
80
81 try:
82 unicode
83 except NameError:
84 unicode = str
85
86 try:
87 os.getcwdu
88 except AttributeError:
89 os.getcwdu = os.getcwd
90
91 if sys.version < '3':
92 def u(x):
93 return codecs.unicode_escape_decode(x)[0]
94 else:
95 def u(x):
96 return x
31
97
32 import sys, warnings, os, fnmatch, glob, shutil, codecs
98 o777 = 511
33 from hashlib import md5
99 o766 = 502
100 o666 = 438
101 o554 = 364
102 ################################
34
103
35 __version__ = '2.2'
104 __version__ = '4.3'
36 __all__ = ['path']
105 __all__ = ['path']
37
106
38 # Platform-specific support for path.owner
39 if os.name == 'nt':
40 try:
41 import win32security
42 except ImportError:
43 win32security = None
44 else:
45 try:
46 import pwd
47 except ImportError:
48 pwd = None
49
50
107
51 class TreeWalkWarning(Warning):
108 class TreeWalkWarning(Warning):
52 pass
109 pass
53
110
111
112 def simple_cache(func):
113 """
114 Save results for the 'using_module' classmethod.
115 When Python 3.2 is available, use functools.lru_cache instead.
116 """
117 saved_results = {}
118
119 def wrapper(cls, module):
120 if module in saved_results:
121 return saved_results[module]
122 saved_results[module] = func(cls, module)
123 return saved_results[module]
124 return wrapper
125
126
127 class ClassProperty(property):
128 def __get__(self, cls, owner):
129 return self.fget.__get__(None, owner)()
130
131
132 class multimethod(object):
133 """
134 Acts like a classmethod when invoked from the class and like an
135 instancemethod when invoked from the instance.
136 """
137 def __init__(self, func):
138 self.func = func
139
140 def __get__(self, instance, owner):
141 return (
142 functools.partial(self.func, owner) if instance is None
143 else functools.partial(self.func, owner, instance)
144 )
145
146
54 class path(unicode):
147 class path(unicode):
55 """ Represents a filesystem path.
148 """ Represents a filesystem path.
56
149
@@ -58,26 +151,45 b' class path(unicode):'
58 counterparts in os.path.
151 counterparts in os.path.
59 """
152 """
60
153
154 module = os.path
155 "The path module to use for path operations."
156
157 def __init__(self, other=''):
158 if other is None:
159 raise TypeError("Invalid initial value for path: None")
160
161 @classmethod
162 @simple_cache
163 def using_module(cls, module):
164 subclass_name = cls.__name__ + '_' + module.__name__
165 bases = (cls,)
166 ns = {'module': module}
167 return type(subclass_name, bases, ns)
168
169 @ClassProperty
170 @classmethod
171 def _next_class(cls):
172 """
173 What class should be used to construct new instances from this class
174 """
175 return cls
176
61 # --- Special Python methods.
177 # --- Special Python methods.
62
178
63 def __repr__(self):
179 def __repr__(self):
64 return 'path(%s)' % unicode.__repr__(self)
180 return '%s(%s)' % (type(self).__name__, super(path, self).__repr__())
65
181
66 # Adding a path and a string yields a path.
182 # Adding a path and a string yields a path.
67 def __add__(self, more):
183 def __add__(self, more):
68 try:
184 try:
69 resultStr = unicode.__add__(self, more)
185 return self._next_class(super(path, self).__add__(more))
70 except TypeError: #Python bug
186 except TypeError: # Python bug
71 resultStr = NotImplemented
187 return NotImplemented
72 if resultStr is NotImplemented:
73 return resultStr
74 return self.__class__(resultStr)
75
188
76 def __radd__(self, other):
189 def __radd__(self, other):
77 if isinstance(other, basestring):
190 if not isinstance(other, basestring):
78 return self.__class__(other.__add__(self))
79 else:
80 return NotImplemented
191 return NotImplemented
192 return self._next_class(other.__add__(self))
81
193
82 # The / operator joins paths.
194 # The / operator joins paths.
83 def __div__(self, rel):
195 def __div__(self, rel):
@@ -86,28 +198,50 b' class path(unicode):'
86 Join two path components, adding a separator character if
198 Join two path components, adding a separator character if
87 needed.
199 needed.
88 """
200 """
89 return self.__class__(os.path.join(self, rel))
201 return self._next_class(self.module.join(self, rel))
90
202
91 # Make the / operator work even when true division is enabled.
203 # Make the / operator work even when true division is enabled.
92 __truediv__ = __div__
204 __truediv__ = __div__
93
205
206 def __enter__(self):
207 self._old_dir = self.getcwd()
208 os.chdir(self)
209 return self
210
211 def __exit__(self, *_):
212 os.chdir(self._old_dir)
213
214 @classmethod
94 def getcwd(cls):
215 def getcwd(cls):
95 """ Return the current working directory as a path object. """
216 """ Return the current working directory as a path object. """
96 return cls(os.getcwdu())
217 return cls(os.getcwdu())
97 getcwd = classmethod(getcwd)
98
99
218
219 #
100 # --- Operations on path strings.
220 # --- Operations on path strings.
101
221
102 def isabs(s): return os.path.isabs(s)
222 def abspath(self):
103 def abspath(self): return self.__class__(os.path.abspath(self))
223 return self._next_class(self.module.abspath(self))
104 def normcase(self): return self.__class__(os.path.normcase(self))
224
105 def normpath(self): return self.__class__(os.path.normpath(self))
225 def normcase(self):
106 def realpath(self): return self.__class__(os.path.realpath(self))
226 return self._next_class(self.module.normcase(self))
107 def expanduser(self): return self.__class__(os.path.expanduser(self))
227
108 def expandvars(self): return self.__class__(os.path.expandvars(self))
228 def normpath(self):
109 def dirname(self): return self.__class__(os.path.dirname(self))
229 return self._next_class(self.module.normpath(self))
110 def basename(s): return os.path.basename(s)
230
231 def realpath(self):
232 return self._next_class(self.module.realpath(self))
233
234 def expanduser(self):
235 return self._next_class(self.module.expanduser(self))
236
237 def expandvars(self):
238 return self._next_class(self.module.expandvars(self))
239
240 def dirname(self):
241 return self._next_class(self.module.dirname(self))
242
243 def basename(self):
244 return self._next_class(self.module.basename(self))
111
245
112 def expand(self):
246 def expand(self):
113 """ Clean up a filename by calling expandvars(),
247 """ Clean up a filename by calling expandvars(),
@@ -118,23 +252,36 b' class path(unicode):'
118 """
252 """
119 return self.expandvars().expanduser().normpath()
253 return self.expandvars().expanduser().normpath()
120
254
121 def _get_namebase(self):
255 @property
122 base, ext = os.path.splitext(self.name)
256 def namebase(self):
257 """ The same as path.name, but with one file extension stripped off.
258
259 For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz',
260 but path('/home/guido/python.tar.gz').namebase == 'python.tar'
261 """
262 base, ext = self.module.splitext(self.name)
123 return base
263 return base
124
264
125 def _get_ext(self):
265 @property
126 f, ext = os.path.splitext(unicode(self))
266 def ext(self):
267 """ The file extension, for example '.py'. """
268 f, ext = self.module.splitext(self)
127 return ext
269 return ext
128
270
129 def _get_drive(self):
271 @property
130 drive, r = os.path.splitdrive(self)
272 def drive(self):
131 return self.__class__(drive)
273 """ The drive specifier, for example 'C:'.
274 This is always empty on systems that don't use drive specifiers.
275 """
276 drive, r = self.module.splitdrive(self)
277 return self._next_class(drive)
132
278
133 parent = property(
279 parent = property(
134 dirname, None, None,
280 dirname, None, None,
135 """ This path's parent directory, as a new path object.
281 """ This path's parent directory, as a new path object.
136
282
137 For example, path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib')
283 For example,
284 path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib')
138 """)
285 """)
139
286
140 name = property(
287 name = property(
@@ -144,28 +291,10 b' class path(unicode):'
144 For example, path('/usr/local/lib/libpython.so').name == 'libpython.so'
291 For example, path('/usr/local/lib/libpython.so').name == 'libpython.so'
145 """)
292 """)
146
293
147 namebase = property(
148 _get_namebase, None, None,
149 """ The same as path.name, but with one file extension stripped off.
150
151 For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz',
152 but path('/home/guido/python.tar.gz').namebase == 'python.tar'
153 """)
154
155 ext = property(
156 _get_ext, None, None,
157 """ The file extension, for example '.py'. """)
158
159 drive = property(
160 _get_drive, None, None,
161 """ The drive specifier, for example 'C:'.
162 This is always empty on systems that don't use drive specifiers.
163 """)
164
165 def splitpath(self):
294 def splitpath(self):
166 """ p.splitpath() -> Return (p.parent, p.name). """
295 """ p.splitpath() -> Return (p.parent, p.name). """
167 parent, child = os.path.split(self)
296 parent, child = self.module.split(self)
168 return self.__class__(parent), child
297 return self._next_class(parent), child
169
298
170 def splitdrive(self):
299 def splitdrive(self):
171 """ p.splitdrive() -> Return (p.drive, <the rest of p>).
300 """ p.splitdrive() -> Return (p.drive, <the rest of p>).
@@ -174,8 +303,8 b' class path(unicode):'
174 no drive specifier, p.drive is empty, so the return value
303 no drive specifier, p.drive is empty, so the return value
175 is simply (path(''), p). This is always the case on Unix.
304 is simply (path(''), p). This is always the case on Unix.
176 """
305 """
177 drive, rel = os.path.splitdrive(self)
306 drive, rel = self.module.splitdrive(self)
178 return self.__class__(drive), rel
307 return self._next_class(drive), rel
179
308
180 def splitext(self):
309 def splitext(self):
181 """ p.splitext() -> Return (p.stripext(), p.ext).
310 """ p.splitext() -> Return (p.stripext(), p.ext).
@@ -187,8 +316,8 b' class path(unicode):'
187 last path segment. This has the property that if
316 last path segment. This has the property that if
188 (a, b) == p.splitext(), then a + b == p.
317 (a, b) == p.splitext(), then a + b == p.
189 """
318 """
190 filename, ext = os.path.splitext(self)
319 filename, ext = self.module.splitext(self)
191 return self.__class__(filename), ext
320 return self._next_class(filename), ext
192
321
193 def stripext(self):
322 def stripext(self):
194 """ p.stripext() -> Remove one file extension from the path.
323 """ p.stripext() -> Remove one file extension from the path.
@@ -198,36 +327,39 b' class path(unicode):'
198 """
327 """
199 return self.splitext()[0]
328 return self.splitext()[0]
200
329
201 if hasattr(os.path, 'splitunc'):
330 def splitunc(self):
202 def splitunc(self):
331 unc, rest = self.module.splitunc(self)
203 unc, rest = os.path.splitunc(self)
332 return self._next_class(unc), rest
204 return self.__class__(unc), rest
205
206 def _get_uncshare(self):
207 unc, r = os.path.splitunc(self)
208 return self.__class__(unc)
209
333
210 uncshare = property(
334 @property
211 _get_uncshare, None, None,
335 def uncshare(self):
212 """ The UNC mount point for this path.
336 """
213 This is empty for paths on local drives. """)
337 The UNC mount point for this path.
338 This is empty for paths on local drives.
339 """
340 unc, r = self.module.splitunc(self)
341 return self._next_class(unc)
214
342
215 def joinpath(self, *args):
343 @multimethod
216 """ Join two or more path components, adding a separator
344 def joinpath(cls, first, *others):
217 character (os.sep) if needed. Returns a new path
345 """
218 object.
346 Join first to zero or more path components, adding a separator
347 character (first.module.sep) if needed. Returns a new instance of
348 first._next_class.
219 """
349 """
220 return self.__class__(os.path.join(self, *args))
350 if not isinstance(first, cls):
351 first = cls(first)
352 return first._next_class(first.module.join(first, *others))
221
353
222 def splitall(self):
354 def splitall(self):
223 r""" Return a list of the path components in this path.
355 r""" Return a list of the path components in this path.
224
356
225 The first item in the list will be a path. Its value will be
357 The first item in the list will be a path. Its value will be
226 either os.curdir, os.pardir, empty, or the root directory of
358 either os.curdir, os.pardir, empty, or the root directory of
227 this path (for example, '/' or 'C:\\'). The other items in
359 this path (for example, ``'/'`` or ``'C:\\'``). The other items in
228 the list will be strings.
360 the list will be strings.
229
361
230 path.path.joinpath(*result) will yield the original path.
362 ``path.path.joinpath(*result)`` will yield the original path.
231 """
363 """
232 parts = []
364 parts = []
233 loc = self
365 loc = self
@@ -241,11 +373,11 b' class path(unicode):'
241 parts.reverse()
373 parts.reverse()
242 return parts
374 return parts
243
375
244 def relpath(self):
376 def relpath(self, start='.'):
245 """ Return this path as a relative path,
377 """ Return this path as a relative path,
246 based from the current working directory.
378 based from start, which defaults to the current working directory.
247 """
379 """
248 cwd = self.__class__(os.getcwdu())
380 cwd = self._next_class(start)
249 return cwd.relpathto(self)
381 return cwd.relpathto(self)
250
382
251 def relpathto(self, dest):
383 def relpathto(self, dest):
@@ -256,20 +388,20 b' class path(unicode):'
256 dest.abspath().
388 dest.abspath().
257 """
389 """
258 origin = self.abspath()
390 origin = self.abspath()
259 dest = self.__class__(dest).abspath()
391 dest = self._next_class(dest).abspath()
260
392
261 orig_list = origin.normcase().splitall()
393 orig_list = origin.normcase().splitall()
262 # Don't normcase dest! We want to preserve the case.
394 # Don't normcase dest! We want to preserve the case.
263 dest_list = dest.splitall()
395 dest_list = dest.splitall()
264
396
265 if orig_list[0] != os.path.normcase(dest_list[0]):
397 if orig_list[0] != self.module.normcase(dest_list[0]):
266 # Can't get here from there.
398 # Can't get here from there.
267 return dest
399 return dest
268
400
269 # Find the location where the two paths start to differ.
401 # Find the location where the two paths start to differ.
270 i = 0
402 i = 0
271 for start_seg, dest_seg in zip(orig_list, dest_list):
403 for start_seg, dest_seg in zip(orig_list, dest_list):
272 if start_seg != os.path.normcase(dest_seg):
404 if start_seg != self.module.normcase(dest_seg):
273 break
405 break
274 i += 1
406 i += 1
275
407
@@ -283,8 +415,8 b' class path(unicode):'
283 # If they happen to be identical, use os.curdir.
415 # If they happen to be identical, use os.curdir.
284 relpath = os.curdir
416 relpath = os.curdir
285 else:
417 else:
286 relpath = os.path.join(*segments)
418 relpath = self.module.join(*segments)
287 return self.__class__(relpath)
419 return self._next_class(relpath)
288
420
289 # --- Listing, searching, walking, and matching
421 # --- Listing, searching, walking, and matching
290
422
@@ -313,7 +445,7 b' class path(unicode):'
313
445
314 With the optional 'pattern' argument, this only lists
446 With the optional 'pattern' argument, this only lists
315 directories whose names match the given pattern. For
447 directories whose names match the given pattern. For
316 example, d.dirs('build-*').
448 example, ``d.dirs('build-*')``.
317 """
449 """
318 return [p for p in self.listdir(pattern) if p.isdir()]
450 return [p for p in self.listdir(pattern) if p.isdir()]
319
451
@@ -325,9 +457,9 b' class path(unicode):'
325
457
326 With the optional 'pattern' argument, this only lists files
458 With the optional 'pattern' argument, this only lists files
327 whose names match the given pattern. For example,
459 whose names match the given pattern. For example,
328 d.files('*.pyc').
460 ``d.files('*.pyc')``.
329 """
461 """
330
462
331 return [p for p in self.listdir(pattern) if p.isfile()]
463 return [p for p in self.listdir(pattern) if p.isfile()]
332
464
333 def walk(self, pattern=None, errors='strict'):
465 def walk(self, pattern=None, errors='strict'):
@@ -388,7 +520,7 b' class path(unicode):'
388
520
389 With the optional 'pattern' argument, this yields only
521 With the optional 'pattern' argument, this yields only
390 directories whose names match the given pattern. For
522 directories whose names match the given pattern. For
391 example, mydir.walkdirs('*test') yields only directories
523 example, ``mydir.walkdirs('*test')`` yields only directories
392 with names ending in 'test'.
524 with names ending in 'test'.
393
525
394 The errors= keyword argument controls behavior when an
526 The errors= keyword argument controls behavior when an
@@ -424,7 +556,7 b' class path(unicode):'
424
556
425 The optional argument, pattern, limits the results to files
557 The optional argument, pattern, limits the results to files
426 with names that match the pattern. For example,
558 with names that match the pattern. For example,
427 mydir.walkfiles('*.tmp') yields only files with the .tmp
559 ``mydir.walkfiles('*.tmp')`` yields only files with the .tmp
428 extension.
560 extension.
429 """
561 """
430 if errors not in ('strict', 'warn', 'ignore'):
562 if errors not in ('strict', 'warn', 'ignore'):
@@ -471,7 +603,7 b' class path(unicode):'
471 """ Return True if self.name matches the given pattern.
603 """ Return True if self.name matches the given pattern.
472
604
473 pattern - A filename pattern with wildcards,
605 pattern - A filename pattern with wildcards,
474 for example '*.py'.
606 for example ``'*.py'``.
475 """
607 """
476 return fnmatch.fnmatch(self.name, pattern)
608 return fnmatch.fnmatch(self.name, pattern)
477
609
@@ -483,23 +615,40 b' class path(unicode):'
483 For example, path('/users').glob('*/bin/*') returns a list
615 For example, path('/users').glob('*/bin/*') returns a list
484 of all the files users have in their bin directories.
616 of all the files users have in their bin directories.
485 """
617 """
486 cls = self.__class__
618 cls = self._next_class
487 return [cls(s) for s in glob.glob(unicode(self / pattern))]
619 return [cls(s) for s in glob.glob(self / pattern)]
488
489
620
621 #
490 # --- Reading or writing an entire file at once.
622 # --- Reading or writing an entire file at once.
491
623
492 def open(self, mode='r'):
624 def open(self, *args, **kwargs):
493 """ Open this file. Return a file object. """
625 """ Open this file. Return a file object. """
494 return open(self, mode)
626 return open(self, *args, **kwargs)
495
627
496 def bytes(self):
628 def bytes(self):
497 """ Open this file, read all bytes, return them as a string. """
629 """ Open this file, read all bytes, return them as a string. """
498 f = self.open('rb')
630 with self.open('rb') as f:
499 try:
500 return f.read()
631 return f.read()
501 finally:
632
502 f.close()
633 def chunks(self, size, *args, **kwargs):
634 """ Returns a generator yielding chunks of the file, so it can
635 be read piece by piece with a simple for loop.
636
637 Any argument you pass after `size` will be passed to `open()`.
638
639 :example:
640
641 >>> for chunk in path("file.txt").chunk(8192):
642 ... print(chunk)
643
644 This will read the file by chunks of 8192 bytes.
645 """
646 with open(self, *args, **kwargs) as f:
647 while True:
648 d = f.read(size)
649 if not d:
650 break
651 yield d
503
652
504 def write_bytes(self, bytes, append=False):
653 def write_bytes(self, bytes, append=False):
505 """ Open this file and write the given bytes to it.
654 """ Open this file and write the given bytes to it.
@@ -511,17 +660,14 b' class path(unicode):'
511 mode = 'ab'
660 mode = 'ab'
512 else:
661 else:
513 mode = 'wb'
662 mode = 'wb'
514 f = self.open(mode)
663 with self.open(mode) as f:
515 try:
516 f.write(bytes)
664 f.write(bytes)
517 finally:
518 f.close()
519
665
520 def text(self, encoding=None, errors='strict'):
666 def text(self, encoding=None, errors='strict'):
521 r""" Open this file, read it in, return the content as a string.
667 r""" Open this file, read it in, return the content as a string.
522
668
523 This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
669 This method uses 'U' mode, so '\r\n' and '\r' are automatically
524 are automatically translated to '\n'.
670 translated to '\n'.
525
671
526 Optional arguments:
672 Optional arguments:
527
673
@@ -534,27 +680,22 b' class path(unicode):'
534 """
680 """
535 if encoding is None:
681 if encoding is None:
536 # 8-bit
682 # 8-bit
537 f = self.open('U')
683 with self.open('U') as f:
538 try:
539 return f.read()
684 return f.read()
540 finally:
541 f.close()
542 else:
685 else:
543 # Unicode
686 # Unicode
544 f = codecs.open(self, 'r', encoding, errors)
687 with codecs.open(self, 'r', encoding, errors) as f:
545 # (Note - Can't use 'U' mode here, since codecs.open
688 # (Note - Can't use 'U' mode here, since codecs.open
546 # doesn't support 'U' mode, even in Python 2.3.)
689 # doesn't support 'U' mode.)
547 try:
548 t = f.read()
690 t = f.read()
549 finally:
691 return (t.replace(u('\r\n'), u('\n'))
550 f.close()
692 .replace(u('\r\x85'), u('\n'))
551 return (t.replace(u'\r\n', u'\n')
693 .replace(u('\r'), u('\n'))
552 .replace(u'\r\x85', u'\n')
694 .replace(u('\x85'), u('\n'))
553 .replace(u'\r', u'\n')
695 .replace(u('\u2028'), u('\n')))
554 .replace(u'\x85', u'\n')
696
555 .replace(u'\u2028', u'\n'))
697 def write_text(self, text, encoding=None, errors='strict',
556
698 linesep=os.linesep, append=False):
557 def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False):
558 r""" Write the given text to this file.
699 r""" Write the given text to this file.
559
700
560 The default behavior is to overwrite any existing file;
701 The default behavior is to overwrite any existing file;
@@ -622,12 +763,12 b' class path(unicode):'
622 if linesep is not None:
763 if linesep is not None:
623 # Convert all standard end-of-line sequences to
764 # Convert all standard end-of-line sequences to
624 # ordinary newline characters.
765 # ordinary newline characters.
625 text = (text.replace(u'\r\n', u'\n')
766 text = (text.replace(u('\r\n'), u('\n'))
626 .replace(u'\r\x85', u'\n')
767 .replace(u('\r\x85'), u('\n'))
627 .replace(u'\r', u'\n')
768 .replace(u('\r'), u('\n'))
628 .replace(u'\x85', u'\n')
769 .replace(u('\x85'), u('\n'))
629 .replace(u'\u2028', u'\n'))
770 .replace(u('\u2028'), u('\n')))
630 text = text.replace(u'\n', linesep)
771 text = text.replace(u('\n'), linesep)
631 if encoding is None:
772 if encoding is None:
632 encoding = sys.getdefaultencoding()
773 encoding = sys.getdefaultencoding()
633 bytes = text.encode(encoding, errors)
774 bytes = text.encode(encoding, errors)
@@ -658,14 +799,11 b' class path(unicode):'
658 translated to '\n'. If false, newline characters are
799 translated to '\n'. If false, newline characters are
659 stripped off. Default is True.
800 stripped off. Default is True.
660
801
661 This uses 'U' mode in Python 2.3 and later.
802 This uses 'U' mode.
662 """
803 """
663 if encoding is None and retain:
804 if encoding is None and retain:
664 f = self.open('U')
805 with self.open('U') as f:
665 try:
666 return f.readlines()
806 return f.readlines()
667 finally:
668 f.close()
669 else:
807 else:
670 return self.text(encoding, errors).splitlines(retain)
808 return self.text(encoding, errors).splitlines(retain)
671
809
@@ -707,18 +845,17 b' class path(unicode):'
707 mode = 'ab'
845 mode = 'ab'
708 else:
846 else:
709 mode = 'wb'
847 mode = 'wb'
710 f = self.open(mode)
848 with self.open(mode) as f:
711 try:
712 for line in lines:
849 for line in lines:
713 isUnicode = isinstance(line, unicode)
850 isUnicode = isinstance(line, unicode)
714 if linesep is not None:
851 if linesep is not None:
715 # Strip off any existing line-end and add the
852 # Strip off any existing line-end and add the
716 # specified linesep string.
853 # specified linesep string.
717 if isUnicode:
854 if isUnicode:
718 if line[-2:] in (u'\r\n', u'\x0d\x85'):
855 if line[-2:] in (u('\r\n'), u('\x0d\x85')):
719 line = line[:-2]
856 line = line[:-2]
720 elif line[-1:] in (u'\r', u'\n',
857 elif line[-1:] in (u('\r'), u('\n'),
721 u'\x85', u'\u2028'):
858 u('\x85'), u('\u2028')):
722 line = line[:-1]
859 line = line[:-1]
723 else:
860 else:
724 if line[-2:] == '\r\n':
861 if line[-2:] == '\r\n':
@@ -731,57 +868,91 b' class path(unicode):'
731 encoding = sys.getdefaultencoding()
868 encoding = sys.getdefaultencoding()
732 line = line.encode(encoding, errors)
869 line = line.encode(encoding, errors)
733 f.write(line)
870 f.write(line)
734 finally:
735 f.close()
736
871
737 def read_md5(self):
872 def read_md5(self):
738 """ Calculate the md5 hash for this file.
873 """ Calculate the md5 hash for this file.
739
874
740 This reads through the entire file.
875 This reads through the entire file.
741 """
876 """
742 f = self.open('rb')
877 return self.read_hash('md5')
743 try:
878
744 m = md5()
879 def _hash(self, hash_name):
745 while True:
880 """ Returns a hash object for the file at the current path.
746 d = f.read(8192)
881
747 if not d:
882 `hash_name` should be a hash algo name such as 'md5' or 'sha1'
748 break
883 that's available in the `hashlib` module.
749 m.update(d)
884 """
750 finally:
885 m = hashlib.new(hash_name)
751 f.close()
886 for chunk in self.chunks(8192):
752 return m.digest()
887 m.update(chunk)
888 return m
889
890 def read_hash(self, hash_name):
891 """ Calculate given hash for this file.
892
893 List of supported hashes can be obtained from hashlib package. This
894 reads the entire file.
895 """
896 return self._hash(hash_name).digest()
897
898 def read_hexhash(self, hash_name):
899 """ Calculate given hash for this file, returning hexdigest.
900
901 List of supported hashes can be obtained from hashlib package. This
902 reads the entire file.
903 """
904 return self._hash(hash_name).hexdigest()
753
905
754 # --- Methods for querying the filesystem.
906 # --- Methods for querying the filesystem.
755 # N.B. We can't assign the functions directly, because they may on some
907 # N.B. On some platforms, the os.path functions may be implemented in C
756 # platforms be implemented in C, and compiled functions don't get bound.
908 # (e.g. isdir on Windows, Python 3.2.2), and compiled functions don't get
757 # See gh-737 for discussion of this.
909 # bound. Playing it safe and wrapping them all in method calls.
758
910
759 def exists(s): return os.path.exists(s)
911 def isabs(self):
760 def isdir(s): return os.path.isdir(s)
912 return self.module.isabs(self)
761 def isfile(s): return os.path.isfile(s)
762 def islink(s): return os.path.islink(s)
763 def ismount(s): return os.path.ismount(s)
764
913
765 if hasattr(os.path, 'samefile'):
914 def exists(self):
766 def samefile(s, o): return os.path.samefile(s, o)
915 return self.module.exists(self)
916
917 def isdir(self):
918 return self.module.isdir(self)
919
920 def isfile(self):
921 return self.module.isfile(self)
922
923 def islink(self):
924 return self.module.islink(self)
925
926 def ismount(self):
927 return self.module.ismount(self)
928
929 def samefile(self, other):
930 return self.module.samefile(self, other)
931
932 def getatime(self):
933 return self.module.getatime(self)
767
934
768 def getatime(s): return os.path.getatime(s)
769 atime = property(
935 atime = property(
770 getatime, None, None,
936 getatime, None, None,
771 """ Last access time of the file. """)
937 """ Last access time of the file. """)
772
938
773 def getmtime(s): return os.path.getmtime(s)
939 def getmtime(self):
940 return self.module.getmtime(self)
941
774 mtime = property(
942 mtime = property(
775 getmtime, None, None,
943 getmtime, None, None,
776 """ Last-modified time of the file. """)
944 """ Last-modified time of the file. """)
777
945
778 if hasattr(os.path, 'getctime'):
946 def getctime(self):
779 def getctime(s): return os.path.getctime(s)
947 return self.module.getctime(self)
780 ctime = property(
948
781 getctime, None, None,
949 ctime = property(
782 """ Creation time of the file. """)
950 getctime, None, None,
951 """ Creation time of the file. """)
952
953 def getsize(self):
954 return self.module.getsize(self)
783
955
784 def getsize(s): return os.path.getsize(s)
785 size = property(
956 size = property(
786 getsize, None, None,
957 getsize, None, None,
787 """ Size of the file, in bytes. """)
958 """ Size of the file, in bytes. """)
@@ -802,27 +973,36 b' class path(unicode):'
802 """ Like path.stat(), but do not follow symbolic links. """
973 """ Like path.stat(), but do not follow symbolic links. """
803 return os.lstat(self)
974 return os.lstat(self)
804
975
805 def get_owner(self):
976 def __get_owner_windows(self):
806 r""" Return the name of the owner of this file or directory.
977 r"""
978 Return the name of the owner of this file or directory. Follow
979 symbolic links.
807
980
808 This follows symbolic links.
981 Return a name of the form ur'DOMAIN\User Name'; may be a group.
982 """
983 desc = win32security.GetFileSecurity(
984 self, win32security.OWNER_SECURITY_INFORMATION)
985 sid = desc.GetSecurityDescriptorOwner()
986 account, domain, typecode = win32security.LookupAccountSid(None, sid)
987 return domain + u('\\') + account
809
988
810 On Windows, this returns a name of the form ur'DOMAIN\User Name'.
989 def __get_owner_unix(self):
811 On Windows, a group can own a file or directory.
812 """
990 """
813 if os.name == 'nt':
991 Return the name of the owner of this file or directory. Follow
814 if win32security is None:
992 symbolic links.
815 raise Exception("path.owner requires win32all to be installed")
993 """
816 desc = win32security.GetFileSecurity(
994 st = self.stat()
817 self, win32security.OWNER_SECURITY_INFORMATION)
995 return pwd.getpwuid(st.st_uid).pw_name
818 sid = desc.GetSecurityDescriptorOwner()
996
819 account, domain, typecode = win32security.LookupAccountSid(None, sid)
997 def __get_owner_not_implemented(self):
820 return domain + u'\\' + account
998 raise NotImplementedError("Ownership not available on this platform.")
821 else:
999
822 if pwd is None:
1000 if 'win32security' in globals():
823 raise NotImplementedError("path.owner is not implemented on this platform.")
1001 get_owner = __get_owner_windows
824 st = self.stat()
1002 elif 'pwd' in globals():
825 return pwd.getpwuid(st.st_uid).pw_name
1003 get_owner = __get_owner_unix
1004 else:
1005 get_owner = __get_owner_not_implemented
826
1006
827 owner = property(
1007 owner = property(
828 get_owner, None, None,
1008 get_owner, None, None,
@@ -837,41 +1017,85 b' class path(unicode):'
837 def pathconf(self, name):
1017 def pathconf(self, name):
838 return os.pathconf(self, name)
1018 return os.pathconf(self, name)
839
1019
840
1020 #
841 # --- Modifying operations on files and directories
1021 # --- Modifying operations on files and directories
842
1022
843 def utime(self, times):
1023 def utime(self, times):
844 """ Set the access and modified times of this file. """
1024 """ Set the access and modified times of this file. """
845 os.utime(self, times)
1025 os.utime(self, times)
1026 return self
846
1027
847 def chmod(self, mode):
1028 def chmod(self, mode):
848 os.chmod(self, mode)
1029 os.chmod(self, mode)
1030 return self
849
1031
850 if hasattr(os, 'chown'):
1032 if hasattr(os, 'chown'):
851 def chown(self, uid, gid):
1033 def chown(self, uid=-1, gid=-1):
852 os.chown(self, uid, gid)
1034 os.chown(self, uid, gid)
1035 return self
853
1036
854 def rename(self, new):
1037 def rename(self, new):
855 os.rename(self, new)
1038 os.rename(self, new)
1039 return self._next_class(new)
856
1040
857 def renames(self, new):
1041 def renames(self, new):
858 os.renames(self, new)
1042 os.renames(self, new)
1043 return self._next_class(new)
859
1044
860
1045 #
861 # --- Create/delete operations on directories
1046 # --- Create/delete operations on directories
862
1047
863 def mkdir(self, mode=0o777):
1048 def mkdir(self, mode=o777):
864 os.mkdir(self, mode)
1049 os.mkdir(self, mode)
1050 return self
1051
1052 def mkdir_p(self, mode=o777):
1053 try:
1054 self.mkdir(mode)
1055 except OSError:
1056 _, e, _ = sys.exc_info()
1057 if e.errno != errno.EEXIST:
1058 raise
1059 return self
865
1060
866 def makedirs(self, mode=0o777):
1061 def makedirs(self, mode=o777):
867 os.makedirs(self, mode)
1062 os.makedirs(self, mode)
1063 return self
1064
1065 def makedirs_p(self, mode=o777):
1066 try:
1067 self.makedirs(mode)
1068 except OSError:
1069 _, e, _ = sys.exc_info()
1070 if e.errno != errno.EEXIST:
1071 raise
1072 return self
868
1073
869 def rmdir(self):
1074 def rmdir(self):
870 os.rmdir(self)
1075 os.rmdir(self)
1076 return self
1077
1078 def rmdir_p(self):
1079 try:
1080 self.rmdir()
1081 except OSError:
1082 _, e, _ = sys.exc_info()
1083 if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST:
1084 raise
1085 return self
871
1086
872 def removedirs(self):
1087 def removedirs(self):
873 os.removedirs(self)
1088 os.removedirs(self)
1089 return self
874
1090
1091 def removedirs_p(self):
1092 try:
1093 self.removedirs()
1094 except OSError:
1095 _, e, _ = sys.exc_info()
1096 if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST:
1097 raise
1098 return self
875
1099
876 # --- Modifying operations on files
1100 # --- Modifying operations on files
877
1101
@@ -879,16 +1103,31 b' class path(unicode):'
879 """ Set the access/modified times of this file to the current time.
1103 """ Set the access/modified times of this file to the current time.
880 Create the file if it does not exist.
1104 Create the file if it does not exist.
881 """
1105 """
882 fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0o666)
1106 fd = os.open(self, os.O_WRONLY | os.O_CREAT, o666)
883 os.close(fd)
1107 os.close(fd)
884 os.utime(self, None)
1108 os.utime(self, None)
1109 return self
885
1110
886 def remove(self):
1111 def remove(self):
887 os.remove(self)
1112 os.remove(self)
1113 return self
1114
1115 def remove_p(self):
1116 try:
1117 self.unlink()
1118 except OSError:
1119 _, e, _ = sys.exc_info()
1120 if e.errno != errno.ENOENT:
1121 raise
1122 return self
888
1123
889 def unlink(self):
1124 def unlink(self):
890 os.unlink(self)
1125 os.unlink(self)
1126 return self
891
1127
1128 def unlink_p(self):
1129 self.remove_p()
1130 return self
892
1131
893 # --- Links
1132 # --- Links
894
1133
@@ -896,11 +1135,13 b' class path(unicode):'
896 def link(self, newpath):
1135 def link(self, newpath):
897 """ Create a hard link at 'newpath', pointing to this file. """
1136 """ Create a hard link at 'newpath', pointing to this file. """
898 os.link(self, newpath)
1137 os.link(self, newpath)
1138 return self._next_class(newpath)
899
1139
900 if hasattr(os, 'symlink'):
1140 if hasattr(os, 'symlink'):
901 def symlink(self, newlink):
1141 def symlink(self, newlink):
902 """ Create a symbolic link at 'newlink', pointing here. """
1142 """ Create a symbolic link at 'newlink', pointing here. """
903 os.symlink(self, newlink)
1143 os.symlink(self, newlink)
1144 return self._next_class(newlink)
904
1145
905 if hasattr(os, 'readlink'):
1146 if hasattr(os, 'readlink'):
906 def readlink(self):
1147 def readlink(self):
@@ -908,7 +1149,7 b' class path(unicode):'
908
1149
909 The result may be an absolute or a relative path.
1150 The result may be an absolute or a relative path.
910 """
1151 """
911 return self.__class__(os.readlink(self))
1152 return self._next_class(os.readlink(self))
912
1153
913 def readlinkabs(self):
1154 def readlinkabs(self):
914 """ Return the path to which this symbolic link points.
1155 """ Return the path to which this symbolic link points.
@@ -921,7 +1162,7 b' class path(unicode):'
921 else:
1162 else:
922 return (self.parent / p).abspath()
1163 return (self.parent / p).abspath()
923
1164
924
1165 #
925 # --- High-level functions from shutil
1166 # --- High-level functions from shutil
926
1167
927 copyfile = shutil.copyfile
1168 copyfile = shutil.copyfile
@@ -934,7 +1175,21 b' class path(unicode):'
934 move = shutil.move
1175 move = shutil.move
935 rmtree = shutil.rmtree
1176 rmtree = shutil.rmtree
936
1177
1178 def rmtree_p(self):
1179 try:
1180 self.rmtree()
1181 except OSError:
1182 _, e, _ = sys.exc_info()
1183 if e.errno != errno.ENOENT:
1184 raise
1185 return self
1186
1187 def chdir(self):
1188 os.chdir(self)
1189
1190 cd = chdir
937
1191
1192 #
938 # --- Special stuff from os
1193 # --- Special stuff from os
939
1194
940 if hasattr(os, 'chroot'):
1195 if hasattr(os, 'chroot'):
@@ -944,4 +1199,69 b' class path(unicode):'
944 if hasattr(os, 'startfile'):
1199 if hasattr(os, 'startfile'):
945 def startfile(self):
1200 def startfile(self):
946 os.startfile(self)
1201 os.startfile(self)
1202 return self
947
1203
1204
1205 class tempdir(path):
1206 """
1207 A temporary directory via tempfile.mkdtemp, and constructed with the
1208 same parameters that you can use as a context manager.
1209
1210 Example:
1211
1212 with tempdir() as d:
1213 # do stuff with the path object "d"
1214
1215 # here the directory is deleted automatically
1216 """
1217
1218 @ClassProperty
1219 @classmethod
1220 def _next_class(cls):
1221 return path
1222
1223 def __new__(cls, *args, **kwargs):
1224 dirname = tempfile.mkdtemp(*args, **kwargs)
1225 return super(tempdir, cls).__new__(cls, dirname)
1226
1227 def __init__(self, *args, **kwargs):
1228 pass
1229
1230 def __enter__(self):
1231 return self
1232
1233 def __exit__(self, exc_type, exc_value, traceback):
1234 if not exc_value:
1235 self.rmtree()
1236
1237
1238 def _permission_mask(mode):
1239 """
1240 Convert a Unix chmod symbolic mode like 'ugo+rwx' to a function
1241 suitable for applying to a mask to affect that change.
1242
1243 >>> mask = _permission_mask('ugo+rwx')
1244 >>> oct(mask(o554))
1245 'o777'
1246
1247 >>> oct(_permission_mask('gw-x')(o777))
1248 'o766'
1249 """
1250 parsed = re.match('(?P<who>[ugo]+)(?P<op>[-+])(?P<what>[rwx]+)$', mode)
1251 if not parsed:
1252 raise ValueError("Unrecognized symbolic mode", mode)
1253 spec_map = dict(r=4, w=2, x=1)
1254 spec = reduce(operator.or_, [spec_map[perm]
1255 for perm in parsed.group('what')])
1256 # now apply spec to each in who
1257 shift_map = dict(u=6, g=3, o=0)
1258 mask = reduce(operator.or_, [spec << shift_map[subj]
1259 for subj in parsed.group('who')])
1260
1261 op = parsed.group('op')
1262 # if op is -, invert the mask
1263 if op == '-':
1264 mask ^= o777
1265
1266 op_map = {'+': operator.or_, '-': operator.and_}
1267 return functools.partial(op_map[op], mask)
@@ -2,4 +2,4 b' try:'
2 import pexpect
2 import pexpect
3 from pexpect import *
3 from pexpect import *
4 except ImportError:
4 except ImportError:
5 from _pexpect import *
5 from ._pexpect import *
@@ -145,8 +145,11 b' class TIMEOUT(ExceptionPexpect):'
145
145
146 PY3 = (sys.version_info[0] >= 3)
146 PY3 = (sys.version_info[0] >= 3)
147
147
148 unicode_type = str if PY3 else unicode
149 basestring_type = str if PY3 else basestring
150
148 def _cast_bytes(s, enc):
151 def _cast_bytes(s, enc):
149 if isinstance(s, unicode):
152 if isinstance(s, unicode_type):
150 return s.encode(enc)
153 return s.encode(enc)
151 return s
154 return s
152
155
@@ -249,16 +252,16 b' def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None'
249 while 1:
252 while 1:
250 try:
253 try:
251 index = child.expect (patterns)
254 index = child.expect (patterns)
252 if isinstance(child.after, basestring):
255 if isinstance(child.after, basestring_type):
253 child_result_list.append(child.before + child.after)
256 child_result_list.append(child.before + child.after)
254 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
257 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
255 child_result_list.append(child.before)
258 child_result_list.append(child.before)
256 if isinstance(responses[index], basestring):
259 if isinstance(responses[index], basestring_type):
257 child.send(responses[index])
260 child.send(responses[index])
258 elif type(responses[index]) is types.FunctionType:
261 elif type(responses[index]) is types.FunctionType:
259 callback_result = responses[index](locals())
262 callback_result = responses[index](locals())
260 sys.stdout.flush()
263 sys.stdout.flush()
261 if isinstance(callback_result, basestring):
264 if isinstance(callback_result, basestring_type):
262 child.send(callback_result)
265 child.send(callback_result)
263 elif callback_result:
266 elif callback_result:
264 break
267 break
@@ -1255,7 +1258,7 b' class spawnb(object):'
1255 compile_flags = compile_flags | re.IGNORECASE
1258 compile_flags = compile_flags | re.IGNORECASE
1256 compiled_pattern_list = []
1259 compiled_pattern_list = []
1257 for p in patterns:
1260 for p in patterns:
1258 if isinstance(p, (bytes, unicode)):
1261 if isinstance(p, (bytes, unicode_type)):
1259 p = self._cast_buffer_type(p)
1262 p = self._cast_buffer_type(p)
1260 compiled_pattern_list.append(re.compile(p, compile_flags))
1263 compiled_pattern_list.append(re.compile(p, compile_flags))
1261 elif p is EOF:
1264 elif p is EOF:
@@ -1272,7 +1275,7 b' class spawnb(object):'
1272
1275
1273 def _prepare_regex_pattern(self, p):
1276 def _prepare_regex_pattern(self, p):
1274 "Recompile unicode regexes as bytes regexes. Overridden in subclass."
1277 "Recompile unicode regexes as bytes regexes. Overridden in subclass."
1275 if isinstance(p.pattern, unicode):
1278 if isinstance(p.pattern, unicode_type):
1276 p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
1279 p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
1277 return p
1280 return p
1278
1281
@@ -1384,7 +1387,7 b' class spawnb(object):'
1384 This method is also useful when you don't want to have to worry about
1387 This method is also useful when you don't want to have to worry about
1385 escaping regular expression characters that you want to match."""
1388 escaping regular expression characters that you want to match."""
1386
1389
1387 if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF):
1390 if isinstance(pattern_list, (bytes, unicode_type)) or pattern_list in (TIMEOUT, EOF):
1388 pattern_list = [pattern_list]
1391 pattern_list = [pattern_list]
1389 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1392 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1390
1393
@@ -1465,7 +1468,7 b' class spawnb(object):'
1465 """This returns the terminal window size of the child tty. The return
1468 """This returns the terminal window size of the child tty. The return
1466 value is a tuple of (rows, cols). """
1469 value is a tuple of (rows, cols). """
1467
1470
1468 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L)
1471 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
1469 s = struct.pack('HHHH', 0, 0, 0, 0)
1472 s = struct.pack('HHHH', 0, 0, 0, 0)
1470 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1473 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1471 return struct.unpack('HHHH', x)[0:2]
1474 return struct.unpack('HHHH', x)[0:2]
@@ -1487,7 +1490,7 b' class spawnb(object):'
1487 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1490 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1488 # Note that this fix is a hack.
1491 # Note that this fix is a hack.
1489 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1492 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1490 if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2.
1493 if TIOCSWINSZ == 2148037735: # L is not required in Python >= 2.2.
1491 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1494 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1492 # Note, assume ws_xpixel and ws_ypixel are zero.
1495 # Note, assume ws_xpixel and ws_ypixel are zero.
1493 s = struct.pack('HHHH', r, c, 0, 0)
1496 s = struct.pack('HHHH', r, c, 0, 0)
@@ -1608,7 +1611,7 b' class spawn(spawnb):'
1608 """This is the main class interface for Pexpect. Use this class to start
1611 """This is the main class interface for Pexpect. Use this class to start
1609 and control child applications."""
1612 and control child applications."""
1610
1613
1611 _buffer_type = unicode
1614 _buffer_type = unicode_type
1612 def _cast_buffer_type(self, s):
1615 def _cast_buffer_type(self, s):
1613 return _cast_unicode(s, self.encoding)
1616 return _cast_unicode(s, self.encoding)
1614 _empty_buffer = u''
1617 _empty_buffer = u''
@@ -1,4 +1,4 b''
1 try:
1 try:
2 from simplegeneric import *
2 from simplegeneric import *
3 except ImportError:
3 except ImportError:
4 from _simplegeneric import *
4 from ._simplegeneric import *
@@ -35,7 +35,7 b' try:'
35 except ImportError:
35 except ImportError:
36 paramiko = None
36 paramiko = None
37 else:
37 else:
38 from forward import forward_tunnel
38 from .forward import forward_tunnel
39
39
40 try:
40 try:
41 from IPython.external import pexpect
41 from IPython.external import pexpect
@@ -34,6 +34,7 b' except ImportError:'
34
34
35 from IPython.config import Application
35 from IPython.config import Application
36 from IPython.utils.path import filefind
36 from IPython.utils.path import filefind
37 from IPython.utils.py3compat import string_types
37
38
38 # UF_HIDDEN is a stat flag not defined in the stat module.
39 # UF_HIDDEN is a stat flag not defined in the stat module.
39 # It is used by BSD to indicate hidden files.
40 # It is used by BSD to indicate hidden files.
@@ -307,7 +308,7 b' class FileFindHandler(web.StaticFileHandler):'
307 _static_paths = {}
308 _static_paths = {}
308
309
309 def initialize(self, path, default_filename=None):
310 def initialize(self, path, default_filename=None):
310 if isinstance(path, basestring):
311 if isinstance(path, string_types):
311 path = [path]
312 path = [path]
312
313
313 self.root = tuple(
314 self.root = tuple(
@@ -16,7 +16,10 b' Authors:'
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import Cookie
19 try:
20 from http.cookies import SimpleCookie # Py 3
21 except ImportError:
22 from Cookie import SimpleCookie # Py 2
20 import logging
23 import logging
21 from tornado import web
24 from tornado import web
22 from tornado import websocket
25 from tornado import websocket
@@ -102,7 +105,7 b' class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):'
102 logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
105 logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
103
106
104 try:
107 try:
105 self.request._cookies = Cookie.SimpleCookie(msg)
108 self.request._cookies = SimpleCookie(msg)
106 except:
109 except:
107 self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True)
110 self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True)
108
111
@@ -16,16 +16,12 b' Authors:'
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import os
20 import json
21
22 from tornado import web
19 from tornado import web
23 HTTPError = web.HTTPError
20 HTTPError = web.HTTPError
24
21
25 from ..base.handlers import IPythonHandler
22 from ..base.handlers import IPythonHandler
26 from ..services.notebooks.handlers import _notebook_path_regex, _path_regex
23 from ..services.notebooks.handlers import _notebook_path_regex, _path_regex
27 from ..utils import url_path_join, url_escape, url_unescape
24 from ..utils import url_path_join, url_escape
28 from urllib import quote
29
25
30 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
31 # Handlers
27 # Handlers
@@ -5,6 +5,7 b' Authors:'
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8 from __future__ import print_function
8 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
9 # Copyright (C) 2013 The IPython Development Team
10 # Copyright (C) 2013 The IPython Development Team
10 #
11 #
@@ -628,7 +629,7 b' class NotebookApp(BaseIPythonApplication):'
628 time.sleep(0.1)
629 time.sleep(0.1)
629 info = self.log.info
630 info = self.log.info
630 info('interrupted')
631 info('interrupted')
631 print self.notebook_info()
632 print(self.notebook_info())
632 sys.stdout.write("Shutdown this notebook server (y/[n])? ")
633 sys.stdout.write("Shutdown this notebook server (y/[n])? ")
633 sys.stdout.flush()
634 sys.stdout.flush()
634 r,w,x = select.select([sys.stdin], [], [], 5)
635 r,w,x = select.select([sys.stdin], [], [], 5)
@@ -639,8 +640,8 b' class NotebookApp(BaseIPythonApplication):'
639 ioloop.IOLoop.instance().stop()
640 ioloop.IOLoop.instance().stop()
640 return
641 return
641 else:
642 else:
642 print "No answer for 5s:",
643 print("No answer for 5s:", end=' ')
643 print "resuming operation..."
644 print("resuming operation...")
644 # no answer, or answer is no:
645 # no answer, or answer is no:
645 # set it back to original SIGINT handler
646 # set it back to original SIGINT handler
646 # use IOLoop.add_callback because signal.signal must be called
647 # use IOLoop.add_callback because signal.signal must be called
@@ -652,7 +653,7 b' class NotebookApp(BaseIPythonApplication):'
652 ioloop.IOLoop.instance().stop()
653 ioloop.IOLoop.instance().stop()
653
654
654 def _signal_info(self, sig, frame):
655 def _signal_info(self, sig, frame):
655 print self.notebook_info()
656 print(self.notebook_info())
656
657
657 def init_components(self):
658 def init_components(self):
658 """Check the components submodule, and warn if it's unclean"""
659 """Check the components submodule, and warn if it's unclean"""
@@ -1,5 +1,6 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Tests for the notebook manager."""
2 """Tests for the notebook manager."""
3 from __future__ import print_function
3
4
4 import os
5 import os
5
6
@@ -66,7 +67,7 b' class TestNotebookManager(TestCase):'
66 try:
67 try:
67 os.makedirs(os_path)
68 os.makedirs(os_path)
68 except OSError:
69 except OSError:
69 print "Directory already exists."
70 print("Directory already exists.")
70
71
71 def test_create_notebook_model(self):
72 def test_create_notebook_model(self):
72 with TemporaryDirectory() as td:
73 with TemporaryDirectory() as td:
@@ -22,6 +22,7 b' import sqlite3'
22 from tornado import web
22 from tornado import web
23
23
24 from IPython.config.configurable import LoggingConfigurable
24 from IPython.config.configurable import LoggingConfigurable
25 from IPython.utils.py3compat import unicode_type
25
26
26 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
27 # Classes
28 # Classes
@@ -66,7 +67,7 b' class SessionManager(LoggingConfigurable):'
66
67
67 def new_session_id(self):
68 def new_session_id(self):
68 "Create a uuid for a new session"
69 "Create a uuid for a new session"
69 return unicode(uuid.uuid4())
70 return unicode_type(uuid.uuid4())
70
71
71 def create_session(self, name=None, path=None, kernel_id=None, ws_url=None):
72 def create_session(self, name=None, path=None, kernel_id=None, ws_url=None):
72 """Creates a session and returns its model"""
73 """Creates a session and returns its model"""
@@ -132,7 +133,7 b' class SessionManager(LoggingConfigurable):'
132
133
133 query = "SELECT * FROM session WHERE %s" % (' AND '.join(conditions))
134 query = "SELECT * FROM session WHERE %s" % (' AND '.join(conditions))
134
135
135 self.cursor.execute(query, kwargs.values())
136 self.cursor.execute(query, list(kwargs.values()))
136 model = self.cursor.fetchone()
137 model = self.cursor.fetchone()
137 if model is None:
138 if model is None:
138 q = []
139 q = []
@@ -169,7 +170,7 b' class SessionManager(LoggingConfigurable):'
169 raise TypeError("No such column: %r" % column)
170 raise TypeError("No such column: %r" % column)
170 sets.append("%s=?" % column)
171 sets.append("%s=?" % column)
171 query = "UPDATE session SET %s WHERE session_id=?" % (', '.join(sets))
172 query = "UPDATE session SET %s WHERE session_id=?" % (', '.join(sets))
172 self.cursor.execute(query, kwargs.values() + [session_id])
173 self.cursor.execute(query, list(kwargs.values()) + [session_id])
173
174
174 @staticmethod
175 @staticmethod
175 def row_factory(cursor, row):
176 def row_factory(cursor, row):
@@ -1,5 +1,6 b''
1 """Test the sessions web service API."""
1 """Test the sessions web service API."""
2
2
3 import errno
3 import io
4 import io
4 import os
5 import os
5 import json
6 import json
@@ -51,7 +52,12 b' class SessionAPITest(NotebookTestBase):'
51 """Test the sessions web service API"""
52 """Test the sessions web service API"""
52 def setUp(self):
53 def setUp(self):
53 nbdir = self.notebook_dir.name
54 nbdir = self.notebook_dir.name
54 os.mkdir(pjoin(nbdir, 'foo'))
55 try:
56 os.mkdir(pjoin(nbdir, 'foo'))
57 except OSError as e:
58 # Deleting the folder in an earlier test may have failed
59 if e.errno != errno.EEXIST:
60 raise
55
61
56 with io.open(pjoin(nbdir, 'foo', 'nb1.ipynb'), 'w') as f:
62 with io.open(pjoin(nbdir, 'foo', 'nb1.ipynb'), 'w') as f:
57 nb = new_notebook(name='nb1')
63 nb = new_notebook(name='nb1')
@@ -62,7 +68,8 b' class SessionAPITest(NotebookTestBase):'
62 def tearDown(self):
68 def tearDown(self):
63 for session in self.sess_api.list().json():
69 for session in self.sess_api.list().json():
64 self.sess_api.delete(session['id'])
70 self.sess_api.delete(session['id'])
65 shutil.rmtree(pjoin(self.notebook_dir.name, 'foo'))
71 shutil.rmtree(pjoin(self.notebook_dir.name, 'foo'),
72 ignore_errors=True)
66
73
67 def test_create(self):
74 def test_create(self):
68 sessions = self.sess_api.list().json()
75 sessions = self.sess_api.list().json()
@@ -13,7 +13,10 b' Authors:'
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 from urllib import quote, unquote
16 try:
17 from urllib.parse import quote, unquote
18 except ImportError:
19 from urllib import quote, unquote
17
20
18 from IPython.utils import py3compat
21 from IPython.utils import py3compat
19
22
@@ -13,7 +13,10 b' Useful for test suites and blocking terminal interfaces.'
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import Queue
16 try:
17 from queue import Queue, Empty # Py 3
18 except ImportError:
19 from Queue import Queue, Empty # Py 2
17
20
18 from IPython.kernel.channels import IOPubChannel, HBChannel, \
21 from IPython.kernel.channels import IOPubChannel, HBChannel, \
19 ShellChannel, StdInChannel
22 ShellChannel, StdInChannel
@@ -27,7 +30,7 b' class BlockingChannelMixin(object):'
27
30
28 def __init__(self, *args, **kwds):
31 def __init__(self, *args, **kwds):
29 super(BlockingChannelMixin, self).__init__(*args, **kwds)
32 super(BlockingChannelMixin, self).__init__(*args, **kwds)
30 self._in_queue = Queue.Queue()
33 self._in_queue = Queue()
31
34
32 def call_handlers(self, msg):
35 def call_handlers(self, msg):
33 self._in_queue.put(msg)
36 self._in_queue.put(msg)
@@ -46,7 +49,7 b' class BlockingChannelMixin(object):'
46 while True:
49 while True:
47 try:
50 try:
48 msgs.append(self.get_msg(block=False))
51 msgs.append(self.get_msg(block=False))
49 except Queue.Empty:
52 except Empty:
50 break
53 break
51 return msgs
54 return msgs
52
55
@@ -31,6 +31,7 b' from .channelsabc import ('
31 ShellChannelABC, IOPubChannelABC,
31 ShellChannelABC, IOPubChannelABC,
32 HBChannelABC, StdInChannelABC,
32 HBChannelABC, StdInChannelABC,
33 )
33 )
34 from IPython.utils.py3compat import string_types, iteritems
34
35
35 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
36 # Constants and exceptions
37 # Constants and exceptions
@@ -53,7 +54,7 b' def validate_string_list(lst):'
53 if not isinstance(lst, list):
54 if not isinstance(lst, list):
54 raise ValueError('input %r must be a list' % lst)
55 raise ValueError('input %r must be a list' % lst)
55 for x in lst:
56 for x in lst:
56 if not isinstance(x, basestring):
57 if not isinstance(x, string_types):
57 raise ValueError('element %r in list must be a string' % x)
58 raise ValueError('element %r in list must be a string' % x)
58
59
59
60
@@ -61,10 +62,10 b' def validate_string_dict(dct):'
61 """Validate that the input is a dict with string keys and values.
62 """Validate that the input is a dict with string keys and values.
62
63
63 Raises ValueError if not."""
64 Raises ValueError if not."""
64 for k,v in dct.iteritems():
65 for k,v in iteritems(dct):
65 if not isinstance(k, basestring):
66 if not isinstance(k, string_types):
66 raise ValueError('key %r in dict must be a string' % k)
67 raise ValueError('key %r in dict must be a string' % k)
67 if not isinstance(v, basestring):
68 if not isinstance(v, string_types):
68 raise ValueError('value %r in dict must be a string' % v)
69 raise ValueError('value %r in dict must be a string' % v)
69
70
70
71
@@ -264,7 +265,7 b' class ShellChannel(ZMQSocketChannel):'
264
265
265
266
266 # Don't waste network traffic if inputs are invalid
267 # Don't waste network traffic if inputs are invalid
267 if not isinstance(code, basestring):
268 if not isinstance(code, string_types):
268 raise ValueError('code %r must be a string' % code)
269 raise ValueError('code %r must be a string' % code)
269 validate_string_list(user_variables)
270 validate_string_list(user_variables)
270 validate_string_dict(user_expressions)
271 validate_string_dict(user_expressions)
@@ -444,7 +445,7 b' class IOPubChannel(ZMQSocketChannel):'
444 # We do the IOLoop callback process twice to ensure that the IOLoop
445 # We do the IOLoop callback process twice to ensure that the IOLoop
445 # gets to perform at least one full poll.
446 # gets to perform at least one full poll.
446 stop_time = time.time() + timeout
447 stop_time = time.time() + timeout
447 for i in xrange(2):
448 for i in range(2):
448 self._flushed = False
449 self._flushed = False
449 self.ioloop.add_callback(self._flush)
450 self.ioloop.add_callback(self._flush)
450 while not self._flushed and time.time() < stop_time:
451 while not self._flushed and time.time() < stop_time:
@@ -11,19 +11,18 b''
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 # Standard library imports
15 import abc
14 import abc
16
15
16 from IPython.utils.py3compat import with_metaclass
17
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18 # Channels
19 # Channels
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20
21
21
22
22 class ChannelABC(object):
23 class ChannelABC(with_metaclass(abc.ABCMeta, object)):
23 """A base class for all channel ABCs."""
24 """A base class for all channel ABCs."""
24
25
25 __metaclass__ = abc.ABCMeta
26
27 @abc.abstractmethod
26 @abc.abstractmethod
28 def start(self):
27 def start(self):
29 pass
28 pass
@@ -11,14 +11,15 b''
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 # Standard library imports
15 import abc
14 import abc
16
15
16 from IPython.utils.py3compat import with_metaclass
17
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18 # Main kernel client class
19 # Main kernel client class
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20
21
21 class KernelClientABC(object):
22 class KernelClientABC(with_metaclass(abc.ABCMeta, object)):
22 """KernelManager ABC.
23 """KernelManager ABC.
23
24
24 The docstrings for this class can be found in the base implementation:
25 The docstrings for this class can be found in the base implementation:
@@ -26,8 +27,6 b' class KernelClientABC(object):'
26 `IPython.kernel.client.KernelClient`
27 `IPython.kernel.client.KernelClient`
27 """
28 """
28
29
29 __metaclass__ = abc.ABCMeta
30
31 @abc.abstractproperty
30 @abc.abstractproperty
32 def kernel(self):
31 def kernel(self):
33 pass
32 pass
@@ -18,6 +18,7 b' from IPython.core.prompts import LazyEvaluate'
18 from IPython.core.getipython import get_ipython
18 from IPython.core.getipython import get_ipython
19
19
20 from IPython.utils.importstring import import_item
20 from IPython.utils.importstring import import_item
21 from IPython.utils.py3compat import string_types
21 from IPython.utils.traitlets import Instance, Unicode, Dict, Any
22 from IPython.utils.traitlets import Instance, Unicode, Dict, Any
22
23
23 from .comm import Comm
24 from .comm import Comm
@@ -86,7 +87,7 b' class CommManager(LoggingConfigurable):'
86
87
87 f can be a Python callable or an import string for one.
88 f can be a Python callable or an import string for one.
88 """
89 """
89 if isinstance(f, basestring):
90 if isinstance(f, string_types):
90 f = import_item(f)
91 f = import_item(f)
91
92
92 self.targets[target_name] = f
93 self.targets[target_name] = f
@@ -38,7 +38,8 b' from IPython.config import Configurable'
38 from IPython.core.profiledir import ProfileDir
38 from IPython.core.profiledir import ProfileDir
39 from IPython.utils.localinterfaces import localhost
39 from IPython.utils.localinterfaces import localhost
40 from IPython.utils.path import filefind, get_ipython_dir
40 from IPython.utils.path import filefind, get_ipython_dir
41 from IPython.utils.py3compat import str_to_bytes, bytes_to_str, cast_bytes_py2
41 from IPython.utils.py3compat import (str_to_bytes, bytes_to_str, cast_bytes_py2,
42 string_types)
42 from IPython.utils.traitlets import (
43 from IPython.utils.traitlets import (
43 Bool, Integer, Unicode, CaselessStrEnum,
44 Bool, Integer, Unicode, CaselessStrEnum,
44 )
45 )
@@ -347,7 +348,7 b' def tunnel_to_kernel(connection_info, sshserver, sshkey=None):'
347 (shell, iopub, stdin, hb) : ints
348 (shell, iopub, stdin, hb) : ints
348 The four ports on localhost that have been forwarded to the kernel.
349 The four ports on localhost that have been forwarded to the kernel.
349 """
350 """
350 if isinstance(connection_info, basestring):
351 if isinstance(connection_info, string_types):
351 # it's a path, unpack it
352 # it's a path, unpack it
352 with open(connection_info) as f:
353 with open(connection_info) as f:
353 connection_info = json.loads(f.read())
354 connection_info = json.loads(f.read())
@@ -13,21 +13,23 b''
13
13
14 # Standard library imports.
14 # Standard library imports.
15 import abc
15 import abc
16 import Queue
16 try:
17 from queue import Queue # Py 3
18 except ImportError:
19 from Queue import Queue # Py 2
17
20
18 # System library imports.
21 # System library imports.
19 import zmq
22 import zmq
20
23
21 # Local imports.
24 # Local imports.
22 from IPython.utils.traitlets import HasTraits, Instance, Int
25 from IPython.utils.traitlets import HasTraits, Instance, Int
26 from IPython.utils.py3compat import with_metaclass
23
27
24 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
25 # Generic socket interface
29 # Generic socket interface
26 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
27
31
28 class SocketABC(object):
32 class SocketABC(with_metaclass(abc.ABCMeta, object)):
29 __metaclass__ = abc.ABCMeta
30
31 @abc.abstractmethod
33 @abc.abstractmethod
32 def recv_multipart(self, flags=0, copy=True, track=False):
34 def recv_multipart(self, flags=0, copy=True, track=False):
33 raise NotImplementedError
35 raise NotImplementedError
@@ -45,7 +47,7 b' SocketABC.register(zmq.Socket)'
45 class DummySocket(HasTraits):
47 class DummySocket(HasTraits):
46 """ A dummy socket implementing (part of) the zmq.Socket interface. """
48 """ A dummy socket implementing (part of) the zmq.Socket interface. """
47
49
48 queue = Instance(Queue.Queue, ())
50 queue = Instance(Queue, ())
49 message_sent = Int(0) # Should be an Event
51 message_sent = Int(0) # Should be an Event
50
52
51 #-------------------------------------------------------------------------
53 #-------------------------------------------------------------------------
@@ -56,7 +58,7 b' class DummySocket(HasTraits):'
56 return self.queue.get_nowait()
58 return self.queue.get_nowait()
57
59
58 def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
60 def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
59 msg_parts = map(zmq.Message, msg_parts)
61 msg_parts = list(map(zmq.Message, msg_parts))
60 self.queue.put_nowait(msg_parts)
62 self.queue.put_nowait(msg_parts)
61 self.message_sent += 1
63 self.message_sent += 1
62
64
@@ -11,7 +11,6 b''
11 from __future__ import print_function
11 from __future__ import print_function
12
12
13 # Standard library imports
13 # Standard library imports
14 from StringIO import StringIO
15 import sys
14 import sys
16 import unittest
15 import unittest
17
16
@@ -23,6 +22,11 b' from IPython.testing.decorators import skipif_not_matplotlib'
23 from IPython.utils.io import capture_output
22 from IPython.utils.io import capture_output
24 from IPython.utils import py3compat
23 from IPython.utils import py3compat
25
24
25 if py3compat.PY3:
26 from io import StringIO
27 else:
28 from StringIO import StringIO
29
26 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
27 # Test case
31 # Test case
28 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
@@ -11,19 +11,18 b''
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 # Standard library imports.
15 import abc
14 import abc
16
15
16 from IPython.utils.py3compat import with_metaclass
17
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18 # Channels
19 # Channels
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20
21
21
22
22 class ChannelABC(object):
23 class ChannelABC(with_metaclass(abc.ABCMeta, object)):
23 """A base class for all channel ABCs."""
24 """A base class for all channel ABCs."""
24
25
25 __metaclass__ = abc.ABCMeta
26
27 @abc.abstractmethod
26 @abc.abstractmethod
28 def start(self):
27 def start(self):
29 pass
28 pass
@@ -130,7 +129,7 b' class HBChannelABC(ChannelABC):'
130 # Main kernel manager class
129 # Main kernel manager class
131 #-----------------------------------------------------------------------------
130 #-----------------------------------------------------------------------------
132
131
133 class KernelManagerABC(object):
132 class KernelManagerABC(with_metaclass(abc.ABCMeta, object)):
134 """KernelManager ABC.
133 """KernelManager ABC.
135
134
136 The docstrings for this class can be found in the base implementation:
135 The docstrings for this class can be found in the base implementation:
@@ -138,8 +137,6 b' class KernelManagerABC(object):'
138 `IPython.kernel.kernelmanager.KernelManager`
137 `IPython.kernel.kernelmanager.KernelManager`
139 """
138 """
140
139
141 __metaclass__ = abc.ABCMeta
142
143 @abc.abstractproperty
140 @abc.abstractproperty
144 def kernel(self):
141 def kernel(self):
145 pass
142 pass
@@ -28,6 +28,7 b' from IPython.utils.importstring import import_item'
28 from IPython.utils.traitlets import (
28 from IPython.utils.traitlets import (
29 Instance, Dict, Unicode, Any, DottedObjectName
29 Instance, Dict, Unicode, Any, DottedObjectName
30 )
30 )
31 from IPython.utils.py3compat import unicode_type
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Classes
34 # Classes
@@ -102,7 +103,7 b' class MultiKernelManager(LoggingConfigurable):'
102 km.start_kernel(stdout=PIPE, stderr=PIPE)
103 km.start_kernel(stdout=PIPE, stderr=PIPE)
103
104
104 """
105 """
105 kernel_id = kwargs.pop('kernel_id', unicode(uuid.uuid4()))
106 kernel_id = kwargs.pop('kernel_id', unicode_type(uuid.uuid4()))
106 if kernel_id in self:
107 if kernel_id in self:
107 raise DuplicateKernelError('Kernel already exists: %s' % kernel_id)
108 raise DuplicateKernelError('Kernel already exists: %s' % kernel_id)
108 # kernel_manager_factory is the constructor for the KernelManager
109 # kernel_manager_factory is the constructor for the KernelManager
@@ -9,7 +9,10 b''
9
9
10 import re
10 import re
11 from subprocess import PIPE
11 from subprocess import PIPE
12 from Queue import Empty
12 try:
13 from queue import Empty # Py 3
14 except ImportError:
15 from Queue import Empty # Py 2
13
16
14 import nose.tools as nt
17 import nose.tools as nt
15
18
@@ -18,6 +21,7 b' from IPython.kernel import KernelManager'
18 from IPython.utils.traitlets import (
21 from IPython.utils.traitlets import (
19 HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum, Any,
22 HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum, Any,
20 )
23 )
24 from IPython.utils.py3compat import string_types, iteritems
21
25
22 from .utils import TIMEOUT, start_global_kernel, flush_channels, execute
26 from .utils import TIMEOUT, start_global_kernel, flush_channels, execute
23
27
@@ -155,7 +159,7 b' class KernelInfoReply(Reference):'
155
159
156 def _ipython_version_changed(self, name, old, new):
160 def _ipython_version_changed(self, name, old, new):
157 for v in new:
161 for v in new:
158 assert isinstance(v, int) or isinstance(v, basestring), \
162 assert isinstance(v, int) or isinstance(v, string_types), \
159 'expected int or string as version component, got {0!r}'.format(v)
163 'expected int or string as version component, got {0!r}'.format(v)
160
164
161
165
@@ -181,18 +185,18 b' class DisplayData(Reference):'
181 metadata = Dict()
185 metadata = Dict()
182 data = Dict()
186 data = Dict()
183 def _data_changed(self, name, old, new):
187 def _data_changed(self, name, old, new):
184 for k,v in new.iteritems():
188 for k,v in iteritems(new):
185 assert mime_pat.match(k)
189 assert mime_pat.match(k)
186 nt.assert_is_instance(v, basestring)
190 nt.assert_is_instance(v, string_types)
187
191
188
192
189 class PyOut(Reference):
193 class PyOut(Reference):
190 execution_count = Integer()
194 execution_count = Integer()
191 data = Dict()
195 data = Dict()
192 def _data_changed(self, name, old, new):
196 def _data_changed(self, name, old, new):
193 for k,v in new.iteritems():
197 for k,v in iteritems(new):
194 assert mime_pat.match(k)
198 assert mime_pat.match(k)
195 nt.assert_is_instance(v, basestring)
199 nt.assert_is_instance(v, string_types)
196
200
197
201
198 references = {
202 references = {
@@ -15,7 +15,10 b' import atexit'
15
15
16 from contextlib import contextmanager
16 from contextlib import contextmanager
17 from subprocess import PIPE, STDOUT
17 from subprocess import PIPE, STDOUT
18 from Queue import Empty
18 try:
19 from queue import Empty # Py 3
20 except ImportError:
21 from Queue import Empty # Py 2
19
22
20 import nose
23 import nose
21 import nose.tools as nt
24 import nose.tools as nt
@@ -1,11 +1,11 b''
1 import __builtin__
2 import sys
1 import sys
3
2
4 from IPython.core.displayhook import DisplayHook
3 from IPython.core.displayhook import DisplayHook
5 from IPython.kernel.inprocess.socket import SocketABC
4 from IPython.kernel.inprocess.socket import SocketABC
6 from IPython.utils.jsonutil import encode_images
5 from IPython.utils.jsonutil import encode_images
6 from IPython.utils.py3compat import builtin_mod
7 from IPython.utils.traitlets import Instance, Dict
7 from IPython.utils.traitlets import Instance, Dict
8 from session import extract_header, Session
8 from .session import extract_header, Session
9
9
10 class ZMQDisplayHook(object):
10 class ZMQDisplayHook(object):
11 """A simple displayhook that publishes the object's repr over a ZeroMQ
11 """A simple displayhook that publishes the object's repr over a ZeroMQ
@@ -21,7 +21,7 b' class ZMQDisplayHook(object):'
21 if obj is None:
21 if obj is None:
22 return
22 return
23
23
24 __builtin__._ = obj
24 builtin_mod._ = obj
25 sys.stdout.flush()
25 sys.stdout.flush()
26 sys.stderr.flush()
26 sys.stderr.flush()
27 msg = self.session.send(self.pub_socket, u'pyout', {u'data':repr(obj)},
27 msg = self.session.send(self.pub_socket, u'pyout', {u'data':repr(obj)},
@@ -8,7 +8,7 b' import sys'
8
8
9 from IPython.utils.frame import extract_module_locals
9 from IPython.utils.frame import extract_module_locals
10
10
11 from kernelapp import IPKernelApp
11 from .kernelapp import IPKernelApp
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Code
14 # Code
@@ -92,14 +92,17 b' def loop_wx(kernel):'
92 def loop_tk(kernel):
92 def loop_tk(kernel):
93 """Start a kernel with the Tk event loop."""
93 """Start a kernel with the Tk event loop."""
94
94
95 import Tkinter
95 try:
96 from tkinter import Tk # Py 3
97 except ImportError:
98 from Tkinter import Tk # Py 2
96 doi = kernel.do_one_iteration
99 doi = kernel.do_one_iteration
97 # Tk uses milliseconds
100 # Tk uses milliseconds
98 poll_interval = int(1000*kernel._poll_interval)
101 poll_interval = int(1000*kernel._poll_interval)
99 # For Tkinter, we create a Tk object and call its withdraw method.
102 # For Tkinter, we create a Tk object and call its withdraw method.
100 class Timer(object):
103 class Timer(object):
101 def __init__(self, func):
104 def __init__(self, func):
102 self.app = Tkinter.Tk()
105 self.app = Tk()
103 self.app.withdraw()
106 self.app.withdraw()
104 self.func = func
107 self.func = func
105
108
@@ -16,9 +16,10 b' from io import StringIO, UnsupportedOperation'
16
16
17 import zmq
17 import zmq
18
18
19 from session import extract_header
19 from .session import extract_header
20
20
21 from IPython.utils import py3compat
21 from IPython.utils import py3compat
22 from IPython.utils.py3compat import unicode_type
22
23
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
24 # Globals
25 # Globals
@@ -180,7 +181,7 b' class OutStream(object):'
180 raise ValueError('I/O operation on closed file')
181 raise ValueError('I/O operation on closed file')
181 else:
182 else:
182 # Make sure that we're handling unicode
183 # Make sure that we're handling unicode
183 if not isinstance(string, unicode):
184 if not isinstance(string, unicode_type):
184 string = string.decode(self.encoding, 'replace')
185 string = string.decode(self.encoding, 'replace')
185
186
186 is_child = (self._check_mp_mode() == CHILD)
187 is_child = (self._check_mp_mode() == CHILD)
@@ -7,7 +7,6 b''
7 from __future__ import print_function
7 from __future__ import print_function
8
8
9 # Standard library imports
9 # Standard library imports
10 import __builtin__
11 import sys
10 import sys
12 import time
11 import time
13 import traceback
12 import traceback
@@ -29,15 +28,16 b' from IPython.config.configurable import Configurable'
29 from IPython.core.error import StdinNotImplementedError
28 from IPython.core.error import StdinNotImplementedError
30 from IPython.core import release
29 from IPython.core import release
31 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.py3compat import builtin_mod, unicode_type, string_types
32 from IPython.utils.jsonutil import json_clean
32 from IPython.utils.jsonutil import json_clean
33 from IPython.utils.traitlets import (
33 from IPython.utils.traitlets import (
34 Any, Instance, Float, Dict, List, Set, Integer, Unicode,
34 Any, Instance, Float, Dict, List, Set, Integer, Unicode,
35 Type
35 Type
36 )
36 )
37
37
38 from serialize import serialize_object, unpack_apply_message
38 from .serialize import serialize_object, unpack_apply_message
39 from session import Session
39 from .session import Session
40 from zmqshell import ZMQInteractiveShell
40 from .zmqshell import ZMQInteractiveShell
41
41
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
@@ -89,7 +89,7 b' class Kernel(Configurable):'
89 ident = Unicode()
89 ident = Unicode()
90
90
91 def _ident_default(self):
91 def _ident_default(self):
92 return unicode(uuid.uuid4())
92 return unicode_type(uuid.uuid4())
93
93
94
94
95 # Private interface
95 # Private interface
@@ -356,13 +356,13 b' class Kernel(Configurable):'
356 raw_input = input = lambda prompt='' : self._no_raw_input()
356 raw_input = input = lambda prompt='' : self._no_raw_input()
357
357
358 if py3compat.PY3:
358 if py3compat.PY3:
359 self._sys_raw_input = __builtin__.input
359 self._sys_raw_input = builtin_mod.input
360 __builtin__.input = raw_input
360 builtin_mod.input = raw_input
361 else:
361 else:
362 self._sys_raw_input = __builtin__.raw_input
362 self._sys_raw_input = builtin_mod.raw_input
363 self._sys_eval_input = __builtin__.input
363 self._sys_eval_input = builtin_mod.input
364 __builtin__.raw_input = raw_input
364 builtin_mod.raw_input = raw_input
365 __builtin__.input = input
365 builtin_mod.input = input
366
366
367 # Set the parent message of the display hook and out streams.
367 # Set the parent message of the display hook and out streams.
368 shell.set_parent(parent)
368 shell.set_parent(parent)
@@ -392,10 +392,10 b' class Kernel(Configurable):'
392 finally:
392 finally:
393 # Restore raw_input.
393 # Restore raw_input.
394 if py3compat.PY3:
394 if py3compat.PY3:
395 __builtin__.input = self._sys_raw_input
395 builtin_mod.input = self._sys_raw_input
396 else:
396 else:
397 __builtin__.raw_input = self._sys_raw_input
397 builtin_mod.raw_input = self._sys_raw_input
398 __builtin__.input = self._sys_eval_input
398 builtin_mod.input = self._sys_eval_input
399
399
400 reply_content[u'status'] = status
400 reply_content[u'status'] = status
401
401
@@ -596,10 +596,10 b' class Kernel(Configurable):'
596 working.update(ns)
596 working.update(ns)
597 code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname)
597 code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname)
598 try:
598 try:
599 exec code in shell.user_global_ns, shell.user_ns
599 exec(code, shell.user_global_ns, shell.user_ns)
600 result = working.get(resultname)
600 result = working.get(resultname)
601 finally:
601 finally:
602 for key in ns.iterkeys():
602 for key in ns:
603 working.pop(key)
603 working.pop(key)
604
604
605 result_buf = serialize_object(result,
605 result_buf = serialize_object(result,
@@ -649,7 +649,7 b' class Kernel(Configurable):'
649 def abort_request(self, stream, ident, parent):
649 def abort_request(self, stream, ident, parent):
650 """abort a specifig msg by id"""
650 """abort a specifig msg by id"""
651 msg_ids = parent['content'].get('msg_ids', None)
651 msg_ids = parent['content'].get('msg_ids', None)
652 if isinstance(msg_ids, basestring):
652 if isinstance(msg_ids, string_types):
653 msg_ids = [msg_ids]
653 msg_ids = [msg_ids]
654 if not msg_ids:
654 if not msg_ids:
655 self.abort_queues()
655 self.abort_queues()
@@ -50,13 +50,13 b' from IPython.utils.importstring import import_item'
50 from IPython.kernel import write_connection_file
50 from IPython.kernel import write_connection_file
51
51
52 # local imports
52 # local imports
53 from heartbeat import Heartbeat
53 from .heartbeat import Heartbeat
54 from ipkernel import Kernel
54 from .ipkernel import Kernel
55 from parentpoller import ParentPollerUnix, ParentPollerWindows
55 from .parentpoller import ParentPollerUnix, ParentPollerWindows
56 from session import (
56 from .session import (
57 Session, session_flags, session_aliases, default_secure,
57 Session, session_flags, session_aliases, default_secure,
58 )
58 )
59 from zmqshell import ZMQInteractiveShell
59 from .zmqshell import ZMQInteractiveShell
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 # Flags and Aliases
62 # Flags and Aliases
@@ -6,7 +6,10 b' except:'
6 import os
6 import os
7 import platform
7 import platform
8 import time
8 import time
9 from thread import interrupt_main
9 try:
10 from _thread import interrupt_main # Py 3
11 except ImportError:
12 from thread import interrupt_main # Py 2
10 from threading import Thread
13 from threading import Thread
11
14
12 from IPython.utils.warn import warn
15 from IPython.utils.warn import warn
@@ -91,7 +91,7 b' def serialize_object(obj, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS):'
91 buffers.extend(_extract_buffers(c, buffer_threshold))
91 buffers.extend(_extract_buffers(c, buffer_threshold))
92 elif istype(obj, dict) and len(obj) < item_threshold:
92 elif istype(obj, dict) and len(obj) < item_threshold:
93 cobj = {}
93 cobj = {}
94 for k in sorted(obj.iterkeys()):
94 for k in sorted(obj):
95 c = can(obj[k])
95 c = can(obj[k])
96 buffers.extend(_extract_buffers(c, buffer_threshold))
96 buffers.extend(_extract_buffers(c, buffer_threshold))
97 cobj[k] = c
97 cobj[k] = c
@@ -129,7 +129,7 b' def unserialize_object(buffers, g=None):'
129 newobj = uncan_sequence(canned, g)
129 newobj = uncan_sequence(canned, g)
130 elif istype(canned, dict) and len(canned) < MAX_ITEMS:
130 elif istype(canned, dict) and len(canned) < MAX_ITEMS:
131 newobj = {}
131 newobj = {}
132 for k in sorted(canned.iterkeys()):
132 for k in sorted(canned):
133 c = canned[k]
133 c = canned[k]
134 _restore_buffers(c, bufs)
134 _restore_buffers(c, bufs)
135 newobj[k] = uncan(c, g)
135 newobj[k] = uncan(c, g)
@@ -49,7 +49,8 b' from IPython.config.configurable import Configurable, LoggingConfigurable'
49 from IPython.utils import io
49 from IPython.utils import io
50 from IPython.utils.importstring import import_item
50 from IPython.utils.importstring import import_item
51 from IPython.utils.jsonutil import extract_dates, squash_dates, date_default
51 from IPython.utils.jsonutil import extract_dates, squash_dates, date_default
52 from IPython.utils.py3compat import str_to_bytes, str_to_unicode
52 from IPython.utils.py3compat import (str_to_bytes, str_to_unicode, unicode_type,
53 iteritems)
53 from IPython.utils.traitlets import (CBytes, Unicode, Bool, Any, Instance, Set,
54 from IPython.utils.traitlets import (CBytes, Unicode, Bool, Any, Instance, Set,
54 DottedObjectName, CUnicode, Dict, Integer,
55 DottedObjectName, CUnicode, Dict, Integer,
55 TraitError,
56 TraitError,
@@ -65,12 +66,12 b' def squash_unicode(obj):'
65 if isinstance(obj,dict):
66 if isinstance(obj,dict):
66 for key in obj.keys():
67 for key in obj.keys():
67 obj[key] = squash_unicode(obj[key])
68 obj[key] = squash_unicode(obj[key])
68 if isinstance(key, unicode):
69 if isinstance(key, unicode_type):
69 obj[squash_unicode(key)] = obj.pop(key)
70 obj[squash_unicode(key)] = obj.pop(key)
70 elif isinstance(obj, list):
71 elif isinstance(obj, list):
71 for i,v in enumerate(obj):
72 for i,v in enumerate(obj):
72 obj[i] = squash_unicode(v)
73 obj[i] = squash_unicode(v)
73 elif isinstance(obj, unicode):
74 elif isinstance(obj, unicode_type):
74 obj = obj.encode('utf8')
75 obj = obj.encode('utf8')
75 return obj
76 return obj
76
77
@@ -166,14 +167,14 b' class Message(object):'
166
167
167 def __init__(self, msg_dict):
168 def __init__(self, msg_dict):
168 dct = self.__dict__
169 dct = self.__dict__
169 for k, v in dict(msg_dict).iteritems():
170 for k, v in iteritems(dict(msg_dict)):
170 if isinstance(v, dict):
171 if isinstance(v, dict):
171 v = Message(v)
172 v = Message(v)
172 dct[k] = v
173 dct[k] = v
173
174
174 # Having this iterator lets dict(msg_obj) work out of the box.
175 # Having this iterator lets dict(msg_obj) work out of the box.
175 def __iter__(self):
176 def __iter__(self):
176 return iter(self.__dict__.iteritems())
177 return iter(iteritems(self.__dict__))
177
178
178 def __repr__(self):
179 def __repr__(self):
179 return repr(self.__dict__)
180 return repr(self.__dict__)
@@ -288,7 +289,7 b' class Session(Configurable):'
288 session = CUnicode(u'', config=True,
289 session = CUnicode(u'', config=True,
289 help="""The UUID identifying this session.""")
290 help="""The UUID identifying this session.""")
290 def _session_default(self):
291 def _session_default(self):
291 u = unicode(uuid.uuid4())
292 u = unicode_type(uuid.uuid4())
292 self.bsession = u.encode('ascii')
293 self.bsession = u.encode('ascii')
293 return u
294 return u
294
295
@@ -538,7 +539,7 b' class Session(Configurable):'
538 elif isinstance(content, bytes):
539 elif isinstance(content, bytes):
539 # content is already packed, as in a relayed message
540 # content is already packed, as in a relayed message
540 pass
541 pass
541 elif isinstance(content, unicode):
542 elif isinstance(content, unicode_type):
542 # should be bytes, but JSON often spits out unicode
543 # should be bytes, but JSON often spits out unicode
543 content = content.encode('utf8')
544 content = content.encode('utf8')
544 else:
545 else:
@@ -24,6 +24,7 b' import nose.tools as nt'
24
24
25 from IPython.kernel import BlockingKernelClient
25 from IPython.kernel import BlockingKernelClient
26 from IPython.utils import path, py3compat
26 from IPython.utils import path, py3compat
27 from IPython.utils.py3compat import unicode_type
27
28
28 #-------------------------------------------------------------------------------
29 #-------------------------------------------------------------------------------
29 # Tests
30 # Tests
@@ -183,7 +184,7 b' def test_embed_kernel_reentrant():'
183 msg = client.get_shell_msg(block=True, timeout=TIMEOUT)
184 msg = client.get_shell_msg(block=True, timeout=TIMEOUT)
184 content = msg['content']
185 content = msg['content']
185 nt.assert_true(content['found'])
186 nt.assert_true(content['found'])
186 nt.assert_equal(content['string_form'], unicode(i))
187 nt.assert_equal(content['string_form'], unicode_type(i))
187
188
188 # exit from embed_kernel
189 # exit from embed_kernel
189 client.execute("get_ipython().exit_now = True")
190 client.execute("get_ipython().exit_now = True")
@@ -20,6 +20,7 b' import nose.tools as nt'
20 from IPython.kernel.zmq.serialize import serialize_object, unserialize_object
20 from IPython.kernel.zmq.serialize import serialize_object, unserialize_object
21 from IPython.testing import decorators as dec
21 from IPython.testing import decorators as dec
22 from IPython.utils.pickleutil import CannedArray, CannedClass
22 from IPython.utils.pickleutil import CannedArray, CannedClass
23 from IPython.utils.py3compat import iteritems
23 from IPython.parallel import interactive
24 from IPython.parallel import interactive
24
25
25 #-------------------------------------------------------------------------------
26 #-------------------------------------------------------------------------------
@@ -37,7 +38,7 b' class C(object):'
37 """dummy class for """
38 """dummy class for """
38
39
39 def __init__(self, **kwargs):
40 def __init__(self, **kwargs):
40 for key,value in kwargs.iteritems():
41 for key,value in iteritems(kwargs):
41 setattr(self, key, value)
42 setattr(self, key, value)
42
43
43 SHAPES = ((100,), (1024,10), (10,8,6,5), (), (0,))
44 SHAPES = ((100,), (1024,10), (10,8,6,5), (), (0,))
@@ -44,13 +44,14 b' from IPython.utils import openpy'
44 from IPython.utils.jsonutil import json_clean, encode_images
44 from IPython.utils.jsonutil import json_clean, encode_images
45 from IPython.utils.process import arg_split
45 from IPython.utils.process import arg_split
46 from IPython.utils import py3compat
46 from IPython.utils import py3compat
47 from IPython.utils.py3compat import unicode_type
47 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes, Any
48 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes, Any
48 from IPython.utils.warn import error
49 from IPython.utils.warn import error
49 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
50 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
50 from IPython.kernel.zmq.datapub import ZMQDataPublisher
51 from IPython.kernel.zmq.datapub import ZMQDataPublisher
51 from IPython.kernel.zmq.session import extract_header
52 from IPython.kernel.zmq.session import extract_header
52 from IPython.kernel.comm import CommManager
53 from IPython.kernel.comm import CommManager
53 from session import Session
54 from .session import Session
54
55
55 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
56 # Functions and classes
57 # Functions and classes
@@ -555,7 +556,7 b' class ZMQInteractiveShell(InteractiveShell):'
555
556
556 exc_content = {
557 exc_content = {
557 u'traceback' : stb,
558 u'traceback' : stb,
558 u'ename' : unicode(etype.__name__),
559 u'ename' : unicode_type(etype.__name__),
559 u'evalue' : py3compat.safe_unicode(evalue),
560 u'evalue' : py3compat.safe_unicode(evalue),
560 }
561 }
561
562
@@ -21,6 +21,7 b' separate implementation).'
21 An example notebook is provided in our documentation illustrating interactive
21 An example notebook is provided in our documentation illustrating interactive
22 use of the system.
22 use of the system.
23 """
23 """
24 from __future__ import print_function
24
25
25 #*****************************************************************************
26 #*****************************************************************************
26 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
27 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
@@ -36,6 +37,7 b' import threading'
36 from IPython import get_ipython
37 from IPython import get_ipython
37 from IPython.core.ultratb import AutoFormattedTB
38 from IPython.core.ultratb import AutoFormattedTB
38 from IPython.utils.warn import error
39 from IPython.utils.warn import error
40 from IPython.utils.py3compat import string_types
39
41
40
42
41 class BackgroundJobManager(object):
43 class BackgroundJobManager(object):
@@ -170,7 +172,7 b' class BackgroundJobManager(object):'
170 if callable(func_or_exp):
172 if callable(func_or_exp):
171 kw = kwargs.get('kw',{})
173 kw = kwargs.get('kw',{})
172 job = BackgroundJobFunc(func_or_exp,*args,**kw)
174 job = BackgroundJobFunc(func_or_exp,*args,**kw)
173 elif isinstance(func_or_exp, basestring):
175 elif isinstance(func_or_exp, string_types):
174 if not args:
176 if not args:
175 frame = sys._getframe(1)
177 frame = sys._getframe(1)
176 glob, loc = frame.f_globals, frame.f_locals
178 glob, loc = frame.f_globals, frame.f_locals
@@ -190,7 +192,7 b' class BackgroundJobManager(object):'
190 job.num = len(self.all)+1 if self.all else 0
192 job.num = len(self.all)+1 if self.all else 0
191 self.running.append(job)
193 self.running.append(job)
192 self.all[job.num] = job
194 self.all[job.num] = job
193 print 'Starting job # %s in a separate thread.' % job.num
195 print('Starting job # %s in a separate thread.' % job.num)
194 job.start()
196 job.start()
195 return job
197 return job
196
198
@@ -245,10 +247,10 b' class BackgroundJobManager(object):'
245 Return True if the group had any elements."""
247 Return True if the group had any elements."""
246
248
247 if group:
249 if group:
248 print '%s jobs:' % name
250 print('%s jobs:' % name)
249 for job in group:
251 for job in group:
250 print '%s : %s' % (job.num,job)
252 print('%s : %s' % (job.num,job))
251 print
253 print()
252 return True
254 return True
253
255
254 def _group_flush(self,group,name):
256 def _group_flush(self,group,name):
@@ -259,7 +261,7 b' class BackgroundJobManager(object):'
259 njobs = len(group)
261 njobs = len(group)
260 if njobs:
262 if njobs:
261 plural = {1:''}.setdefault(njobs,'s')
263 plural = {1:''}.setdefault(njobs,'s')
262 print 'Flushing %s %s job%s.' % (njobs,name,plural)
264 print('Flushing %s %s job%s.' % (njobs,name,plural))
263 group[:] = []
265 group[:] = []
264 return True
266 return True
265
267
@@ -325,7 +327,7 b' class BackgroundJobManager(object):'
325 fl_comp = self._group_flush(self.completed, 'Completed')
327 fl_comp = self._group_flush(self.completed, 'Completed')
326 fl_dead = self._group_flush(self.dead, 'Dead')
328 fl_dead = self._group_flush(self.dead, 'Dead')
327 if not (fl_comp or fl_dead):
329 if not (fl_comp or fl_dead):
328 print 'No jobs to flush.'
330 print('No jobs to flush.')
329
331
330 def result(self,num):
332 def result(self,num):
331 """result(N) -> return the result of job N."""
333 """result(N) -> return the result of job N."""
@@ -345,9 +347,9 b' class BackgroundJobManager(object):'
345 if job is None:
347 if job is None:
346 self._update_status()
348 self._update_status()
347 for deadjob in self.dead:
349 for deadjob in self.dead:
348 print "Traceback for: %r" % deadjob
350 print("Traceback for: %r" % deadjob)
349 self._traceback(deadjob)
351 self._traceback(deadjob)
350 print
352 print()
351 else:
353 else:
352 self._traceback(job)
354 self._traceback(job)
353
355
@@ -416,7 +418,7 b' class BackgroundJobBase(threading.Thread):'
416 return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
418 return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
417
419
418 def traceback(self):
420 def traceback(self):
419 print self._tb
421 print(self._tb)
420
422
421 def run(self):
423 def run(self):
422 try:
424 try:
@@ -41,11 +41,14 b' def tkinter_clipboard_get():'
41 implementation that uses that toolkit.
41 implementation that uses that toolkit.
42 """
42 """
43 try:
43 try:
44 import Tkinter
44 from tkinter import Tk # Py 3
45 except ImportError:
45 except ImportError:
46 raise TryNext("Getting text from the clipboard on this platform "
46 try:
47 "requires Tkinter.")
47 from Tkinter import Tk # Py 2
48 root = Tkinter.Tk()
48 except ImportError:
49 raise TryNext("Getting text from the clipboard on this platform "
50 "requires Tkinter.")
51 root = Tk()
49 root.withdraw()
52 root.withdraw()
50 text = root.clipboard_get()
53 text = root.clipboard_get()
51 root.destroy()
54 root.destroy()
@@ -17,6 +17,7 b' Alternatively, you can add a dreload builtin alongside normal reload with::'
17 This code is almost entirely based on knee.py, which is a Python
17 This code is almost entirely based on knee.py, which is a Python
18 re-implementation of hierarchical module import.
18 re-implementation of hierarchical module import.
19 """
19 """
20 from __future__ import print_function
20 #*****************************************************************************
21 #*****************************************************************************
21 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
22 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
22 #
23 #
@@ -24,7 +25,6 b' re-implementation of hierarchical module import.'
24 # the file COPYING, distributed as part of this software.
25 # the file COPYING, distributed as part of this software.
25 #*****************************************************************************
26 #*****************************************************************************
26
27
27 import __builtin__
28 from contextlib import contextmanager
28 from contextlib import contextmanager
29 import imp
29 import imp
30 import sys
30 import sys
@@ -32,16 +32,18 b' import sys'
32 from types import ModuleType
32 from types import ModuleType
33 from warnings import warn
33 from warnings import warn
34
34
35 original_import = __builtin__.__import__
35 from IPython.utils.py3compat import builtin_mod, builtin_mod_name
36
37 original_import = builtin_mod.__import__
36
38
37 @contextmanager
39 @contextmanager
38 def replace_import_hook(new_import):
40 def replace_import_hook(new_import):
39 saved_import = __builtin__.__import__
41 saved_import = builtin_mod.__import__
40 __builtin__.__import__ = new_import
42 builtin_mod.__import__ = new_import
41 try:
43 try:
42 yield
44 yield
43 finally:
45 finally:
44 __builtin__.__import__ = saved_import
46 builtin_mod.__import__ = saved_import
45
47
46 def get_parent(globals, level):
48 def get_parent(globals, level):
47 """
49 """
@@ -91,7 +93,7 b' def get_parent(globals, level):'
91 globals['__package__'] = name = modname[:lastdot]
93 globals['__package__'] = name = modname[:lastdot]
92
94
93 dot = len(name)
95 dot = len(name)
94 for x in xrange(level, 1, -1):
96 for x in range(level, 1, -1):
95 try:
97 try:
96 dot = name.rindex('.', 0, dot)
98 dot = name.rindex('.', 0, dot)
97 except ValueError:
99 except ValueError:
@@ -167,7 +169,7 b' def import_submodule(mod, subname, fullname):'
167 if fullname in found_now and fullname in sys.modules:
169 if fullname in found_now and fullname in sys.modules:
168 m = sys.modules[fullname]
170 m = sys.modules[fullname]
169 else:
171 else:
170 print 'Reloading', fullname
172 print('Reloading', fullname)
171 found_now[fullname] = 1
173 found_now[fullname] = 1
172 oldm = sys.modules.get(fullname, None)
174 oldm = sys.modules.get(fullname, None)
173
175
@@ -312,12 +314,12 b' def deep_reload_hook(m):'
312
314
313 # Save the original hooks
315 # Save the original hooks
314 try:
316 try:
315 original_reload = __builtin__.reload
317 original_reload = builtin_mod.reload
316 except AttributeError:
318 except AttributeError:
317 original_reload = imp.reload # Python 3
319 original_reload = imp.reload # Python 3
318
320
319 # Replacement for reload()
321 # Replacement for reload()
320 def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']):
322 def reload(module, exclude=['sys', 'os.path', builtin_mod_name, '__main__']):
321 """Recursively reload all modules used in the given module. Optionally
323 """Recursively reload all modules used in the given module. Optionally
322 takes a list of modules to exclude from reloading. The default exclude
324 takes a list of modules to exclude from reloading. The default exclude
323 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
325 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
@@ -334,4 +336,4 b" def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']):"
334
336
335 # Uncomment the following to automatically activate deep reloading whenever
337 # Uncomment the following to automatically activate deep reloading whenever
336 # this module is imported
338 # this module is imported
337 #__builtin__.reload = reload
339 #builtin_mod.reload = reload
@@ -186,6 +186,7 b' import sys'
186 from IPython.utils import io
186 from IPython.utils import io
187 from IPython.utils.text import marquee
187 from IPython.utils.text import marquee
188 from IPython.utils import openpy
188 from IPython.utils import openpy
189 from IPython.utils import py3compat
189 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
190 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
190
191
191 class DemoError(Exception): pass
192 class DemoError(Exception): pass
@@ -397,7 +398,7 b' class Demo(object):'
397
398
398 print(self.marquee('<%s> block # %s (%s remaining)' %
399 print(self.marquee('<%s> block # %s (%s remaining)' %
399 (self.title,index,self.nblocks-index-1)), file=io.stdout)
400 (self.title,index,self.nblocks-index-1)), file=io.stdout)
400 print((self.src_blocks_colored[index]), file=io.stdout)
401 print(self.src_blocks_colored[index], file=io.stdout)
401 sys.stdout.flush()
402 sys.stdout.flush()
402
403
403 def show_all(self):
404 def show_all(self):
@@ -421,7 +422,7 b' class Demo(object):'
421 def run_cell(self,source):
422 def run_cell(self,source):
422 """Execute a string with one or more lines of code"""
423 """Execute a string with one or more lines of code"""
423
424
424 exec source in self.user_ns
425 exec(source, self.user_ns)
425
426
426 def __call__(self,index=None):
427 def __call__(self,index=None):
427 """run a block of the demo.
428 """run a block of the demo.
@@ -449,7 +450,7 b' class Demo(object):'
449 print(marquee('output:'), file=io.stdout)
450 print(marquee('output:'), file=io.stdout)
450 else:
451 else:
451 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ', file=io.stdout)
452 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ', file=io.stdout)
452 ans = raw_input().strip()
453 ans = py3compat.input().strip()
453 if ans:
454 if ans:
454 print(marquee('Block NOT executed'), file=io.stdout)
455 print(marquee('Block NOT executed'), file=io.stdout)
455 return
456 return
@@ -280,8 +280,7 b' class FileLink(object):'
280 text to append at the end of link [default: '<br>']
280 text to append at the end of link [default: '<br>']
281 """
281 """
282 if isdir(path):
282 if isdir(path):
283 raise ValueError,\
283 raise ValueError("Cannot display a directory using FileLink. "
284 ("Cannot display a directory using FileLink. "
285 "Use FileLinks to display '%s'." % path)
284 "Use FileLinks to display '%s'." % path)
286 self.path = path
285 self.path = path
287 self.url_prefix = url_prefix
286 self.url_prefix = url_prefix
@@ -366,8 +365,7 b' class FileLinks(FileLink):'
366
365
367 """
366 """
368 if isfile(path):
367 if isfile(path):
369 raise ValueError,\
368 raise ValueError("Cannot display a file using FileLinks. "
370 ("Cannot display a file using FileLinks. "
371 "Use FileLink to display '%s'." % path)
369 "Use FileLink to display '%s'." % path)
372 self.included_suffixes = included_suffixes
370 self.included_suffixes = included_suffixes
373 # remove trailing slashs for more consistent output formatting
371 # remove trailing slashs for more consistent output formatting
@@ -4,6 +4,7 b' They should honor the line number argument, at least.'
4
4
5 Contributions are *very* welcome.
5 Contributions are *very* welcome.
6 """
6 """
7 from __future__ import print_function
7
8
8 import os
9 import os
9 import pipes
10 import pipes
@@ -11,6 +12,7 b' import subprocess'
11
12
12 from IPython import get_ipython
13 from IPython import get_ipython
13 from IPython.core.error import TryNext
14 from IPython.core.error import TryNext
15 from IPython.utils import py3compat
14
16
15
17
16 def install_editor(template, wait=False):
18 def install_editor(template, wait=False):
@@ -45,12 +47,12 b' def install_editor(template, wait=False):'
45 if line is None:
47 if line is None:
46 line = 0
48 line = 0
47 cmd = template.format(filename=pipes.quote(filename), line=line)
49 cmd = template.format(filename=pipes.quote(filename), line=line)
48 print ">", cmd
50 print(">", cmd)
49 proc = subprocess.Popen(cmd, shell=True)
51 proc = subprocess.Popen(cmd, shell=True)
50 if wait and proc.wait() != 0:
52 if wait and proc.wait() != 0:
51 raise TryNext()
53 raise TryNext()
52 if wait:
54 if wait:
53 raw_input("Press Enter when done editing:")
55 py3compat.input("Press Enter when done editing:")
54
56
55 get_ipython().set_hook('editor', call_editor)
57 get_ipython().set_hook('editor', call_editor)
56 get_ipython().editor = template
58 get_ipython().editor = template
@@ -320,8 +320,11 b' class InputHookManager(object):'
320 """
320 """
321 self._current_gui = GUI_TK
321 self._current_gui = GUI_TK
322 if app is None:
322 if app is None:
323 import Tkinter
323 try:
324 app = Tkinter.Tk()
324 from tkinter import Tk # Py 3
325 except ImportError:
326 from Tkinter import Tk # Py 2
327 app = Tk()
325 app.withdraw()
328 app.withdraw()
326 self._apps[GUI_TK] = app
329 self._apps[GUI_TK] = app
327 return app
330 return app
@@ -2,6 +2,7 b''
2 """
2 """
3 GLUT Inputhook support functions
3 GLUT Inputhook support functions
4 """
4 """
5 from __future__ import print_function
5
6
6 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
8 # Copyright (C) 2008-2011 The IPython Development Team
@@ -114,7 +115,7 b' def glut_close():'
114 def glut_int_handler(signum, frame):
115 def glut_int_handler(signum, frame):
115 # Catch sigint and print the defautl message
116 # Catch sigint and print the defautl message
116 signal.signal(signal.SIGINT, signal.default_int_handler)
117 signal.signal(signal.SIGINT, signal.default_int_handler)
117 print '\nKeyboardInterrupt'
118 print('\nKeyboardInterrupt')
118 # Need to reprint the prompt at this stage
119 # Need to reprint the prompt at this stage
119
120
120
121
@@ -199,7 +199,7 b' class InteractiveRunner(object):'
199
199
200 # if the source is a string, chop it up in lines so we can iterate
200 # if the source is a string, chop it up in lines so we can iterate
201 # over it just as if it were an open file.
201 # over it just as if it were an open file.
202 if isinstance(source, basestring):
202 if isinstance(source, py3compat.string_types):
203 source = source.splitlines(True)
203 source = source.splitlines(True)
204
204
205 if self.echo:
205 if self.echo:
@@ -103,14 +103,21 b' Inheritance diagram:'
103 Portions (c) 2009 by Robert Kern.
103 Portions (c) 2009 by Robert Kern.
104 :license: BSD License.
104 :license: BSD License.
105 """
105 """
106 from __future__ import print_function
106 from contextlib import contextmanager
107 from contextlib import contextmanager
107 import sys
108 import sys
108 import types
109 import types
109 import re
110 import re
110 import datetime
111 import datetime
111 from StringIO import StringIO
112 from collections import deque
112 from collections import deque
113
113
114 from IPython.utils.py3compat import PY3
115
116 if PY3:
117 from io import StringIO
118 else:
119 from StringIO import StringIO
120
114
121
115 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
122 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
116 'for_type', 'for_type_by_name']
123 'for_type', 'for_type_by_name']
@@ -707,10 +714,8 b' except NameError:'
707 #: printers for builtin types
714 #: printers for builtin types
708 _type_pprinters = {
715 _type_pprinters = {
709 int: _repr_pprint,
716 int: _repr_pprint,
710 long: _repr_pprint,
711 float: _repr_pprint,
717 float: _repr_pprint,
712 str: _repr_pprint,
718 str: _repr_pprint,
713 unicode: _repr_pprint,
714 tuple: _seq_pprinter_factory('(', ')', tuple),
719 tuple: _seq_pprinter_factory('(', ')', tuple),
715 list: _seq_pprinter_factory('[', ']', list),
720 list: _seq_pprinter_factory('[', ']', list),
716 dict: _dict_pprinter_factory('{', '}', dict),
721 dict: _dict_pprinter_factory('{', '}', dict),
@@ -722,7 +727,6 b' _type_pprinters = {'
722 type: _type_pprint,
727 type: _type_pprint,
723 types.FunctionType: _function_pprint,
728 types.FunctionType: _function_pprint,
724 types.BuiltinFunctionType: _function_pprint,
729 types.BuiltinFunctionType: _function_pprint,
725 types.SliceType: _repr_pprint,
726 types.MethodType: _repr_pprint,
730 types.MethodType: _repr_pprint,
727
731
728 datetime.datetime: _repr_pprint,
732 datetime.datetime: _repr_pprint,
@@ -733,13 +737,17 b' _type_pprinters = {'
733 try:
737 try:
734 _type_pprinters[types.DictProxyType] = _dict_pprinter_factory('<dictproxy {', '}>')
738 _type_pprinters[types.DictProxyType] = _dict_pprinter_factory('<dictproxy {', '}>')
735 _type_pprinters[types.ClassType] = _type_pprint
739 _type_pprinters[types.ClassType] = _type_pprint
740 _type_pprinters[types.SliceType] = _repr_pprint
736 except AttributeError: # Python 3
741 except AttributeError: # Python 3
737 pass
742 _type_pprinters[slice] = _repr_pprint
738
743
739 try:
744 try:
740 _type_pprinters[xrange] = _repr_pprint
745 _type_pprinters[xrange] = _repr_pprint
746 _type_pprinters[long] = _repr_pprint
747 _type_pprinters[unicode] = _repr_pprint
741 except NameError:
748 except NameError:
742 _type_pprinters[range] = _repr_pprint
749 _type_pprinters[range] = _repr_pprint
750 _type_pprinters[bytes] = _repr_pprint
743
751
744 #: printers for types specified by name
752 #: printers for types specified by name
745 _deferred_type_pprinters = {
753 _deferred_type_pprinters = {
@@ -784,6 +792,6 b" if __name__ == '__main__':"
784 self.list = ["blub", "blah", self]
792 self.list = ["blub", "blah", self]
785
793
786 def get_foo(self):
794 def get_foo(self):
787 print "foo"
795 print("foo")
788
796
789 pprint(Foo(), verbose=True)
797 pprint(Foo(), verbose=True)
@@ -10,6 +10,7 b' import os'
10 import nose.tools as nt
10 import nose.tools as nt
11
11
12 from IPython.testing import decorators as dec
12 from IPython.testing import decorators as dec
13 from IPython.utils.py3compat import builtin_mod_name
13 from IPython.utils.syspathcontext import prepended_to_syspath
14 from IPython.utils.syspathcontext import prepended_to_syspath
14 from IPython.utils.tempdir import TemporaryDirectory
15 from IPython.utils.tempdir import TemporaryDirectory
15 from IPython.lib.deepreload import reload as dreload
16 from IPython.lib.deepreload import reload as dreload
@@ -24,7 +25,7 b' def test_deepreload_numpy():'
24 import numpy
25 import numpy
25 exclude = [
26 exclude = [
26 # Standard exclusions:
27 # Standard exclusions:
27 'sys', 'os.path', '__builtin__', '__main__',
28 'sys', 'os.path', builtin_mod_name, '__main__',
28 # Test-related exclusions:
29 # Test-related exclusions:
29 'unittest', 'UserDict',
30 'unittest', 'UserDict',
30 ]
31 ]
@@ -8,19 +8,23 b' from __future__ import print_function'
8 VERBOSE = True
8 VERBOSE = True
9
9
10 # stdlib imports
10 # stdlib imports
11 import StringIO
12 import sys
11 import sys
13 import unittest
12 import unittest
14
13
15 # IPython imports
14 # IPython imports
16 from IPython.lib import irunner
15 from IPython.lib import irunner
17 from IPython.utils.py3compat import doctest_refactor_print
16 from IPython.utils.py3compat import doctest_refactor_print, PY3
17
18 if PY3:
19 from io import StringIO
20 else:
21 from StringIO import StringIO
18
22
19 # Testing code begins
23 # Testing code begins
20 class RunnerTestCase(unittest.TestCase):
24 class RunnerTestCase(unittest.TestCase):
21
25
22 def setUp(self):
26 def setUp(self):
23 self.out = StringIO.StringIO()
27 self.out = StringIO()
24 #self.out = sys.stdout
28 #self.out = sys.stdout
25
29
26 def _test_runner(self,runner,source,output):
30 def _test_runner(self,runner,source,output):
@@ -7,7 +7,6 b' from __future__ import print_function'
7 VERBOSE = True
7 VERBOSE = True
8
8
9 # stdlib imports
9 # stdlib imports
10 import StringIO
11 import sys
10 import sys
12 import unittest
11 import unittest
13 import re
12 import re
@@ -15,6 +14,12 b' import re'
15 # IPython imports
14 # IPython imports
16 from IPython.lib import irunner
15 from IPython.lib import irunner
17 from IPython.testing import decorators
16 from IPython.testing import decorators
17 from IPython.utils.py3compat import PY3
18
19 if PY3:
20 from io import StringIO
21 else:
22 from StringIO import StringIO
18
23
19 def pylab_not_importable():
24 def pylab_not_importable():
20 """Test if importing pylab fails. (For example, when having no display)"""
25 """Test if importing pylab fails. (For example, when having no display)"""
@@ -28,7 +33,7 b' def pylab_not_importable():'
28 class RunnerTestCase(unittest.TestCase):
33 class RunnerTestCase(unittest.TestCase):
29
34
30 def setUp(self):
35 def setUp(self):
31 self.out = StringIO.StringIO()
36 self.out = StringIO()
32 #self.out = sys.stdout
37 #self.out = sys.stdout
33
38
34 def _test_runner(self,runner,source,output):
39 def _test_runner(self,runner,source,output):
@@ -1,7 +1,7 b''
1 """Utilities for converting notebooks to and from different formats."""
1 """Utilities for converting notebooks to and from different formats."""
2
2
3 from .exporters import *
3 from .exporters import *
4 import filters
4 from . import filters
5 import preprocessors
5 from . import preprocessors
6 import postprocessors
6 from . import postprocessors
7 import writers
7 from . import writers
@@ -17,6 +17,7 b' from functools import wraps'
17
17
18 from IPython.nbformat.v3.nbbase import NotebookNode
18 from IPython.nbformat.v3.nbbase import NotebookNode
19 from IPython.config import Config
19 from IPython.config import Config
20 from IPython.utils.py3compat import string_types
20
21
21 from .exporter import Exporter
22 from .exporter import Exporter
22 from .templateexporter import TemplateExporter
23 from .templateexporter import TemplateExporter
@@ -116,7 +117,7 b' def export(exporter, nb, **kw):'
116 #Try to convert the notebook using the appropriate conversion function.
117 #Try to convert the notebook using the appropriate conversion function.
117 if isinstance(nb, NotebookNode):
118 if isinstance(nb, NotebookNode):
118 output, resources = exporter_instance.from_notebook_node(nb, resources)
119 output, resources = exporter_instance.from_notebook_node(nb, resources)
119 elif isinstance(nb, basestring):
120 elif isinstance(nb, string_types):
120 output, resources = exporter_instance.from_filename(nb, resources)
121 output, resources = exporter_instance.from_filename(nb, resources)
121 else:
122 else:
122 output, resources = exporter_instance.from_file(nb, resources)
123 output, resources = exporter_instance.from_file(nb, resources)
@@ -71,7 +71,7 b' def ansi2html(text):'
71 '`': '&#96;',
71 '`': '&#96;',
72 }
72 }
73
73
74 for c, escape in html_escapes.iteritems():
74 for c, escape in html_escapes.items():
75 text = text.replace(c, escape)
75 text = text.replace(c, escape)
76
76
77 ansi_re = re.compile('\x1b' + r'\[([\dA-Fa-f;]*?)m')
77 ansi_re = re.compile('\x1b' + r'\[([\dA-Fa-f;]*?)m')
@@ -19,7 +19,10 b' templates.'
19 import os
19 import os
20 import re
20 import re
21 import textwrap
21 import textwrap
22 from urllib2 import quote
22 try:
23 from urllib.parse import quote # Py 3
24 except ImportError:
25 from urllib2 import quote # Py 2
23 from xml.etree import ElementTree
26 from xml.etree import ElementTree
24
27
25 from IPython.core.interactiveshell import InteractiveShell
28 from IPython.core.interactiveshell import InteractiveShell
@@ -1,4 +1,5 b''
1 """PostProcessor for serving reveal.js HTML slideshows."""
1 """PostProcessor for serving reveal.js HTML slideshows."""
2 from __future__ import print_function
2 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
3 #Copyright (c) 2013, the IPython Development Team.
4 #Copyright (c) 2013, the IPython Development Team.
4 #
5 #
@@ -48,7 +48,7 b' class ConvertFiguresPreprocessor(Preprocessor):'
48
48
49 # Loop through all of the datatypes of the outputs in the cell.
49 # Loop through all of the datatypes of the outputs in the cell.
50 for index, cell_out in enumerate(cell.get('outputs', [])):
50 for index, cell_out in enumerate(cell.get('outputs', [])):
51 for data_type, data in cell_out.items():
51 for data_type, data in list(cell_out.items()):
52 # this must run *before* extract outputs,
52 # this must run *before* extract outputs,
53 # so figure_name and filename do not exist
53 # so figure_name and filename do not exist
54 self._convert_figure(cell_out, resources, data_type, data)
54 self._convert_figure(cell_out, resources, data_type, data)
@@ -12,11 +12,8 b''
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
16 import urllib2
17
18 from .base import Preprocessor
15 from .base import Preprocessor
19 from IPython.utils.traitlets import Unicode, Bool
16 from IPython.utils.traitlets import Unicode
20
17
21 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
22 # Classes and functions
19 # Classes and functions
@@ -97,7 +97,7 b' def prompt_dictionary(choices, default_style=1, menu_comments={}):'
97 # Build the menu that will be displayed to the user with
97 # Build the menu that will be displayed to the user with
98 # all of the options available.
98 # all of the options available.
99 prompt = ""
99 prompt = ""
100 for key, value in choices.iteritems():
100 for key, value in choices.items():
101 prompt += "%d %s " % (key, value)
101 prompt += "%d %s " % (key, value)
102 if key in menu_comments:
102 if key in menu_comments:
103 prompt += menu_comments[key]
103 prompt += menu_comments[key]
@@ -1,6 +1,7 b''
1 """
1 """
2 Contains debug writer.
2 Contains debug writer.
3 """
3 """
4 from __future__ import print_function
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
6 #Copyright (c) 2013, the IPython Development Team.
6 #
7 #
@@ -15,10 +15,15 b' Module with tests for debug'
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import sys
17 import sys
18 from StringIO import StringIO
19
18
20 from ...tests.base import TestsBase
19 from ...tests.base import TestsBase
21 from ..debug import DebugWriter
20 from ..debug import DebugWriter
21 from IPython.utils.py3compat import PY3
22
23 if PY3:
24 from io import StringIO
25 else:
26 from StringIO import StringIO
22
27
23
28
24 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
@@ -16,10 +16,15 b' Module with tests for files'
16
16
17 import sys
17 import sys
18 import os
18 import os
19 from StringIO import StringIO
20
19
21 from ...tests.base import TestsBase
20 from ...tests.base import TestsBase
22 from ..files import FilesWriter
21 from ..files import FilesWriter
22 from IPython.utils.py3compat import PY3
23
24 if PY3:
25 from io import StringIO
26 else:
27 from StringIO import StringIO
23
28
24
29
25 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
@@ -15,10 +15,15 b' Module with tests for stdout'
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import sys
17 import sys
18 from StringIO import StringIO
19
18
20 from ...tests.base import TestsBase
19 from ...tests.base import TestsBase
21 from ..stdout import StdoutWriter
20 from ..stdout import StdoutWriter
21 from IPython.utils.py3compat import PY3
22
23 if PY3:
24 from io import StringIO
25 else:
26 from StringIO import StringIO
22
27
23
28
24 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
@@ -22,6 +22,8 b' from __future__ import print_function'
22 from xml.etree import ElementTree as ET
22 from xml.etree import ElementTree as ET
23 import re
23 import re
24
24
25 from IPython.utils.py3compat import unicode_type
26
25 from IPython.nbformat.v3 import (
27 from IPython.nbformat.v3 import (
26 NotebookNode,
28 NotebookNode,
27 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
29 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
@@ -106,7 +108,7 b' def reads(s, format, **kwargs):'
106 nb : NotebookNode
108 nb : NotebookNode
107 The notebook that was read.
109 The notebook that was read.
108 """
110 """
109 format = unicode(format)
111 format = unicode_type(format)
110 if format == u'json' or format == u'ipynb':
112 if format == u'json' or format == u'ipynb':
111 return reads_json(s, **kwargs)
113 return reads_json(s, **kwargs)
112 elif format == u'py':
114 elif format == u'py':
@@ -132,7 +134,7 b' def writes(nb, format, **kwargs):'
132 s : unicode
134 s : unicode
133 The notebook string.
135 The notebook string.
134 """
136 """
135 format = unicode(format)
137 format = unicode_type(format)
136 if format == u'json' or format == u'ipynb':
138 if format == u'json' or format == u'ipynb':
137 return writes_json(nb, **kwargs)
139 return writes_json(nb, **kwargs)
138 elif format == u'py':
140 elif format == u'py':
@@ -18,9 +18,9 b' Authors:'
18
18
19 import json
19 import json
20
20
21 import v1
21 from . import v1
22 import v2
22 from . import v2
23 import v3
23 from . import v3
24
24
25 versions = {
25 versions = {
26 1: v1,
26 1: v1,
@@ -20,6 +20,7 b' import pprint'
20 import uuid
20 import uuid
21
21
22 from IPython.utils.ipstruct import Struct
22 from IPython.utils.ipstruct import Struct
23 from IPython.utils.py3compat import unicode_type
23
24
24 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
25 # Code
26 # Code
@@ -46,7 +47,7 b' def new_code_cell(code=None, prompt_number=None):'
46 cell = NotebookNode()
47 cell = NotebookNode()
47 cell.cell_type = u'code'
48 cell.cell_type = u'code'
48 if code is not None:
49 if code is not None:
49 cell.code = unicode(code)
50 cell.code = unicode_type(code)
50 if prompt_number is not None:
51 if prompt_number is not None:
51 cell.prompt_number = int(prompt_number)
52 cell.prompt_number = int(prompt_number)
52 return cell
53 return cell
@@ -56,7 +57,7 b' def new_text_cell(text=None):'
56 """Create a new text cell."""
57 """Create a new text cell."""
57 cell = NotebookNode()
58 cell = NotebookNode()
58 if text is not None:
59 if text is not None:
59 cell.text = unicode(text)
60 cell.text = unicode_type(text)
60 cell.cell_type = u'text'
61 cell.cell_type = u'text'
61 return cell
62 return cell
62
63
@@ -25,6 +25,7 b' import pprint'
25 import uuid
25 import uuid
26
26
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.utils.py3compat import unicode_type
28
29
29 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
30 # Code
31 # Code
@@ -53,25 +54,25 b' def new_output(output_type=None, output_text=None, output_png=None,'
53 """Create a new code cell with input and output"""
54 """Create a new code cell with input and output"""
54 output = NotebookNode()
55 output = NotebookNode()
55 if output_type is not None:
56 if output_type is not None:
56 output.output_type = unicode(output_type)
57 output.output_type = unicode_type(output_type)
57
58
58 if output_type != 'pyerr':
59 if output_type != 'pyerr':
59 if output_text is not None:
60 if output_text is not None:
60 output.text = unicode(output_text)
61 output.text = unicode_type(output_text)
61 if output_png is not None:
62 if output_png is not None:
62 output.png = bytes(output_png)
63 output.png = bytes(output_png)
63 if output_jpeg is not None:
64 if output_jpeg is not None:
64 output.jpeg = bytes(output_jpeg)
65 output.jpeg = bytes(output_jpeg)
65 if output_html is not None:
66 if output_html is not None:
66 output.html = unicode(output_html)
67 output.html = unicode_type(output_html)
67 if output_svg is not None:
68 if output_svg is not None:
68 output.svg = unicode(output_svg)
69 output.svg = unicode_type(output_svg)
69 if output_latex is not None:
70 if output_latex is not None:
70 output.latex = unicode(output_latex)
71 output.latex = unicode_type(output_latex)
71 if output_json is not None:
72 if output_json is not None:
72 output.json = unicode(output_json)
73 output.json = unicode_type(output_json)
73 if output_javascript is not None:
74 if output_javascript is not None:
74 output.javascript = unicode(output_javascript)
75 output.javascript = unicode_type(output_javascript)
75
76
76 if output_type == u'pyout':
77 if output_type == u'pyout':
77 if prompt_number is not None:
78 if prompt_number is not None:
@@ -79,11 +80,11 b' def new_output(output_type=None, output_text=None, output_png=None,'
79
80
80 if output_type == u'pyerr':
81 if output_type == u'pyerr':
81 if etype is not None:
82 if etype is not None:
82 output.etype = unicode(etype)
83 output.etype = unicode_type(etype)
83 if evalue is not None:
84 if evalue is not None:
84 output.evalue = unicode(evalue)
85 output.evalue = unicode_type(evalue)
85 if traceback is not None:
86 if traceback is not None:
86 output.traceback = [unicode(frame) for frame in list(traceback)]
87 output.traceback = [unicode_type(frame) for frame in list(traceback)]
87
88
88 return output
89 return output
89
90
@@ -94,9 +95,9 b' def new_code_cell(input=None, prompt_number=None, outputs=None,'
94 cell = NotebookNode()
95 cell = NotebookNode()
95 cell.cell_type = u'code'
96 cell.cell_type = u'code'
96 if language is not None:
97 if language is not None:
97 cell.language = unicode(language)
98 cell.language = unicode_type(language)
98 if input is not None:
99 if input is not None:
99 cell.input = unicode(input)
100 cell.input = unicode_type(input)
100 if prompt_number is not None:
101 if prompt_number is not None:
101 cell.prompt_number = int(prompt_number)
102 cell.prompt_number = int(prompt_number)
102 if outputs is None:
103 if outputs is None:
@@ -112,9 +113,9 b' def new_text_cell(cell_type, source=None, rendered=None):'
112 """Create a new text cell."""
113 """Create a new text cell."""
113 cell = NotebookNode()
114 cell = NotebookNode()
114 if source is not None:
115 if source is not None:
115 cell.source = unicode(source)
116 cell.source = unicode_type(source)
116 if rendered is not None:
117 if rendered is not None:
117 cell.rendered = unicode(rendered)
118 cell.rendered = unicode_type(rendered)
118 cell.cell_type = cell_type
119 cell.cell_type = cell_type
119 return cell
120 return cell
120
121
@@ -123,7 +124,7 b' def new_worksheet(name=None, cells=None):'
123 """Create a worksheet by name with with a list of cells."""
124 """Create a worksheet by name with with a list of cells."""
124 ws = NotebookNode()
125 ws = NotebookNode()
125 if name is not None:
126 if name is not None:
126 ws.name = unicode(name)
127 ws.name = unicode_type(name)
127 if cells is None:
128 if cells is None:
128 ws.cells = []
129 ws.cells = []
129 else:
130 else:
@@ -151,29 +152,29 b' def new_metadata(name=None, authors=None, license=None, created=None,'
151 """Create a new metadata node."""
152 """Create a new metadata node."""
152 metadata = NotebookNode()
153 metadata = NotebookNode()
153 if name is not None:
154 if name is not None:
154 metadata.name = unicode(name)
155 metadata.name = unicode_type(name)
155 if authors is not None:
156 if authors is not None:
156 metadata.authors = list(authors)
157 metadata.authors = list(authors)
157 if created is not None:
158 if created is not None:
158 metadata.created = unicode(created)
159 metadata.created = unicode_type(created)
159 if modified is not None:
160 if modified is not None:
160 metadata.modified = unicode(modified)
161 metadata.modified = unicode_type(modified)
161 if license is not None:
162 if license is not None:
162 metadata.license = unicode(license)
163 metadata.license = unicode_type(license)
163 if gistid is not None:
164 if gistid is not None:
164 metadata.gistid = unicode(gistid)
165 metadata.gistid = unicode_type(gistid)
165 return metadata
166 return metadata
166
167
167 def new_author(name=None, email=None, affiliation=None, url=None):
168 def new_author(name=None, email=None, affiliation=None, url=None):
168 """Create a new author."""
169 """Create a new author."""
169 author = NotebookNode()
170 author = NotebookNode()
170 if name is not None:
171 if name is not None:
171 author.name = unicode(name)
172 author.name = unicode_type(name)
172 if email is not None:
173 if email is not None:
173 author.email = unicode(email)
174 author.email = unicode_type(email)
174 if affiliation is not None:
175 if affiliation is not None:
175 author.affiliation = unicode(affiliation)
176 author.affiliation = unicode_type(affiliation)
176 if url is not None:
177 if url is not None:
177 author.url = unicode(url)
178 author.url = unicode_type(url)
178 return author
179 return author
179
180
@@ -17,6 +17,7 b' Authors:'
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import re
19 import re
20 from IPython.utils.py3compat import unicode_type
20 from .rwbase import NotebookReader, NotebookWriter
21 from .rwbase import NotebookReader, NotebookWriter
21 from .nbbase import new_code_cell, new_text_cell, new_worksheet, new_notebook
22 from .nbbase import new_code_cell, new_text_cell, new_worksheet, new_notebook
22
23
@@ -136,7 +137,7 b' class PyWriter(NotebookWriter):'
136 lines.extend([u'# ' + line for line in input.splitlines()])
137 lines.extend([u'# ' + line for line in input.splitlines()])
137 lines.append(u'')
138 lines.append(u'')
138 lines.append('')
139 lines.append('')
139 return unicode('\n'.join(lines))
140 return unicode_type('\n'.join(lines))
140
141
141
142
142 _reader = PyReader()
143 _reader = PyReader()
@@ -20,6 +20,7 b' from base64 import encodestring, decodestring'
20 import warnings
20 import warnings
21 from xml.etree import ElementTree as ET
21 from xml.etree import ElementTree as ET
22
22
23 from IPython.utils.py3compat import unicode_type
23 from .rwbase import NotebookReader, NotebookWriter
24 from .rwbase import NotebookReader, NotebookWriter
24 from .nbbase import (
25 from .nbbase import (
25 new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output,
26 new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output,
@@ -71,7 +72,7 b' def _get_int(e, tag):'
71 def _set_int(nbnode, attr, parent, tag):
72 def _set_int(nbnode, attr, parent, tag):
72 if attr in nbnode:
73 if attr in nbnode:
73 e = ET.SubElement(parent, tag)
74 e = ET.SubElement(parent, tag)
74 e.text = unicode(nbnode[attr])
75 e.text = unicode_type(nbnode[attr])
75
76
76
77
77 def _get_bool(e, tag):
78 def _get_bool(e, tag):
@@ -19,7 +19,7 b' Authors:'
19 from base64 import encodestring, decodestring
19 from base64 import encodestring, decodestring
20 import pprint
20 import pprint
21
21
22 from IPython.utils.py3compat import str_to_bytes
22 from IPython.utils.py3compat import str_to_bytes, unicode_type, string_types
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
@@ -83,17 +83,17 b' def split_lines(nb):'
83 for ws in nb.worksheets:
83 for ws in nb.worksheets:
84 for cell in ws.cells:
84 for cell in ws.cells:
85 if cell.cell_type == 'code':
85 if cell.cell_type == 'code':
86 if 'input' in cell and isinstance(cell.input, basestring):
86 if 'input' in cell and isinstance(cell.input, string_types):
87 cell.input = cell.input.splitlines()
87 cell.input = cell.input.splitlines()
88 for output in cell.outputs:
88 for output in cell.outputs:
89 for key in _multiline_outputs:
89 for key in _multiline_outputs:
90 item = output.get(key, None)
90 item = output.get(key, None)
91 if isinstance(item, basestring):
91 if isinstance(item, string_types):
92 output[key] = item.splitlines()
92 output[key] = item.splitlines()
93 else: # text cell
93 else: # text cell
94 for key in ['source', 'rendered']:
94 for key in ['source', 'rendered']:
95 item = cell.get(key, None)
95 item = cell.get(key, None)
96 if isinstance(item, basestring):
96 if isinstance(item, string_types):
97 cell[key] = item.splitlines()
97 cell[key] = item.splitlines()
98 return nb
98 return nb
99
99
@@ -110,11 +110,11 b' def base64_decode(nb):'
110 if cell.cell_type == 'code':
110 if cell.cell_type == 'code':
111 for output in cell.outputs:
111 for output in cell.outputs:
112 if 'png' in output:
112 if 'png' in output:
113 if isinstance(output.png, unicode):
113 if isinstance(output.png, unicode_type):
114 output.png = output.png.encode('ascii')
114 output.png = output.png.encode('ascii')
115 output.png = decodestring(output.png)
115 output.png = decodestring(output.png)
116 if 'jpeg' in output:
116 if 'jpeg' in output:
117 if isinstance(output.jpeg, unicode):
117 if isinstance(output.jpeg, unicode_type):
118 output.jpeg = output.jpeg.encode('ascii')
118 output.jpeg = output.jpeg.encode('ascii')
119 output.jpeg = decodestring(output.jpeg)
119 output.jpeg = decodestring(output.jpeg)
120 return nb
120 return nb
@@ -25,7 +25,7 b' import pprint'
25 import uuid
25 import uuid
26
26
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.utils.py3compat import cast_unicode
28 from IPython.utils.py3compat import cast_unicode, unicode_type
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Code
31 # Code
@@ -58,7 +58,7 b' def new_output(output_type=None, output_text=None, output_png=None,'
58 """Create a new code cell with input and output"""
58 """Create a new code cell with input and output"""
59 output = NotebookNode()
59 output = NotebookNode()
60 if output_type is not None:
60 if output_type is not None:
61 output.output_type = unicode(output_type)
61 output.output_type = unicode_type(output_type)
62
62
63 if metadata is None:
63 if metadata is None:
64 metadata = {}
64 metadata = {}
@@ -20,8 +20,7 b' from base64 import encodestring, decodestring'
20 import pprint
20 import pprint
21
21
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23 from IPython.utils.py3compat import str_to_bytes, unicode_type, string_types
24 str_to_bytes = py3compat.str_to_bytes
25
24
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27 # Code
26 # Code
@@ -103,17 +102,17 b' def split_lines(nb):'
103 for ws in nb.worksheets:
102 for ws in nb.worksheets:
104 for cell in ws.cells:
103 for cell in ws.cells:
105 if cell.cell_type == 'code':
104 if cell.cell_type == 'code':
106 if 'input' in cell and isinstance(cell.input, basestring):
105 if 'input' in cell and isinstance(cell.input, string_types):
107 cell.input = cell.input.splitlines(True)
106 cell.input = cell.input.splitlines(True)
108 for output in cell.outputs:
107 for output in cell.outputs:
109 for key in _multiline_outputs:
108 for key in _multiline_outputs:
110 item = output.get(key, None)
109 item = output.get(key, None)
111 if isinstance(item, basestring):
110 if isinstance(item, string_types):
112 output[key] = item.splitlines(True)
111 output[key] = item.splitlines(True)
113 else: # text, heading cell
112 else: # text, heading cell
114 for key in ['source', 'rendered']:
113 for key in ['source', 'rendered']:
115 item = cell.get(key, None)
114 item = cell.get(key, None)
116 if isinstance(item, basestring):
115 if isinstance(item, string_types):
117 cell[key] = item.splitlines(True)
116 cell[key] = item.splitlines(True)
118 return nb
117 return nb
119
118
@@ -130,11 +129,11 b' def base64_decode(nb):'
130 if cell.cell_type == 'code':
129 if cell.cell_type == 'code':
131 for output in cell.outputs:
130 for output in cell.outputs:
132 if 'png' in output:
131 if 'png' in output:
133 if isinstance(output.png, unicode):
132 if isinstance(output.png, unicode_type):
134 output.png = output.png.encode('ascii')
133 output.png = output.png.encode('ascii')
135 output.png = decodestring(output.png)
134 output.png = decodestring(output.png)
136 if 'jpeg' in output:
135 if 'jpeg' in output:
137 if isinstance(output.jpeg, unicode):
136 if isinstance(output.jpeg, unicode_type):
138 output.jpeg = output.jpeg.encode('ascii')
137 output.jpeg = output.jpeg.encode('ascii')
139 output.jpeg = decodestring(output.jpeg)
138 output.jpeg = decodestring(output.jpeg)
140 return nb
139 return nb
@@ -168,7 +167,7 b' class NotebookReader(object):'
168 def read(self, fp, **kwargs):
167 def read(self, fp, **kwargs):
169 """Read a notebook from a file like object"""
168 """Read a notebook from a file like object"""
170 nbs = fp.read()
169 nbs = fp.read()
171 if not py3compat.PY3 and not isinstance(nbs, unicode):
170 if not py3compat.PY3 and not isinstance(nbs, unicode_type):
172 nbs = py3compat.str_to_unicode(nbs)
171 nbs = py3compat.str_to_unicode(nbs)
173 return self.reads(nbs, **kwargs)
172 return self.reads(nbs, **kwargs)
174
173
@@ -183,7 +182,7 b' class NotebookWriter(object):'
183 def write(self, nb, fp, **kwargs):
182 def write(self, nb, fp, **kwargs):
184 """Write a notebook to a file like object"""
183 """Write a notebook to a file like object"""
185 nbs = self.writes(nb,**kwargs)
184 nbs = self.writes(nb,**kwargs)
186 if not py3compat.PY3 and not isinstance(nbs, unicode):
185 if not py3compat.PY3 and not isinstance(nbs, unicode_type):
187 # this branch is likely only taken for JSON on Python 2
186 # this branch is likely only taken for JSON on Python 2
188 nbs = py3compat.str_to_unicode(nbs)
187 nbs = py3compat.str_to_unicode(nbs)
189 return fp.write(nbs)
188 return fp.write(nbs)
@@ -2,6 +2,7 b' import pprint'
2 from base64 import decodestring
2 from base64 import decodestring
3 from unittest import TestCase
3 from unittest import TestCase
4
4
5 from IPython.utils.py3compat import unicode_type
5 from ..nbjson import reads, writes
6 from ..nbjson import reads, writes
6 from .. import nbjson
7 from .. import nbjson
7 from .nbexamples import nb0
8 from .nbexamples import nb0
@@ -42,7 +43,7 b' class TestJSON(formattest.NBFormatTest, TestCase):'
42 if 'png' in output:
43 if 'png' in output:
43 found_png = True
44 found_png = True
44 pngdata = output['png']
45 pngdata = output['png']
45 self.assertEqual(type(pngdata), unicode)
46 self.assertEqual(type(pngdata), unicode_type)
46 # test that it is valid b64 data
47 # test that it is valid b64 data
47 b64bytes = pngdata.encode('ascii')
48 b64bytes = pngdata.encode('ascii')
48 raw_bytes = decodestring(b64bytes)
49 raw_bytes = decodestring(b64bytes)
@@ -60,7 +61,7 b' class TestJSON(formattest.NBFormatTest, TestCase):'
60 if 'jpeg' in output:
61 if 'jpeg' in output:
61 found_jpeg = True
62 found_jpeg = True
62 jpegdata = output['jpeg']
63 jpegdata = output['jpeg']
63 self.assertEqual(type(jpegdata), unicode)
64 self.assertEqual(type(jpegdata), unicode_type)
64 # test that it is valid b64 data
65 # test that it is valid b64 data
65 b64bytes = jpegdata.encode('ascii')
66 b64bytes = jpegdata.encode('ascii')
66 raw_bytes = decodestring(b64bytes)
67 raw_bytes = decodestring(b64bytes)
@@ -2,6 +2,8 b''
2
2
3 from unittest import TestCase
3 from unittest import TestCase
4
4
5 from IPython.utils.py3compat import string_types, iteritems
6
5 from . import formattest
7 from . import formattest
6
8
7 from .. import nbpy
9 from .. import nbpy
@@ -22,7 +24,7 b' class TestPy(formattest.NBFormatTest, TestCase):'
22 elements.
24 elements.
23 """
25 """
24 if isinstance(da, dict):
26 if isinstance(da, dict):
25 for k,v in da.iteritems():
27 for k,v in iteritems(da):
26 if k in self.ignored_keys:
28 if k in self.ignored_keys:
27 continue
29 continue
28 self.assertTrue(k in db)
30 self.assertTrue(k in db)
@@ -31,7 +33,7 b' class TestPy(formattest.NBFormatTest, TestCase):'
31 for a,b in zip(da, db):
33 for a,b in zip(da, db):
32 self.assertSubset(a,b)
34 self.assertSubset(a,b)
33 else:
35 else:
34 if isinstance(da, basestring) and isinstance(db, basestring):
36 if isinstance(da, string_types) and isinstance(db, string_types):
35 # pyfile is not sensitive to preserving leading/trailing
37 # pyfile is not sensitive to preserving leading/trailing
36 # newlines in blocks through roundtrip
38 # newlines in blocks through roundtrip
37 da = da.strip('\n')
39 da = da.strip('\n')
@@ -1,3 +1,4 b''
1 from __future__ import print_function
1 #!/usr/bin/env python
2 #!/usr/bin/env python
2 # -*- coding: utf8 -*-
3 # -*- coding: utf8 -*-
3 import argparse
4 import argparse
@@ -6,6 +7,7 b' import json'
6
7
7 from IPython.external.jsonschema import Draft3Validator, validate, ValidationError
8 from IPython.external.jsonschema import Draft3Validator, validate, ValidationError
8 import IPython.external.jsonpointer as jsonpointer
9 import IPython.external.jsonpointer as jsonpointer
10 from IPython.utils.py3compat import iteritems
9
11
10 def nbvalidate(nbjson, schema='v3.withref.json', key=None,verbose=True):
12 def nbvalidate(nbjson, schema='v3.withref.json', key=None,verbose=True):
11 v3schema = resolve_ref(json.load(open(schema,'r')))
13 v3schema = resolve_ref(json.load(open(schema,'r')))
@@ -34,7 +36,7 b' def resolve_ref(json, base=None):'
34 temp.append(resolve_ref(item, base=base))
36 temp.append(resolve_ref(item, base=base))
35 elif type(json) is dict:
37 elif type(json) is dict:
36 temp = {};
38 temp = {};
37 for key,value in json.iteritems():
39 for key,value in iteritems(json):
38 if key == '$ref':
40 if key == '$ref':
39 return resolve_ref(jsonpointer.resolve_pointer(base,value), base=base)
41 return resolve_ref(jsonpointer.resolve_pointer(base,value), base=base)
40 else :
42 else :
@@ -79,10 +81,10 b" if __name__ == '__main__':"
79 key=args.key,
81 key=args.key,
80 verbose=args.verbose)
82 verbose=args.verbose)
81 if nerror is 0:
83 if nerror is 0:
82 print u"[Pass]",name
84 print(u"[Pass]",name)
83 else :
85 else :
84 print u"[ ]",name,'(%d)'%(nerror)
86 print(u"[ ]",name,'(%d)'%(nerror))
85 if args.verbose :
87 if args.verbose :
86 print '=================================================='
88 print('==================================================')
87
89
88
90
@@ -20,8 +20,6 b' Authors:'
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from __future__ import with_statement
24
25 import os
23 import os
26 import logging
24 import logging
27 import re
25 import re
@@ -38,8 +36,9 b' from IPython.core.application import ('
38 base_flags as base_ip_flags
36 base_flags as base_ip_flags
39 )
37 )
40 from IPython.utils.path import expand_path
38 from IPython.utils.path import expand_path
39 from IPython.utils.py3compat import unicode_type
41
40
42 from IPython.utils.traitlets import Unicode, Bool, Instance, Dict, List
41 from IPython.utils.traitlets import Unicode, Bool, Instance, Dict
43
42
44 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
45 # Module errors
44 # Module errors
@@ -110,7 +109,7 b' class BaseParallelApplication(BaseIPythonApplication):'
110 help='Set the working dir for the process.'
109 help='Set the working dir for the process.'
111 )
110 )
112 def _work_dir_changed(self, name, old, new):
111 def _work_dir_changed(self, name, old, new):
113 self.work_dir = unicode(expand_path(new))
112 self.work_dir = unicode_type(expand_path(new))
114
113
115 log_to_file = Bool(config=True,
114 log_to_file = Bool(config=True,
116 help="whether to log to a file")
115 help="whether to log to a file")
@@ -157,7 +156,7 b' class BaseParallelApplication(BaseIPythonApplication):'
157
156
158 def to_work_dir(self):
157 def to_work_dir(self):
159 wd = self.work_dir
158 wd = self.work_dir
160 if unicode(wd) != os.getcwdu():
159 if unicode_type(wd) != os.getcwdu():
161 os.chdir(wd)
160 os.chdir(wd)
162 self.log.info("Changing to working dir: %s" % wd)
161 self.log.info("Changing to working dir: %s" % wd)
163 # This is the working dir by now.
162 # This is the working dir by now.
@@ -272,5 +271,5 b' class BaseParallelApplication(BaseIPythonApplication):'
272 " Making the likely assumption that it is."%pid
271 " Making the likely assumption that it is."%pid
273 )
272 )
274 return True
273 return True
275 pids = map(int, re.findall(r'^\W*\d+', output, re.MULTILINE))
274 pids = list(map(int, re.findall(r'^\W*\d+', output, re.MULTILINE)))
276 return pid in pids
275 return pid in pids
@@ -9,6 +9,7 b' Authors:'
9 * MinRK
9 * MinRK
10
10
11 """
11 """
12 from __future__ import print_function
12
13
13 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
15 # Copyright (C) 2008-2011 The IPython Development Team
@@ -37,6 +38,7 b' from IPython.core.application import BaseIPythonApplication'
37 from IPython.core.profiledir import ProfileDir
38 from IPython.core.profiledir import ProfileDir
38 from IPython.utils.daemonize import daemonize
39 from IPython.utils.daemonize import daemonize
39 from IPython.utils.importstring import import_item
40 from IPython.utils.importstring import import_item
41 from IPython.utils.py3compat import string_types
40 from IPython.utils.sysinfo import num_cpus
42 from IPython.utils.sysinfo import num_cpus
41 from IPython.utils.traitlets import (Integer, Unicode, Bool, CFloat, Dict, List, Any,
43 from IPython.utils.traitlets import (Integer, Unicode, Bool, CFloat, Dict, List, Any,
42 DottedObjectName)
44 DottedObjectName)
@@ -257,7 +259,7 b' class IPClusterEngines(BaseParallelApplication):'
257
259
258 engine_launcher = Any(config=True, help="Deprecated, use engine_launcher_class")
260 engine_launcher = Any(config=True, help="Deprecated, use engine_launcher_class")
259 def _engine_launcher_changed(self, name, old, new):
261 def _engine_launcher_changed(self, name, old, new):
260 if isinstance(new, basestring):
262 if isinstance(new, string_types):
261 self.log.warn("WARNING: %s.engine_launcher is deprecated as of 0.12,"
263 self.log.warn("WARNING: %s.engine_launcher is deprecated as of 0.12,"
262 " use engine_launcher_class" % self.__class__.__name__)
264 " use engine_launcher_class" % self.__class__.__name__)
263 self.engine_launcher_class = new
265 self.engine_launcher_class = new
@@ -461,7 +463,7 b' class IPClusterStart(IPClusterEngines):'
461
463
462 controller_launcher = Any(config=True, help="Deprecated, use controller_launcher_class")
464 controller_launcher = Any(config=True, help="Deprecated, use controller_launcher_class")
463 def _controller_launcher_changed(self, name, old, new):
465 def _controller_launcher_changed(self, name, old, new):
464 if isinstance(new, basestring):
466 if isinstance(new, string_types):
465 # old 0.11-style config
467 # old 0.11-style config
466 self.log.warn("WARNING: %s.controller_launcher is deprecated as of 0.12,"
468 self.log.warn("WARNING: %s.controller_launcher is deprecated as of 0.12,"
467 " use controller_launcher_class" % self.__class__.__name__)
469 " use controller_launcher_class" % self.__class__.__name__)
@@ -595,8 +597,8 b' class IPClusterApp(BaseIPythonApplication):'
595
597
596 def start(self):
598 def start(self):
597 if self.subapp is None:
599 if self.subapp is None:
598 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
600 print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()))
599 print
601 print()
600 self.print_description()
602 self.print_description()
601 self.print_subcommands()
603 self.print_subcommands()
602 self.exit(1)
604 self.exit(1)
@@ -482,7 +482,7 b' class IPControllerApp(BaseParallelApplication):'
482 for s in statements:
482 for s in statements:
483 try:
483 try:
484 self.log.msg("Executing statement: '%s'" % s)
484 self.log.msg("Executing statement: '%s'" % s)
485 exec s in globals(), locals()
485 exec(s, globals(), locals())
486 except:
486 except:
487 self.log.msg("Error running statement: %s" % s)
487 self.log.msg("Error running statement: %s" % s)
488
488
@@ -355,7 +355,7 b' class IPEngineApp(BaseParallelApplication):'
355 try:
355 try:
356 self.log.info("Initializing MPI:")
356 self.log.info("Initializing MPI:")
357 self.log.info(mpi_import_statement)
357 self.log.info(mpi_import_statement)
358 exec mpi_import_statement in globals()
358 exec(mpi_import_statement, globals())
359 except:
359 except:
360 mpi = None
360 mpi = None
361 else:
361 else:
@@ -64,6 +64,7 b' from IPython.utils.traitlets import ('
64 from IPython.utils.encoding import DEFAULT_ENCODING
64 from IPython.utils.encoding import DEFAULT_ENCODING
65 from IPython.utils.path import get_home_dir
65 from IPython.utils.path import get_home_dir
66 from IPython.utils.process import find_cmd, FindCmdError
66 from IPython.utils.process import find_cmd, FindCmdError
67 from IPython.utils.py3compat import iteritems, itervalues
67
68
68 from .win32support import forward_read_events
69 from .win32support import forward_read_events
69
70
@@ -404,14 +405,14 b' class LocalEngineSetLauncher(LocalEngineLauncher):'
404
405
405 def signal(self, sig):
406 def signal(self, sig):
406 dlist = []
407 dlist = []
407 for el in self.launchers.itervalues():
408 for el in itervalues(self.launchers):
408 d = el.signal(sig)
409 d = el.signal(sig)
409 dlist.append(d)
410 dlist.append(d)
410 return dlist
411 return dlist
411
412
412 def interrupt_then_kill(self, delay=1.0):
413 def interrupt_then_kill(self, delay=1.0):
413 dlist = []
414 dlist = []
414 for el in self.launchers.itervalues():
415 for el in itervalues(self.launchers):
415 d = el.interrupt_then_kill(delay)
416 d = el.interrupt_then_kill(delay)
416 dlist.append(d)
417 dlist.append(d)
417 return dlist
418 return dlist
@@ -421,7 +422,7 b' class LocalEngineSetLauncher(LocalEngineLauncher):'
421
422
422 def _notice_engine_stopped(self, data):
423 def _notice_engine_stopped(self, data):
423 pid = data['pid']
424 pid = data['pid']
424 for idx,el in self.launchers.iteritems():
425 for idx,el in iteritems(self.launchers):
425 if el.process.pid == pid:
426 if el.process.pid == pid:
426 break
427 break
427 self.launchers.pop(idx)
428 self.launchers.pop(idx)
@@ -742,7 +743,7 b' class SSHEngineSetLauncher(LocalEngineSetLauncher):'
742 def engine_count(self):
743 def engine_count(self):
743 """determine engine count from `engines` dict"""
744 """determine engine count from `engines` dict"""
744 count = 0
745 count = 0
745 for n in self.engines.itervalues():
746 for n in itervalues(self.engines):
746 if isinstance(n, (tuple,list)):
747 if isinstance(n, (tuple,list)):
747 n,args = n
748 n,args = n
748 count += n
749 count += n
@@ -754,7 +755,7 b' class SSHEngineSetLauncher(LocalEngineSetLauncher):'
754 """
755 """
755
756
756 dlist = []
757 dlist = []
757 for host, n in self.engines.iteritems():
758 for host, n in iteritems(self.engines):
758 if isinstance(n, (tuple, list)):
759 if isinstance(n, (tuple, list)):
759 n, args = n
760 n, args = n
760 else:
761 else:
@@ -24,6 +24,8 b' import zmq'
24
24
25 from threading import Thread
25 from threading import Thread
26
26
27 from IPython.utils.py3compat import unicode_type
28
27 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
28 # Code
30 # Code
29 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
@@ -39,7 +41,7 b' class ForwarderThread(Thread):'
39 """Loop through lines in self.fd, and send them over self.sock."""
41 """Loop through lines in self.fd, and send them over self.sock."""
40 line = self.fd.readline()
42 line = self.fd.readline()
41 # allow for files opened in unicode mode
43 # allow for files opened in unicode mode
42 if isinstance(line, unicode):
44 if isinstance(line, unicode_type):
43 send = self.sock.send_unicode
45 send = self.sock.send_unicode
44 else:
46 else:
45 send = self.sock.send
47 send = self.sock.send
@@ -28,6 +28,7 b' import uuid'
28 from xml.etree import ElementTree as ET
28 from xml.etree import ElementTree as ET
29
29
30 from IPython.config.configurable import Configurable
30 from IPython.config.configurable import Configurable
31 from IPython.utils.py3compat import iteritems
31 from IPython.utils.traitlets import (
32 from IPython.utils.traitlets import (
32 Unicode, Integer, List, Instance,
33 Unicode, Integer, List, Instance,
33 Enum, Bool
34 Enum, Bool
@@ -215,7 +216,7 b' class WinHPCTask(Configurable):'
215
216
216 def get_env_vars(self):
217 def get_env_vars(self):
217 env_vars = ET.Element('EnvironmentVariables')
218 env_vars = ET.Element('EnvironmentVariables')
218 for k, v in self.environment_variables.iteritems():
219 for k, v in iteritems(self.environment_variables):
219 variable = ET.SubElement(env_vars, "Variable")
220 variable = ET.SubElement(env_vars, "Variable")
220 name = ET.SubElement(variable, "Name")
221 name = ET.SubElement(variable, "Name")
221 name.text = k
222 name.text = k
@@ -26,6 +26,7 b' from zmq import MessageTracker'
26 from IPython.core.display import clear_output, display, display_pretty
26 from IPython.core.display import clear_output, display, display_pretty
27 from IPython.external.decorator import decorator
27 from IPython.external.decorator import decorator
28 from IPython.parallel import error
28 from IPython.parallel import error
29 from IPython.utils.py3compat import string_types
29
30
30 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
31 # Functions
32 # Functions
@@ -61,7 +62,7 b' class AsyncResult(object):'
61 _single_result = False
62 _single_result = False
62
63
63 def __init__(self, client, msg_ids, fname='unknown', targets=None, tracker=None):
64 def __init__(self, client, msg_ids, fname='unknown', targets=None, tracker=None):
64 if isinstance(msg_ids, basestring):
65 if isinstance(msg_ids, string_types):
65 # always a list
66 # always a list
66 msg_ids = [msg_ids]
67 msg_ids = [msg_ids]
67 self._single_result = True
68 self._single_result = True
@@ -79,7 +80,7 b' class AsyncResult(object):'
79 self._ready = False
80 self._ready = False
80 self._outputs_ready = False
81 self._outputs_ready = False
81 self._success = None
82 self._success = None
82 self._metadata = [ self._client.metadata.get(id) for id in self.msg_ids ]
83 self._metadata = [self._client.metadata[id] for id in self.msg_ids]
83
84
84 def __repr__(self):
85 def __repr__(self):
85 if self._ready:
86 if self._ready:
@@ -142,7 +143,7 b' class AsyncResult(object):'
142 self._ready = self._client.wait(self.msg_ids, timeout)
143 self._ready = self._client.wait(self.msg_ids, timeout)
143 if self._ready:
144 if self._ready:
144 try:
145 try:
145 results = map(self._client.results.get, self.msg_ids)
146 results = list(map(self._client.results.get, self.msg_ids))
146 self._result = results
147 self._result = results
147 if self._single_result:
148 if self._single_result:
148 r = results[0]
149 r = results[0]
@@ -254,7 +255,7 b' class AsyncResult(object):'
254 elif isinstance(key, slice):
255 elif isinstance(key, slice):
255 self._check_ready()
256 self._check_ready()
256 return error.collect_exceptions(self._result[key], self._fname)
257 return error.collect_exceptions(self._result[key], self._fname)
257 elif isinstance(key, basestring):
258 elif isinstance(key, string_types):
258 # metadata proxy *does not* require that results are done
259 # metadata proxy *does not* require that results are done
259 self.wait(0)
260 self.wait(0)
260 values = [ md[key] for md in self._metadata ]
261 values = [ md[key] for md in self._metadata ]
@@ -668,10 +669,10 b' class AsyncHubResult(AsyncResult):'
668 start = time.time()
669 start = time.time()
669 if self._ready:
670 if self._ready:
670 return
671 return
671 local_ids = filter(lambda msg_id: msg_id in self._client.outstanding, self.msg_ids)
672 local_ids = [m for m in self.msg_ids if m in self._client.outstanding]
672 local_ready = self._client.wait(local_ids, timeout)
673 local_ready = self._client.wait(local_ids, timeout)
673 if local_ready:
674 if local_ready:
674 remote_ids = filter(lambda msg_id: msg_id not in self._client.results, self.msg_ids)
675 remote_ids = [m for m in self.msg_ids if m not in self._client.results]
675 if not remote_ids:
676 if not remote_ids:
676 self._ready = True
677 self._ready = True
677 else:
678 else:
@@ -686,7 +687,7 b' class AsyncHubResult(AsyncResult):'
686 self._ready = True
687 self._ready = True
687 if self._ready:
688 if self._ready:
688 try:
689 try:
689 results = map(self._client.results.get, self.msg_ids)
690 results = list(map(self._client.results.get, self.msg_ids))
690 self._result = results
691 self._result = results
691 if self._single_result:
692 if self._single_result:
692 r = results[0]
693 r = results[0]
@@ -701,6 +702,6 b' class AsyncHubResult(AsyncResult):'
701 else:
702 else:
702 self._success = True
703 self._success = True
703 finally:
704 finally:
704 self._metadata = map(self._client.metadata.get, self.msg_ids)
705 self._metadata = [self._client.metadata[mid] for mid in self.msg_ids]
705
706
706 __all__ = ['AsyncResult', 'AsyncMapResult', 'AsyncHubResult']
707 __all__ = ['AsyncResult', 'AsyncMapResult', 'AsyncHubResult']
@@ -4,6 +4,7 b' Authors:'
4
4
5 * MinRK
5 * MinRK
6 """
6 """
7 from __future__ import print_function
7 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
8 # Copyright (C) 2010-2011 The IPython Development Team
9 # Copyright (C) 2010-2011 The IPython Development Team
9 #
10 #
@@ -39,7 +40,7 b' from IPython.utils.coloransi import TermColors'
39 from IPython.utils.jsonutil import rekey
40 from IPython.utils.jsonutil import rekey
40 from IPython.utils.localinterfaces import localhost, is_local_ip
41 from IPython.utils.localinterfaces import localhost, is_local_ip
41 from IPython.utils.path import get_ipython_dir
42 from IPython.utils.path import get_ipython_dir
42 from IPython.utils.py3compat import cast_bytes
43 from IPython.utils.py3compat import cast_bytes, string_types, xrange, iteritems
43 from IPython.utils.traitlets import (HasTraits, Integer, Instance, Unicode,
44 from IPython.utils.traitlets import (HasTraits, Integer, Instance, Unicode,
44 Dict, List, Bool, Set, Any)
45 Dict, List, Bool, Set, Any)
45 from IPython.external.decorator import decorator
46 from IPython.external.decorator import decorator
@@ -55,11 +56,6 b' from IPython.kernel.zmq import serialize'
55 from .asyncresult import AsyncResult, AsyncHubResult
56 from .asyncresult import AsyncResult, AsyncHubResult
56 from .view import DirectView, LoadBalancedView
57 from .view import DirectView, LoadBalancedView
57
58
58 if sys.version_info[0] >= 3:
59 # xrange is used in a couple 'isinstance' tests in py2
60 # should be just 'range' in 3k
61 xrange = range
62
63 #--------------------------------------------------------------------------
59 #--------------------------------------------------------------------------
64 # Decorators for Client methods
60 # Decorators for Client methods
65 #--------------------------------------------------------------------------
61 #--------------------------------------------------------------------------
@@ -199,21 +195,21 b' class Metadata(dict):'
199
195
200 def __getattr__(self, key):
196 def __getattr__(self, key):
201 """getattr aliased to getitem"""
197 """getattr aliased to getitem"""
202 if key in self.iterkeys():
198 if key in self:
203 return self[key]
199 return self[key]
204 else:
200 else:
205 raise AttributeError(key)
201 raise AttributeError(key)
206
202
207 def __setattr__(self, key, value):
203 def __setattr__(self, key, value):
208 """setattr aliased to setitem, with strict"""
204 """setattr aliased to setitem, with strict"""
209 if key in self.iterkeys():
205 if key in self:
210 self[key] = value
206 self[key] = value
211 else:
207 else:
212 raise AttributeError(key)
208 raise AttributeError(key)
213
209
214 def __setitem__(self, key, value):
210 def __setitem__(self, key, value):
215 """strict static key enforcement"""
211 """strict static key enforcement"""
216 if key in self.iterkeys():
212 if key in self:
217 dict.__setitem__(self, key, value)
213 dict.__setitem__(self, key, value)
218 else:
214 else:
219 raise KeyError(key)
215 raise KeyError(key)
@@ -538,13 +534,13 b' class Client(HasTraits):'
538
534
539 def _update_engines(self, engines):
535 def _update_engines(self, engines):
540 """Update our engines dict and _ids from a dict of the form: {id:uuid}."""
536 """Update our engines dict and _ids from a dict of the form: {id:uuid}."""
541 for k,v in engines.iteritems():
537 for k,v in iteritems(engines):
542 eid = int(k)
538 eid = int(k)
543 if eid not in self._engines:
539 if eid not in self._engines:
544 self._ids.append(eid)
540 self._ids.append(eid)
545 self._engines[eid] = v
541 self._engines[eid] = v
546 self._ids = sorted(self._ids)
542 self._ids = sorted(self._ids)
547 if sorted(self._engines.keys()) != range(len(self._engines)) and \
543 if sorted(self._engines.keys()) != list(range(len(self._engines))) and \
548 self._task_scheme == 'pure' and self._task_socket:
544 self._task_scheme == 'pure' and self._task_socket:
549 self._stop_scheduling_tasks()
545 self._stop_scheduling_tasks()
550
546
@@ -572,7 +568,7 b' class Client(HasTraits):'
572
568
573 if targets is None:
569 if targets is None:
574 targets = self._ids
570 targets = self._ids
575 elif isinstance(targets, basestring):
571 elif isinstance(targets, string_types):
576 if targets.lower() == 'all':
572 if targets.lower() == 'all':
577 targets = self._ids
573 targets = self._ids
578 else:
574 else:
@@ -585,7 +581,7 b' class Client(HasTraits):'
585 targets = [targets]
581 targets = [targets]
586
582
587 if isinstance(targets, slice):
583 if isinstance(targets, slice):
588 indices = range(len(self._ids))[targets]
584 indices = list(range(len(self._ids))[targets])
589 ids = self.ids
585 ids = self.ids
590 targets = [ ids[i] for i in indices ]
586 targets = [ ids[i] for i in indices ]
591
587
@@ -738,9 +734,9 b' class Client(HasTraits):'
738 msg_id = parent['msg_id']
734 msg_id = parent['msg_id']
739 if msg_id not in self.outstanding:
735 if msg_id not in self.outstanding:
740 if msg_id in self.history:
736 if msg_id in self.history:
741 print ("got stale result: %s"%msg_id)
737 print("got stale result: %s"%msg_id)
742 else:
738 else:
743 print ("got unknown result: %s"%msg_id)
739 print("got unknown result: %s"%msg_id)
744 else:
740 else:
745 self.outstanding.remove(msg_id)
741 self.outstanding.remove(msg_id)
746
742
@@ -774,11 +770,11 b' class Client(HasTraits):'
774 msg_id = parent['msg_id']
770 msg_id = parent['msg_id']
775 if msg_id not in self.outstanding:
771 if msg_id not in self.outstanding:
776 if msg_id in self.history:
772 if msg_id in self.history:
777 print ("got stale result: %s"%msg_id)
773 print("got stale result: %s"%msg_id)
778 print self.results[msg_id]
774 print(self.results[msg_id])
779 print msg
775 print(msg)
780 else:
776 else:
781 print ("got unknown result: %s"%msg_id)
777 print("got unknown result: %s"%msg_id)
782 else:
778 else:
783 self.outstanding.remove(msg_id)
779 self.outstanding.remove(msg_id)
784 content = msg['content']
780 content = msg['content']
@@ -1066,7 +1062,7 b' class Client(HasTraits):'
1066 if jobs is None:
1062 if jobs is None:
1067 theids = self.outstanding
1063 theids = self.outstanding
1068 else:
1064 else:
1069 if isinstance(jobs, (int, basestring, AsyncResult)):
1065 if isinstance(jobs, string_types + (int, AsyncResult)):
1070 jobs = [jobs]
1066 jobs = [jobs]
1071 theids = set()
1067 theids = set()
1072 for job in jobs:
1068 for job in jobs:
@@ -1074,7 +1070,7 b' class Client(HasTraits):'
1074 # index access
1070 # index access
1075 job = self.history[job]
1071 job = self.history[job]
1076 elif isinstance(job, AsyncResult):
1072 elif isinstance(job, AsyncResult):
1077 map(theids.add, job.msg_ids)
1073 theids.update(job.msg_ids)
1078 continue
1074 continue
1079 theids.add(job)
1075 theids.add(job)
1080 if not theids.intersection(self.outstanding):
1076 if not theids.intersection(self.outstanding):
@@ -1134,9 +1130,9 b' class Client(HasTraits):'
1134 targets = self._build_targets(targets)[0]
1130 targets = self._build_targets(targets)[0]
1135
1131
1136 msg_ids = []
1132 msg_ids = []
1137 if isinstance(jobs, (basestring,AsyncResult)):
1133 if isinstance(jobs, string_types + (AsyncResult,)):
1138 jobs = [jobs]
1134 jobs = [jobs]
1139 bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs)
1135 bad_ids = [obj for obj in jobs if not isinstance(obj, string_types + (AsyncResult,))]
1140 if bad_ids:
1136 if bad_ids:
1141 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1137 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1142 for j in jobs:
1138 for j in jobs:
@@ -1287,7 +1283,7 b' class Client(HasTraits):'
1287 metadata = metadata if metadata is not None else {}
1283 metadata = metadata if metadata is not None else {}
1288
1284
1289 # validate arguments
1285 # validate arguments
1290 if not isinstance(code, basestring):
1286 if not isinstance(code, string_types):
1291 raise TypeError("code must be text, not %s" % type(code))
1287 raise TypeError("code must be text, not %s" % type(code))
1292 if not isinstance(metadata, dict):
1288 if not isinstance(metadata, dict):
1293 raise TypeError("metadata must be dict, not %s" % type(metadata))
1289 raise TypeError("metadata must be dict, not %s" % type(metadata))
@@ -1415,12 +1411,12 b' class Client(HasTraits):'
1415 for id in indices_or_msg_ids:
1411 for id in indices_or_msg_ids:
1416 if isinstance(id, int):
1412 if isinstance(id, int):
1417 id = self.history[id]
1413 id = self.history[id]
1418 if not isinstance(id, basestring):
1414 if not isinstance(id, string_types):
1419 raise TypeError("indices must be str or int, not %r"%id)
1415 raise TypeError("indices must be str or int, not %r"%id)
1420 theids.append(id)
1416 theids.append(id)
1421
1417
1422 local_ids = filter(lambda msg_id: msg_id in self.outstanding or msg_id in self.results, theids)
1418 local_ids = [msg_id for msg_id in theids if (msg_id in self.outstanding or msg_id in self.results)]
1423 remote_ids = filter(lambda msg_id: msg_id not in local_ids, theids)
1419 remote_ids = [msg_id for msg_id in theids if msg_id not in local_ids]
1424
1420
1425 # given single msg_id initially, get_result shot get the result itself,
1421 # given single msg_id initially, get_result shot get the result itself,
1426 # not a length-one list
1422 # not a length-one list
@@ -1470,7 +1466,7 b' class Client(HasTraits):'
1470 for id in indices_or_msg_ids:
1466 for id in indices_or_msg_ids:
1471 if isinstance(id, int):
1467 if isinstance(id, int):
1472 id = self.history[id]
1468 id = self.history[id]
1473 if not isinstance(id, basestring):
1469 if not isinstance(id, string_types):
1474 raise TypeError("indices must be str or int, not %r"%id)
1470 raise TypeError("indices must be str or int, not %r"%id)
1475 theids.append(id)
1471 theids.append(id)
1476
1472
@@ -1527,7 +1523,7 b' class Client(HasTraits):'
1527 for msg_id in msg_ids:
1523 for msg_id in msg_ids:
1528 if isinstance(msg_id, int):
1524 if isinstance(msg_id, int):
1529 msg_id = self.history[msg_id]
1525 msg_id = self.history[msg_id]
1530 if not isinstance(msg_id, basestring):
1526 if not isinstance(msg_id, string_types):
1531 raise TypeError("msg_ids must be str, not %r"%msg_id)
1527 raise TypeError("msg_ids must be str, not %r"%msg_id)
1532 theids.append(msg_id)
1528 theids.append(msg_id)
1533
1529
@@ -1645,16 +1641,16 b' class Client(HasTraits):'
1645 if not targets: # needed as _build_targets otherwise uses all engines
1641 if not targets: # needed as _build_targets otherwise uses all engines
1646 return []
1642 return []
1647 target_ids = self._build_targets(targets)[0]
1643 target_ids = self._build_targets(targets)[0]
1648 return filter(lambda md_id: self.metadata[md_id]["engine_uuid"] in target_ids, self.metadata)
1644 return [md_id for md_id in self.metadata if self.metadata[md_id]["engine_uuid"] in target_ids]
1649
1645
1650 def _build_msgids_from_jobs(self, jobs=None):
1646 def _build_msgids_from_jobs(self, jobs=None):
1651 """Build a list of msg_ids from "jobs" """
1647 """Build a list of msg_ids from "jobs" """
1652 if not jobs:
1648 if not jobs:
1653 return []
1649 return []
1654 msg_ids = []
1650 msg_ids = []
1655 if isinstance(jobs, (basestring,AsyncResult)):
1651 if isinstance(jobs, string_types + (AsyncResult,)):
1656 jobs = [jobs]
1652 jobs = [jobs]
1657 bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs)
1653 bad_ids = [obj for obj in jobs if not isinstance(obj, string_types + (AsyncResult,))]
1658 if bad_ids:
1654 if bad_ids:
1659 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1655 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1660 for j in jobs:
1656 for j in jobs:
@@ -1705,8 +1701,9 b' class Client(HasTraits):'
1705 msg_ids = []
1701 msg_ids = []
1706 msg_ids.extend(self._build_msgids_from_target(targets))
1702 msg_ids.extend(self._build_msgids_from_target(targets))
1707 msg_ids.extend(self._build_msgids_from_jobs(jobs))
1703 msg_ids.extend(self._build_msgids_from_jobs(jobs))
1708 map(self.results.pop, msg_ids)
1704 for mid in msg_ids:
1709 map(self.metadata.pop, msg_ids)
1705 self.results.pop(mid)
1706 self.metadata.pop(mid)
1710
1707
1711
1708
1712 @spin_first
1709 @spin_first
@@ -1826,7 +1823,7 b' class Client(HasTraits):'
1826 The subset of keys to be returned. The default is to fetch everything but buffers.
1823 The subset of keys to be returned. The default is to fetch everything but buffers.
1827 'msg_id' will *always* be included.
1824 'msg_id' will *always* be included.
1828 """
1825 """
1829 if isinstance(keys, basestring):
1826 if isinstance(keys, string_types):
1830 keys = [keys]
1827 keys = [keys]
1831 content = dict(query=query, keys=keys)
1828 content = dict(query=query, keys=keys)
1832 self.session.send(self._query_socket, "db_request", content=content)
1829 self.session.send(self._query_socket, "db_request", content=content)
@@ -26,6 +26,7 b' Usage'
26 {CONFIG_DOC}
26 {CONFIG_DOC}
27
27
28 """
28 """
29 from __future__ import print_function
29
30
30 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
31 # Copyright (C) 2008 The IPython Development Team
32 # Copyright (C) 2008 The IPython Development Team
@@ -251,7 +252,7 b' class ParallelMagics(Magics):'
251 else:
252 else:
252 str_targets = str(targets)
253 str_targets = str(targets)
253 if self.verbose:
254 if self.verbose:
254 print base + " execution on engine(s): %s" % str_targets
255 print(base + " execution on engine(s): %s" % str_targets)
255
256
256 result = self.view.execute(cell, silent=False, block=False)
257 result = self.view.execute(cell, silent=False, block=False)
257 self.last_result = result
258 self.last_result = result
@@ -358,7 +359,7 b' class ParallelMagics(Magics):'
358 self.shell.run_cell = self.pxrun_cell
359 self.shell.run_cell = self.pxrun_cell
359
360
360 self._autopx = True
361 self._autopx = True
361 print "%autopx enabled"
362 print("%autopx enabled")
362
363
363 def _disable_autopx(self):
364 def _disable_autopx(self):
364 """Disable %autopx by restoring the original InteractiveShell.run_cell.
365 """Disable %autopx by restoring the original InteractiveShell.run_cell.
@@ -366,7 +367,7 b' class ParallelMagics(Magics):'
366 if self._autopx:
367 if self._autopx:
367 self.shell.run_cell = self._original_run_cell
368 self.shell.run_cell = self._original_run_cell
368 self._autopx = False
369 self._autopx = False
369 print "%autopx disabled"
370 print("%autopx disabled")
370
371
371 def pxrun_cell(self, raw_cell, store_history=False, silent=False):
372 def pxrun_cell(self, raw_cell, store_history=False, silent=False):
372 """drop-in replacement for InteractiveShell.run_cell.
373 """drop-in replacement for InteractiveShell.run_cell.
@@ -26,7 +26,6 b' Authors:'
26
26
27 from __future__ import division
27 from __future__ import division
28
28
29 import types
30 from itertools import islice
29 from itertools import islice
31
30
32 from IPython.utils.data import flatten as utils_flatten
31 from IPython.utils.data import flatten as utils_flatten
@@ -100,7 +99,7 b' class Map(object):'
100 if isinstance(testObject, m['type']):
99 if isinstance(testObject, m['type']):
101 return m['module'].concatenate(listOfPartitions)
100 return m['module'].concatenate(listOfPartitions)
102 # Next try for Python sequence types
101 # Next try for Python sequence types
103 if isinstance(testObject, (types.ListType, types.TupleType)):
102 if isinstance(testObject, (list, tuple)):
104 return utils_flatten(listOfPartitions)
103 return utils_flatten(listOfPartitions)
105 # If we have scalars, just return listOfPartitions
104 # If we have scalars, just return listOfPartitions
106 return listOfPartitions
105 return listOfPartitions
@@ -122,7 +121,7 b' class RoundRobinMap(Map):'
122 #print m
121 #print m
123 if isinstance(testObject, m['type']):
122 if isinstance(testObject, m['type']):
124 return self.flatten_array(m['type'], listOfPartitions)
123 return self.flatten_array(m['type'], listOfPartitions)
125 if isinstance(testObject, (types.ListType, types.TupleType)):
124 if isinstance(testObject, (list, tuple)):
126 return self.flatten_list(listOfPartitions)
125 return self.flatten_list(listOfPartitions)
127 return listOfPartitions
126 return listOfPartitions
128
127
@@ -4,6 +4,7 b' Authors:'
4
4
5 * Min RK
5 * Min RK
6 """
6 """
7 from __future__ import print_function
7 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
8 # Copyright (C) 2010-2011 The IPython Development Team
9 # Copyright (C) 2010-2011 The IPython Development Team
9 #
10 #
@@ -31,6 +32,7 b' from IPython.external.decorator import decorator'
31
32
32 from IPython.parallel import util
33 from IPython.parallel import util
33 from IPython.parallel.controller.dependency import Dependency, dependent
34 from IPython.parallel.controller.dependency import Dependency, dependent
35 from IPython.utils.py3compat import string_types, iteritems, PY3
34
36
35 from . import map as Map
37 from . import map as Map
36 from .asyncresult import AsyncResult, AsyncMapResult
38 from .asyncresult import AsyncResult, AsyncMapResult
@@ -50,7 +52,7 b' def save_ids(f, self, *args, **kwargs):'
50 nmsgs = len(self.client.history) - n_previous
52 nmsgs = len(self.client.history) - n_previous
51 msg_ids = self.client.history[-nmsgs:]
53 msg_ids = self.client.history[-nmsgs:]
52 self.history.extend(msg_ids)
54 self.history.extend(msg_ids)
53 map(self.outstanding.add, msg_ids)
55 self.outstanding.update(msg_ids)
54 return ret
56 return ret
55
57
56 @decorator
58 @decorator
@@ -162,7 +164,7 b' class View(HasTraits):'
162 safely edit after arrays and buffers during non-copying
164 safely edit after arrays and buffers during non-copying
163 sends.
165 sends.
164 """
166 """
165 for name, value in kwargs.iteritems():
167 for name, value in iteritems(kwargs):
166 if name not in self._flag_names:
168 if name not in self._flag_names:
167 raise KeyError("Invalid name: %r"%name)
169 raise KeyError("Invalid name: %r"%name)
168 else:
170 else:
@@ -439,8 +441,8 b' class DirectView(View):'
439 importing recarray from numpy on engine(s)
441 importing recarray from numpy on engine(s)
440
442
441 """
443 """
442 import __builtin__
444 from IPython.utils.py3compat import builtin_mod
443 local_import = __builtin__.__import__
445 local_import = builtin_mod.__import__
444 modules = set()
446 modules = set()
445 results = []
447 results = []
446 @util.interactive
448 @util.interactive
@@ -462,8 +464,8 b' class DirectView(View):'
462 locally as well.
464 locally as well.
463 """
465 """
464 # don't override nested imports
466 # don't override nested imports
465 save_import = __builtin__.__import__
467 save_import = builtin_mod.__import__
466 __builtin__.__import__ = local_import
468 builtin_mod.__import__ = local_import
467
469
468 if imp.lock_held():
470 if imp.lock_held():
469 # this is a side-effect import, don't do it remotely, or even
471 # this is a side-effect import, don't do it remotely, or even
@@ -482,17 +484,17 b' class DirectView(View):'
482 modules.add(key)
484 modules.add(key)
483 if not quiet:
485 if not quiet:
484 if fromlist:
486 if fromlist:
485 print "importing %s from %s on engine(s)"%(','.join(fromlist), name)
487 print("importing %s from %s on engine(s)"%(','.join(fromlist), name))
486 else:
488 else:
487 print "importing %s on engine(s)"%name
489 print("importing %s on engine(s)"%name)
488 results.append(self.apply_async(remote_import, name, fromlist, level))
490 results.append(self.apply_async(remote_import, name, fromlist, level))
489 # restore override
491 # restore override
490 __builtin__.__import__ = save_import
492 builtin_mod.__import__ = save_import
491
493
492 return mod
494 return mod
493
495
494 # override __import__
496 # override __import__
495 __builtin__.__import__ = view_import
497 builtin_mod.__import__ = view_import
496 try:
498 try:
497 # enter the block
499 # enter the block
498 yield
500 yield
@@ -504,7 +506,7 b' class DirectView(View):'
504 pass
506 pass
505 finally:
507 finally:
506 # always restore __import__
508 # always restore __import__
507 __builtin__.__import__ = local_import
509 builtin_mod.__import__ = local_import
508
510
509 for r in results:
511 for r in results:
510 # raise possible remote ImportErrors here
512 # raise possible remote ImportErrors here
@@ -718,11 +720,11 b' class DirectView(View):'
718 block = block if block is not None else self.block
720 block = block if block is not None else self.block
719 targets = targets if targets is not None else self.targets
721 targets = targets if targets is not None else self.targets
720 applier = self.apply_sync if block else self.apply_async
722 applier = self.apply_sync if block else self.apply_async
721 if isinstance(names, basestring):
723 if isinstance(names, string_types):
722 pass
724 pass
723 elif isinstance(names, (list,tuple,set)):
725 elif isinstance(names, (list,tuple,set)):
724 for key in names:
726 for key in names:
725 if not isinstance(key, basestring):
727 if not isinstance(key, string_types):
726 raise TypeError("keys must be str, not type %r"%type(key))
728 raise TypeError("keys must be str, not type %r"%type(key))
727 else:
729 else:
728 raise TypeError("names must be strs, not %r"%names)
730 raise TypeError("names must be strs, not %r"%names)
@@ -830,7 +832,7 b' class DirectView(View):'
830 # This is injected into __builtins__.
832 # This is injected into __builtins__.
831 ip = get_ipython()
833 ip = get_ipython()
832 except NameError:
834 except NameError:
833 print "The IPython parallel magics (%px, etc.) only work within IPython."
835 print("The IPython parallel magics (%px, etc.) only work within IPython.")
834 return
836 return
835
837
836 M = ParallelMagics(ip, self, suffix)
838 M = ParallelMagics(ip, self, suffix)
@@ -870,11 +872,11 b' class LoadBalancedView(View):'
870
872
871 For use in `set_flags`.
873 For use in `set_flags`.
872 """
874 """
873 if dep is None or isinstance(dep, (basestring, AsyncResult, Dependency)):
875 if dep is None or isinstance(dep, string_types + (AsyncResult, Dependency)):
874 return True
876 return True
875 elif isinstance(dep, (list,set, tuple)):
877 elif isinstance(dep, (list,set, tuple)):
876 for d in dep:
878 for d in dep:
877 if not isinstance(d, (basestring, AsyncResult)):
879 if not isinstance(d, string_types + (AsyncResult,)):
878 return False
880 return False
879 elif isinstance(dep, dict):
881 elif isinstance(dep, dict):
880 if set(dep.keys()) != set(Dependency().as_dict().keys()):
882 if set(dep.keys()) != set(Dependency().as_dict().keys()):
@@ -882,7 +884,7 b' class LoadBalancedView(View):'
882 if not isinstance(dep['msg_ids'], list):
884 if not isinstance(dep['msg_ids'], list):
883 return False
885 return False
884 for d in dep['msg_ids']:
886 for d in dep['msg_ids']:
885 if not isinstance(d, basestring):
887 if not isinstance(d, string_types):
886 return False
888 return False
887 else:
889 else:
888 return False
890 return False
@@ -950,8 +952,9 b' class LoadBalancedView(View):'
950 raise ValueError("Invalid dependency: %r"%value)
952 raise ValueError("Invalid dependency: %r"%value)
951 if 'timeout' in kwargs:
953 if 'timeout' in kwargs:
952 t = kwargs['timeout']
954 t = kwargs['timeout']
953 if not isinstance(t, (int, long, float, type(None))):
955 if not isinstance(t, (int, float, type(None))):
954 raise TypeError("Invalid type for timeout: %r"%type(t))
956 if (not PY3) and (not isinstance(t, long)):
957 raise TypeError("Invalid type for timeout: %r"%type(t))
955 if t is not None:
958 if t is not None:
956 if t < 0:
959 if t < 0:
957 raise ValueError("Invalid timeout: %s"%t)
960 raise ValueError("Invalid timeout: %s"%t)
@@ -17,6 +17,7 b' from IPython.parallel.client.asyncresult import AsyncResult'
17 from IPython.parallel.error import UnmetDependency
17 from IPython.parallel.error import UnmetDependency
18 from IPython.parallel.util import interactive
18 from IPython.parallel.util import interactive
19 from IPython.utils import py3compat
19 from IPython.utils import py3compat
20 from IPython.utils.py3compat import string_types
20 from IPython.utils.pickleutil import can, uncan
21 from IPython.utils.pickleutil import can, uncan
21
22
22 class depend(object):
23 class depend(object):
@@ -55,7 +56,11 b' class dependent(object):'
55
56
56 def __init__(self, f, df, *dargs, **dkwargs):
57 def __init__(self, f, df, *dargs, **dkwargs):
57 self.f = f
58 self.f = f
58 self.func_name = getattr(f, '__name__', 'f')
59 name = getattr(f, '__name__', 'f')
60 if py3compat.PY3:
61 self.__name__ = name
62 else:
63 self.func_name = name
59 self.df = df
64 self.df = df
60 self.dargs = dargs
65 self.dargs = dargs
61 self.dkwargs = dkwargs
66 self.dkwargs = dkwargs
@@ -80,7 +85,7 b' def _require(*modules, **mapping):'
80 user_ns = globals()
85 user_ns = globals()
81 for name in modules:
86 for name in modules:
82 try:
87 try:
83 exec 'import %s' % name in user_ns
88 exec('import %s' % name, user_ns)
84 except ImportError:
89 except ImportError:
85 raise UnmetDependency(name)
90 raise UnmetDependency(name)
86
91
@@ -117,7 +122,7 b' def require(*objects, **mapping):'
117 if isinstance(obj, ModuleType):
122 if isinstance(obj, ModuleType):
118 obj = obj.__name__
123 obj = obj.__name__
119
124
120 if isinstance(obj, basestring):
125 if isinstance(obj, string_types):
121 names.append(obj)
126 names.append(obj)
122 elif hasattr(obj, '__name__'):
127 elif hasattr(obj, '__name__'):
123 mapping[obj.__name__] = obj
128 mapping[obj.__name__] = obj
@@ -165,10 +170,10 b' class Dependency(set):'
165 ids = []
170 ids = []
166
171
167 # extract ids from various sources:
172 # extract ids from various sources:
168 if isinstance(dependencies, (basestring, AsyncResult)):
173 if isinstance(dependencies, string_types + (AsyncResult,)):
169 dependencies = [dependencies]
174 dependencies = [dependencies]
170 for d in dependencies:
175 for d in dependencies:
171 if isinstance(d, basestring):
176 if isinstance(d, string_types):
172 ids.append(d)
177 ids.append(d)
173 elif isinstance(d, AsyncResult):
178 elif isinstance(d, AsyncResult):
174 ids.extend(d.msg_ids)
179 ids.extend(d.msg_ids)
@@ -51,6 +51,7 b' from datetime import datetime'
51
51
52 from IPython.config.configurable import LoggingConfigurable
52 from IPython.config.configurable import LoggingConfigurable
53
53
54 from IPython.utils.py3compat import iteritems, itervalues
54 from IPython.utils.traitlets import Dict, Unicode, Integer, Float
55 from IPython.utils.traitlets import Dict, Unicode, Integer, Float
55
56
56 filters = {
57 filters = {
@@ -74,7 +75,7 b' class CompositeFilter(object):'
74 def __init__(self, dikt):
75 def __init__(self, dikt):
75 self.tests = []
76 self.tests = []
76 self.values = []
77 self.values = []
77 for key, value in dikt.iteritems():
78 for key, value in iteritems(dikt):
78 self.tests.append(filters[key])
79 self.tests.append(filters[key])
79 self.values.append(value)
80 self.values.append(value)
80
81
@@ -131,7 +132,7 b' class DictDB(BaseDB):'
131
132
132 def _match_one(self, rec, tests):
133 def _match_one(self, rec, tests):
133 """Check if a specific record matches tests."""
134 """Check if a specific record matches tests."""
134 for key,test in tests.iteritems():
135 for key,test in iteritems(tests):
135 if not test(rec.get(key, None)):
136 if not test(rec.get(key, None)):
136 return False
137 return False
137 return True
138 return True
@@ -140,13 +141,13 b' class DictDB(BaseDB):'
140 """Find all the matches for a check dict."""
141 """Find all the matches for a check dict."""
141 matches = []
142 matches = []
142 tests = {}
143 tests = {}
143 for k,v in check.iteritems():
144 for k,v in iteritems(check):
144 if isinstance(v, dict):
145 if isinstance(v, dict):
145 tests[k] = CompositeFilter(v)
146 tests[k] = CompositeFilter(v)
146 else:
147 else:
147 tests[k] = lambda o: o==v
148 tests[k] = lambda o: o==v
148
149
149 for rec in self._records.itervalues():
150 for rec in itervalues(self._records):
150 if self._match_one(rec, tests):
151 if self._match_one(rec, tests):
151 matches.append(copy(rec))
152 matches.append(copy(rec))
152 return matches
153 return matches
@@ -125,10 +125,12 b' class HeartMonitor(LoggingConfigurable):'
125 goodhearts = self.hearts.intersection(self.responses)
125 goodhearts = self.hearts.intersection(self.responses)
126 missed_beats = self.hearts.difference(goodhearts)
126 missed_beats = self.hearts.difference(goodhearts)
127 newhearts = self.responses.difference(goodhearts)
127 newhearts = self.responses.difference(goodhearts)
128 map(self.handle_new_heart, newhearts)
128 for heart in newhearts:
129 self.handle_new_heart(heart)
129 heartfailures, on_probation = self._check_missed(missed_beats, self.on_probation,
130 heartfailures, on_probation = self._check_missed(missed_beats, self.on_probation,
130 self.hearts)
131 self.hearts)
131 map(self.handle_heart_failure, heartfailures)
132 for failure in heartfailures:
133 self.handle_heart_failure(failure)
132 self.on_probation = on_probation
134 self.on_probation = on_probation
133 self.responses = set()
135 self.responses = set()
134 #print self.on_probation, self.hearts
136 #print self.on_probation, self.hearts
@@ -31,7 +31,7 b' from zmq.eventloop.zmqstream import ZMQStream'
31 # internal:
31 # internal:
32 from IPython.utils.importstring import import_item
32 from IPython.utils.importstring import import_item
33 from IPython.utils.localinterfaces import localhost
33 from IPython.utils.localinterfaces import localhost
34 from IPython.utils.py3compat import cast_bytes
34 from IPython.utils.py3compat import cast_bytes, unicode_type, iteritems
35 from IPython.utils.traitlets import (
35 from IPython.utils.traitlets import (
36 HasTraits, Instance, Integer, Unicode, Dict, Set, Tuple, CBytes, DottedObjectName
36 HasTraits, Instance, Integer, Unicode, Dict, Set, Tuple, CBytes, DottedObjectName
37 )
37 )
@@ -193,9 +193,9 b' class HubFactory(RegistrationFactory):'
193 help="IP on which to listen for monitor messages. [default: loopback]")
193 help="IP on which to listen for monitor messages. [default: loopback]")
194 monitor_transport = Unicode('tcp', config=True,
194 monitor_transport = Unicode('tcp', config=True,
195 help="0MQ transport for monitor messages. [default : tcp]")
195 help="0MQ transport for monitor messages. [default : tcp]")
196
196
197 _client_ip_default = _monitor_ip_default = _engine_ip_default
197 _client_ip_default = _monitor_ip_default = _engine_ip_default
198
198
199
199
200 monitor_url = Unicode('')
200 monitor_url = Unicode('')
201
201
@@ -455,7 +455,7 b' class Hub(SessionFactory):'
455 self._idcounter += 1
455 self._idcounter += 1
456 return newid
456 return newid
457 # newid = 0
457 # newid = 0
458 # incoming = [id[0] for id in self.incoming_registrations.itervalues()]
458 # incoming = [id[0] for id in itervalues(self.incoming_registrations)]
459 # # print newid, self.ids, self.incoming_registrations
459 # # print newid, self.ids, self.incoming_registrations
460 # while newid in self.ids or newid in incoming:
460 # while newid in self.ids or newid in incoming:
461 # newid += 1
461 # newid += 1
@@ -471,13 +471,13 b' class Hub(SessionFactory):'
471 # default to all
471 # default to all
472 return self.ids
472 return self.ids
473
473
474 if isinstance(targets, (int,str,unicode)):
474 if isinstance(targets, (int,str,unicode_type)):
475 # only one target specified
475 # only one target specified
476 targets = [targets]
476 targets = [targets]
477 _targets = []
477 _targets = []
478 for t in targets:
478 for t in targets:
479 # map raw identities to ids
479 # map raw identities to ids
480 if isinstance(t, (str,unicode)):
480 if isinstance(t, (str,unicode_type)):
481 t = self.by_ident.get(cast_bytes(t), t)
481 t = self.by_ident.get(cast_bytes(t), t)
482 _targets.append(t)
482 _targets.append(t)
483 targets = _targets
483 targets = _targets
@@ -611,7 +611,7 b' class Hub(SessionFactory):'
611 try:
611 try:
612 # it's posible iopub arrived first:
612 # it's posible iopub arrived first:
613 existing = self.db.get_record(msg_id)
613 existing = self.db.get_record(msg_id)
614 for key,evalue in existing.iteritems():
614 for key,evalue in iteritems(existing):
615 rvalue = record.get(key, None)
615 rvalue = record.get(key, None)
616 if evalue and rvalue and evalue != rvalue:
616 if evalue and rvalue and evalue != rvalue:
617 self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue)
617 self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue)
@@ -717,7 +717,7 b' class Hub(SessionFactory):'
717 # still check content,header which should not change
717 # still check content,header which should not change
718 # but are not expensive to compare as buffers
718 # but are not expensive to compare as buffers
719
719
720 for key,evalue in existing.iteritems():
720 for key,evalue in iteritems(existing):
721 if key.endswith('buffers'):
721 if key.endswith('buffers'):
722 # don't compare buffers
722 # don't compare buffers
723 continue
723 continue
@@ -892,7 +892,7 b' class Hub(SessionFactory):'
892 self.log.info("client::client %r connected", client_id)
892 self.log.info("client::client %r connected", client_id)
893 content = dict(status='ok')
893 content = dict(status='ok')
894 jsonable = {}
894 jsonable = {}
895 for k,v in self.keytable.iteritems():
895 for k,v in iteritems(self.keytable):
896 if v not in self.dead_engines:
896 if v not in self.dead_engines:
897 jsonable[str(k)] = v
897 jsonable[str(k)] = v
898 content['engines'] = jsonable
898 content['engines'] = jsonable
@@ -920,7 +920,7 b' class Hub(SessionFactory):'
920 content = error.wrap_exception()
920 content = error.wrap_exception()
921 self.log.error("uuid %r in use", uuid, exc_info=True)
921 self.log.error("uuid %r in use", uuid, exc_info=True)
922 else:
922 else:
923 for h, ec in self.incoming_registrations.iteritems():
923 for h, ec in iteritems(self.incoming_registrations):
924 if uuid == h:
924 if uuid == h:
925 try:
925 try:
926 raise KeyError("heart_id %r in use" % uuid)
926 raise KeyError("heart_id %r in use" % uuid)
@@ -1073,7 +1073,7 b' class Hub(SessionFactory):'
1073 self.log.debug("save engine state to %s" % self.engine_state_file)
1073 self.log.debug("save engine state to %s" % self.engine_state_file)
1074 state = {}
1074 state = {}
1075 engines = {}
1075 engines = {}
1076 for eid, ec in self.engines.iteritems():
1076 for eid, ec in iteritems(self.engines):
1077 if ec.uuid not in self.dead_engines:
1077 if ec.uuid not in self.dead_engines:
1078 engines[eid] = ec.uuid
1078 engines[eid] = ec.uuid
1079
1079
@@ -1097,7 +1097,7 b' class Hub(SessionFactory):'
1097
1097
1098 save_notifier = self.notifier
1098 save_notifier = self.notifier
1099 self.notifier = None
1099 self.notifier = None
1100 for eid, uuid in state['engines'].iteritems():
1100 for eid, uuid in iteritems(state['engines']):
1101 heart = uuid.encode('ascii')
1101 heart = uuid.encode('ascii')
1102 # start with this heart as current and beating:
1102 # start with this heart as current and beating:
1103 self.heartmonitor.responses.add(heart)
1103 self.heartmonitor.responses.add(heart)
@@ -1190,7 +1190,7 b' class Hub(SessionFactory):'
1190 except Exception:
1190 except Exception:
1191 reply = error.wrap_exception()
1191 reply = error.wrap_exception()
1192 else:
1192 else:
1193 pending = filter(lambda m: m in self.pending, msg_ids)
1193 pending = [m for m in msg_ids if (m in self.pending)]
1194 if pending:
1194 if pending:
1195 try:
1195 try:
1196 raise IndexError("msg pending: %r" % pending[0])
1196 raise IndexError("msg pending: %r" % pending[0])
@@ -1290,7 +1290,7 b' class Hub(SessionFactory):'
1290 finish(dict(status='ok', resubmitted=resubmitted))
1290 finish(dict(status='ok', resubmitted=resubmitted))
1291
1291
1292 # store the new IDs in the Task DB
1292 # store the new IDs in the Task DB
1293 for msg_id, resubmit_id in resubmitted.iteritems():
1293 for msg_id, resubmit_id in iteritems(resubmitted):
1294 try:
1294 try:
1295 self.db.update_record(msg_id, {'resubmitted' : resubmit_id})
1295 self.db.update_record(msg_id, {'resubmitted' : resubmit_id})
1296 except Exception:
1296 except Exception:
@@ -1312,7 +1312,7 b' class Hub(SessionFactory):'
1312 'io' : io_dict,
1312 'io' : io_dict,
1313 }
1313 }
1314 if rec['result_buffers']:
1314 if rec['result_buffers']:
1315 buffers = map(bytes, rec['result_buffers'])
1315 buffers = list(map(bytes, rec['result_buffers']))
1316 else:
1316 else:
1317 buffers = []
1317 buffers = []
1318
1318
@@ -62,7 +62,7 b' class MongoDB(BaseDB):'
62 def _binary_buffers(self, rec):
62 def _binary_buffers(self, rec):
63 for key in ('buffers', 'result_buffers'):
63 for key in ('buffers', 'result_buffers'):
64 if rec.get(key, None):
64 if rec.get(key, None):
65 rec[key] = map(Binary, rec[key])
65 rec[key] = list(map(Binary, rec[key]))
66 return rec
66 return rec
67
67
68 def add_record(self, msg_id, rec):
68 def add_record(self, msg_id, rec):
@@ -52,7 +52,7 b' from .dependency import Dependency'
52 @decorator
52 @decorator
53 def logged(f,self,*args,**kwargs):
53 def logged(f,self,*args,**kwargs):
54 # print ("#--------------------")
54 # print ("#--------------------")
55 self.log.debug("scheduler::%s(*%s,**%s)", f.func_name, args, kwargs)
55 self.log.debug("scheduler::%s(*%s,**%s)", f.__name__, args, kwargs)
56 # print ("#--")
56 # print ("#--")
57 return f(self,*args, **kwargs)
57 return f(self,*args, **kwargs)
58
58
@@ -364,7 +364,7 b' class TaskScheduler(SessionFactory):'
364 date=datetime.now(),
364 date=datetime.now(),
365 )
365 )
366 msg = self.session.msg('apply_reply', content, parent=parent, metadata=md)
366 msg = self.session.msg('apply_reply', content, parent=parent, metadata=md)
367 raw_reply = map(zmq.Message, self.session.serialize(msg, ident=idents))
367 raw_reply = list(map(zmq.Message, self.session.serialize(msg, ident=idents)))
368 # and dispatch it
368 # and dispatch it
369 self.dispatch_result(raw_reply)
369 self.dispatch_result(raw_reply)
370
370
@@ -402,8 +402,7 b' class TaskScheduler(SessionFactory):'
402 # get targets as a set of bytes objects
402 # get targets as a set of bytes objects
403 # from a list of unicode objects
403 # from a list of unicode objects
404 targets = md.get('targets', [])
404 targets = md.get('targets', [])
405 targets = map(cast_bytes, targets)
405 targets = set(map(cast_bytes, targets))
406 targets = set(targets)
407
406
408 retries = md.get('retries', 0)
407 retries = md.get('retries', 0)
409 self.retries[msg_id] = retries
408 self.retries[msg_id] = retries
@@ -515,7 +514,7 b' class TaskScheduler(SessionFactory):'
515 def available_engines(self):
514 def available_engines(self):
516 """return a list of available engine indices based on HWM"""
515 """return a list of available engine indices based on HWM"""
517 if not self.hwm:
516 if not self.hwm:
518 return range(len(self.targets))
517 return list(range(len(self.targets)))
519 available = []
518 available = []
520 for idx in range(len(self.targets)):
519 for idx in range(len(self.targets)):
521 if self.loads[idx] < self.hwm:
520 if self.loads[idx] < self.hwm:
@@ -547,7 +546,7 b' class TaskScheduler(SessionFactory):'
547 # check follow
546 # check follow
548 return job.follow.check(self.completed[target], self.failed[target])
547 return job.follow.check(self.completed[target], self.failed[target])
549
548
550 indices = filter(can_run, available)
549 indices = list(filter(can_run, available))
551
550
552 if not indices:
551 if not indices:
553 # couldn't run
552 # couldn't run
@@ -13,7 +13,10 b' Authors:'
13
13
14 import json
14 import json
15 import os
15 import os
16 import cPickle as pickle
16 try:
17 import cPickle as pickle
18 except ImportError:
19 import pickle
17 from datetime import datetime
20 from datetime import datetime
18
21
19 try:
22 try:
@@ -26,6 +29,7 b' from zmq.eventloop import ioloop'
26 from IPython.utils.traitlets import Unicode, Instance, List, Dict
29 from IPython.utils.traitlets import Unicode, Instance, List, Dict
27 from .dictdb import BaseDB
30 from .dictdb import BaseDB
28 from IPython.utils.jsonutil import date_default, extract_dates, squash_dates
31 from IPython.utils.jsonutil import date_default, extract_dates, squash_dates
32 from IPython.utils.py3compat import iteritems
29
33
30 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
31 # SQLite operators, adapters, and converters
35 # SQLite operators, adapters, and converters
@@ -72,7 +76,7 b' def _adapt_bufs(bufs):'
72 # this is *horrible*
76 # this is *horrible*
73 # copy buffers into single list and pickle it:
77 # copy buffers into single list and pickle it:
74 if bufs and isinstance(bufs[0], (bytes, buffer)):
78 if bufs and isinstance(bufs[0], (bytes, buffer)):
75 return sqlite3.Binary(pickle.dumps(map(bytes, bufs),-1))
79 return sqlite3.Binary(pickle.dumps(list(map(bytes, bufs)),-1))
76 elif bufs:
80 elif bufs:
77 return bufs
81 return bufs
78 else:
82 else:
@@ -292,9 +296,9 b' class SQLiteDB(BaseDB):'
292 if skeys:
296 if skeys:
293 raise KeyError("Illegal testing key(s): %s"%skeys)
297 raise KeyError("Illegal testing key(s): %s"%skeys)
294
298
295 for name,sub_check in check.iteritems():
299 for name,sub_check in iteritems(check):
296 if isinstance(sub_check, dict):
300 if isinstance(sub_check, dict):
297 for test,value in sub_check.iteritems():
301 for test,value in iteritems(sub_check):
298 try:
302 try:
299 op = operators[test]
303 op = operators[test]
300 except KeyError:
304 except KeyError:
@@ -17,6 +17,8 b' from __future__ import print_function'
17 import sys
17 import sys
18 import traceback
18 import traceback
19
19
20 from IPython.utils.py3compat import unicode_type
21
20 __docformat__ = "restructuredtext en"
22 __docformat__ = "restructuredtext en"
21
23
22 # Tell nose to skip this module
24 # Tell nose to skip this module
@@ -236,8 +238,8 b' def wrap_exception(engine_info={}):'
236 exc_content = {
238 exc_content = {
237 'status' : 'error',
239 'status' : 'error',
238 'traceback' : stb,
240 'traceback' : stb,
239 'ename' : unicode(etype.__name__),
241 'ename' : unicode_type(etype.__name__),
240 'evalue' : unicode(evalue),
242 'evalue' : unicode_type(evalue),
241 'engine_info' : engine_info
243 'engine_info' : engine_info
242 }
244 }
243 return exc_content
245 return exc_content
@@ -1,4 +1,5 b''
1 """toplevel setup/teardown for parallel tests."""
1 """toplevel setup/teardown for parallel tests."""
2 from __future__ import print_function
2
3
3 #-------------------------------------------------------------------------------
4 #-------------------------------------------------------------------------------
4 # Copyright (C) 2011 The IPython Development Team
5 # Copyright (C) 2011 The IPython Development Team
@@ -118,15 +119,15 b' def teardown():'
118 try:
119 try:
119 p.stop()
120 p.stop()
120 except Exception as e:
121 except Exception as e:
121 print e
122 print(e)
122 pass
123 pass
123 if p.poll() is None:
124 if p.poll() is None:
124 time.sleep(.25)
125 time.sleep(.25)
125 if p.poll() is None:
126 if p.poll() is None:
126 try:
127 try:
127 print 'cleaning up test process...'
128 print('cleaning up test process...')
128 p.signal(SIGKILL)
129 p.signal(SIGKILL)
129 except:
130 except:
130 print "couldn't shutdown process: ", p
131 print("couldn't shutdown process: ", p)
131 blackhole.close()
132 blackhole.close()
132
133
@@ -16,7 +16,6 b' from __future__ import print_function'
16 import sys
16 import sys
17 import tempfile
17 import tempfile
18 import time
18 import time
19 from StringIO import StringIO
20
19
21 from nose import SkipTest
20 from nose import SkipTest
22
21
@@ -26,6 +26,7 b' from IPython.parallel.error import TimeoutError'
26 from IPython.parallel import error, Client
26 from IPython.parallel import error, Client
27 from IPython.parallel.tests import add_engines
27 from IPython.parallel.tests import add_engines
28 from .clienttest import ClusterTestCase
28 from .clienttest import ClusterTestCase
29 from IPython.utils.py3compat import iteritems
29
30
30 def setup():
31 def setup():
31 add_engines(2, total=True)
32 add_engines(2, total=True)
@@ -77,12 +78,12 b' class AsyncResultTest(ClusterTestCase):'
77 self.assertEqual(ar.get(), [5]*n)
78 self.assertEqual(ar.get(), [5]*n)
78 d = ar.get_dict()
79 d = ar.get_dict()
79 self.assertEqual(sorted(d.keys()), sorted(self.client.ids))
80 self.assertEqual(sorted(d.keys()), sorted(self.client.ids))
80 for eid,r in d.iteritems():
81 for eid,r in iteritems(d):
81 self.assertEqual(r, 5)
82 self.assertEqual(r, 5)
82
83
83 def test_get_dict_single(self):
84 def test_get_dict_single(self):
84 view = self.client[-1]
85 view = self.client[-1]
85 for v in (range(5), 5, ('abc', 'def'), 'string'):
86 for v in (list(range(5)), 5, ('abc', 'def'), 'string'):
86 ar = view.apply_async(echo, v)
87 ar = view.apply_async(echo, v)
87 self.assertEqual(ar.get(), v)
88 self.assertEqual(ar.get(), v)
88 d = ar.get_dict()
89 d = ar.get_dict()
@@ -145,11 +146,11 b' class AsyncResultTest(ClusterTestCase):'
145
146
146 def test_len(self):
147 def test_len(self):
147 v = self.client.load_balanced_view()
148 v = self.client.load_balanced_view()
148 ar = v.map_async(lambda x: x, range(10))
149 ar = v.map_async(lambda x: x, list(range(10)))
149 self.assertEqual(len(ar), 10)
150 self.assertEqual(len(ar), 10)
150 ar = v.apply_async(lambda x: x, range(10))
151 ar = v.apply_async(lambda x: x, list(range(10)))
151 self.assertEqual(len(ar), 1)
152 self.assertEqual(len(ar), 1)
152 ar = self.client[:].apply_async(lambda x: x, range(10))
153 ar = self.client[:].apply_async(lambda x: x, list(range(10)))
153 self.assertEqual(len(ar), len(self.client.ids))
154 self.assertEqual(len(ar), len(self.client.ids))
154
155
155 def test_wall_time_single(self):
156 def test_wall_time_single(self):
@@ -30,7 +30,7 b' from IPython.parallel import error'
30 from IPython.parallel import AsyncResult, AsyncHubResult
30 from IPython.parallel import AsyncResult, AsyncHubResult
31 from IPython.parallel import LoadBalancedView, DirectView
31 from IPython.parallel import LoadBalancedView, DirectView
32
32
33 from clienttest import ClusterTestCase, segfault, wait, add_engines
33 from .clienttest import ClusterTestCase, segfault, wait, add_engines
34
34
35 def setup():
35 def setup():
36 add_engines(4, total=True)
36 add_engines(4, total=True)
@@ -95,7 +95,7 b' class TestClient(ClusterTestCase):'
95
95
96 def double(x):
96 def double(x):
97 return x*2
97 return x*2
98 seq = range(100)
98 seq = list(range(100))
99 ref = [ double(x) for x in seq ]
99 ref = [ double(x) for x in seq ]
100
100
101 # add some engines, which should be used
101 # add some engines, which should be used
@@ -41,9 +41,9 b' def wait(n):'
41 def func(x):
41 def func(x):
42 return x*x
42 return x*x
43
43
44 mixed = map(str, range(10))
44 mixed = list(map(str, range(10)))
45 completed = map(str, range(0,10,2))
45 completed = list(map(str, range(0,10,2)))
46 failed = map(str, range(1,10,2))
46 failed = list(map(str, range(1,10,2)))
47
47
48 class DependencyTest(ClusterTestCase):
48 class DependencyTest(ClusterTestCase):
49
49
@@ -74,12 +74,12 b' class DependencyTest(ClusterTestCase):'
74 def test_require_imports(self):
74 def test_require_imports(self):
75 """test that @require imports names"""
75 """test that @require imports names"""
76 @self.cancan
76 @self.cancan
77 @pmod.require('urllib')
77 @pmod.require('base64')
78 @interactive
78 @interactive
79 def encode(dikt):
79 def encode(arg):
80 return urllib.urlencode(dikt)
80 return base64.b64encode(arg)
81 # must pass through canning to properly connect namespaces
81 # must pass through canning to properly connect namespaces
82 self.assertEqual(encode(dict(a=5)), 'a=5')
82 self.assertEqual(encode(b'foo'), b'Zm9v')
83
83
84 def test_success_only(self):
84 def test_success_only(self):
85 dep = pmod.Dependency(mixed, success=True, failure=False)
85 dep = pmod.Dependency(mixed, success=True, failure=False)
@@ -34,6 +34,7 b' from IPython.config import Config'
34 from IPython.parallel.apps import launcher
34 from IPython.parallel.apps import launcher
35
35
36 from IPython.testing import decorators as dec
36 from IPython.testing import decorators as dec
37 from IPython.utils.py3compat import string_types
37
38
38
39
39 #-------------------------------------------------------------------------------
40 #-------------------------------------------------------------------------------
@@ -79,7 +80,7 b' class LauncherTest:'
79 def test_args(self):
80 def test_args(self):
80 launcher = self.build_launcher()
81 launcher = self.build_launcher()
81 for arg in launcher.args:
82 for arg in launcher.args:
82 self.assertTrue(isinstance(arg, basestring), str(arg))
83 self.assertTrue(isinstance(arg, string_types), str(arg))
83
84
84 class BatchTest:
85 class BatchTest:
85 """Tests for batch-system launchers (LSF, SGE, PBS)"""
86 """Tests for batch-system launchers (LSF, SGE, PBS)"""
@@ -55,17 +55,17 b' class TestLoadBalancedView(ClusterTestCase):'
55 def test_map(self):
55 def test_map(self):
56 def f(x):
56 def f(x):
57 return x**2
57 return x**2
58 data = range(16)
58 data = list(range(16))
59 r = self.view.map_sync(f, data)
59 r = self.view.map_sync(f, data)
60 self.assertEqual(r, map(f, data))
60 self.assertEqual(r, list(map(f, data)))
61
61
62 def test_map_generator(self):
62 def test_map_generator(self):
63 def f(x):
63 def f(x):
64 return x**2
64 return x**2
65
65
66 data = range(16)
66 data = list(range(16))
67 r = self.view.map_sync(f, iter(data))
67 r = self.view.map_sync(f, iter(data))
68 self.assertEqual(r, map(f, iter(data)))
68 self.assertEqual(r, list(map(f, iter(data))))
69
69
70 def test_map_short_first(self):
70 def test_map_short_first(self):
71 def f(x,y):
71 def f(x,y):
@@ -74,11 +74,11 b' class TestLoadBalancedView(ClusterTestCase):'
74 if x is None:
74 if x is None:
75 return x
75 return x
76 return x*y
76 return x*y
77 data = range(10)
77 data = list(range(10))
78 data2 = range(4)
78 data2 = list(range(4))
79
79
80 r = self.view.map_sync(f, data, data2)
80 r = self.view.map_sync(f, data, data2)
81 self.assertEqual(r, map(f, data, data2))
81 self.assertEqual(r, list(map(f, data, data2)))
82
82
83 def test_map_short_last(self):
83 def test_map_short_last(self):
84 def f(x,y):
84 def f(x,y):
@@ -87,11 +87,11 b' class TestLoadBalancedView(ClusterTestCase):'
87 if x is None:
87 if x is None:
88 return x
88 return x
89 return x*y
89 return x*y
90 data = range(4)
90 data = list(range(4))
91 data2 = range(10)
91 data2 = list(range(10))
92
92
93 r = self.view.map_sync(f, data, data2)
93 r = self.view.map_sync(f, data, data2)
94 self.assertEqual(r, map(f, data, data2))
94 self.assertEqual(r, list(map(f, data, data2)))
95
95
96 def test_map_unordered(self):
96 def test_map_unordered(self):
97 def f(x):
97 def f(x):
@@ -100,8 +100,8 b' class TestLoadBalancedView(ClusterTestCase):'
100 import time
100 import time
101 time.sleep(0.05*x)
101 time.sleep(0.05*x)
102 return x**2
102 return x**2
103 data = range(16,0,-1)
103 data = list(range(16,0,-1))
104 reference = map(f, data)
104 reference = list(map(f, data))
105
105
106 amr = self.view.map_async(slow_f, data, ordered=False)
106 amr = self.view.map_async(slow_f, data, ordered=False)
107 self.assertTrue(isinstance(amr, pmod.AsyncMapResult))
107 self.assertTrue(isinstance(amr, pmod.AsyncMapResult))
@@ -119,8 +119,8 b' class TestLoadBalancedView(ClusterTestCase):'
119 import time
119 import time
120 time.sleep(0.05*x)
120 time.sleep(0.05*x)
121 return x**2
121 return x**2
122 data = range(16,0,-1)
122 data = list(range(16,0,-1))
123 reference = map(f, data)
123 reference = list(map(f, data))
124
124
125 amr = self.view.map_async(slow_f, data)
125 amr = self.view.map_async(slow_f, data)
126 self.assertTrue(isinstance(amr, pmod.AsyncMapResult))
126 self.assertTrue(isinstance(amr, pmod.AsyncMapResult))
@@ -28,6 +28,7 b' from nose.plugins.attrib import attr'
28
28
29 from IPython.testing import decorators as dec
29 from IPython.testing import decorators as dec
30 from IPython.utils.io import capture_output
30 from IPython.utils.io import capture_output
31 from IPython.utils.py3compat import unicode_type
31
32
32 from IPython import parallel as pmod
33 from IPython import parallel as pmod
33 from IPython.parallel import error
34 from IPython.parallel import error
@@ -68,7 +69,7 b' class TestView(ClusterTestCase):'
68
69
69 def test_push_pull(self):
70 def test_push_pull(self):
70 """test pushing and pulling"""
71 """test pushing and pulling"""
71 data = dict(a=10, b=1.05, c=range(10), d={'e':(1,2),'f':'hi'})
72 data = dict(a=10, b=1.05, c=list(range(10)), d={'e':(1,2),'f':'hi'})
72 t = self.client.ids[-1]
73 t = self.client.ids[-1]
73 v = self.client[t]
74 v = self.client[t]
74 push = v.push
75 push = v.push
@@ -229,7 +230,7 b' class TestView(ClusterTestCase):'
229
230
230 def test_scatter_gather(self):
231 def test_scatter_gather(self):
231 view = self.client[:]
232 view = self.client[:]
232 seq1 = range(16)
233 seq1 = list(range(16))
233 view.scatter('a', seq1)
234 view.scatter('a', seq1)
234 seq2 = view.gather('a', block=True)
235 seq2 = view.gather('a', block=True)
235 self.assertEqual(seq2, seq1)
236 self.assertEqual(seq2, seq1)
@@ -248,7 +249,7 b' class TestView(ClusterTestCase):'
248 def test_scatter_gather_lazy(self):
249 def test_scatter_gather_lazy(self):
249 """scatter/gather with targets='all'"""
250 """scatter/gather with targets='all'"""
250 view = self.client.direct_view(targets='all')
251 view = self.client.direct_view(targets='all')
251 x = range(64)
252 x = list(range(64))
252 view.scatter('x', x)
253 view.scatter('x', x)
253 gathered = view.gather('x', block=True)
254 gathered = view.gather('x', block=True)
254 self.assertEqual(gathered, x)
255 self.assertEqual(gathered, x)
@@ -314,7 +315,7 b' class TestView(ClusterTestCase):'
314 """push/pull pandas.TimeSeries"""
315 """push/pull pandas.TimeSeries"""
315 import pandas
316 import pandas
316
317
317 ts = pandas.TimeSeries(range(10))
318 ts = pandas.TimeSeries(list(range(10)))
318
319
319 view = self.client[-1]
320 view = self.client[-1]
320
321
@@ -328,9 +329,9 b' class TestView(ClusterTestCase):'
328 view = self.client[:]
329 view = self.client[:]
329 def f(x):
330 def f(x):
330 return x**2
331 return x**2
331 data = range(16)
332 data = list(range(16))
332 r = view.map_sync(f, data)
333 r = view.map_sync(f, data)
333 self.assertEqual(r, map(f, data))
334 self.assertEqual(r, list(map(f, data)))
334
335
335 def test_map_iterable(self):
336 def test_map_iterable(self):
336 """test map on iterables (direct)"""
337 """test map on iterables (direct)"""
@@ -355,7 +356,7 b' class TestView(ClusterTestCase):'
355 assert_array_equal(r, arr)
356 assert_array_equal(r, arr)
356
357
357 def test_scatter_gather_nonblocking(self):
358 def test_scatter_gather_nonblocking(self):
358 data = range(16)
359 data = list(range(16))
359 view = self.client[:]
360 view = self.client[:]
360 view.scatter('a', data, block=False)
361 view.scatter('a', data, block=False)
361 ar = view.gather('a', block=False)
362 ar = view.gather('a', block=False)
@@ -450,7 +451,7 b' class TestView(ClusterTestCase):'
450
451
451 @interactive
452 @interactive
452 def check_unicode(a, check):
453 def check_unicode(a, check):
453 assert isinstance(a, unicode), "%r is not unicode"%a
454 assert not isinstance(a, bytes), "%r is bytes, not unicode"%a
454 assert isinstance(check, bytes), "%r is not bytes"%check
455 assert isinstance(check, bytes), "%r is not bytes"%check
455 assert a.encode('utf8') == check, "%s != %s"%(a,check)
456 assert a.encode('utf8') == check, "%s != %s"%(a,check)
456
457
@@ -487,7 +488,7 b' class TestView(ClusterTestCase):'
487
488
488 def test_eval_reference(self):
489 def test_eval_reference(self):
489 v = self.client[self.client.ids[0]]
490 v = self.client[self.client.ids[0]]
490 v['g'] = range(5)
491 v['g'] = list(range(5))
491 rg = pmod.Reference('g[0]')
492 rg = pmod.Reference('g[0]')
492 echo = lambda x:x
493 echo = lambda x:x
493 self.assertEqual(v.apply_sync(echo, rg), 0)
494 self.assertEqual(v.apply_sync(echo, rg), 0)
@@ -500,7 +501,7 b' class TestView(ClusterTestCase):'
500
501
501 def test_single_engine_map(self):
502 def test_single_engine_map(self):
502 e0 = self.client[self.client.ids[0]]
503 e0 = self.client[self.client.ids[0]]
503 r = range(5)
504 r = list(range(5))
504 check = [ -1*i for i in r ]
505 check = [ -1*i for i in r ]
505 result = e0.map_sync(lambda x: -1*x, r)
506 result = e0.map_sync(lambda x: -1*x, r)
506 self.assertEqual(result, check)
507 self.assertEqual(result, check)
@@ -590,7 +591,7 b' class TestView(ClusterTestCase):'
590 view.execute("from IPython.core.display import *")
591 view.execute("from IPython.core.display import *")
591 ar = view.execute("[ display(i) for i in range(5) ]", block=True)
592 ar = view.execute("[ display(i) for i in range(5) ]", block=True)
592
593
593 expected = [ {u'text/plain' : unicode(j)} for j in range(5) ]
594 expected = [ {u'text/plain' : unicode_type(j)} for j in range(5) ]
594 for outputs in ar.outputs:
595 for outputs in ar.outputs:
595 mimes = [ out['data'] for out in outputs ]
596 mimes = [ out['data'] for out in outputs ]
596 self.assertEqual(mimes, expected)
597 self.assertEqual(mimes, expected)
@@ -606,7 +607,7 b' class TestView(ClusterTestCase):'
606
607
607 ar = view.apply_async(publish)
608 ar = view.apply_async(publish)
608 ar.get(5)
609 ar.get(5)
609 expected = [ {u'text/plain' : unicode(j)} for j in range(5) ]
610 expected = [ {u'text/plain' : unicode_type(j)} for j in range(5) ]
610 for outputs in ar.outputs:
611 for outputs in ar.outputs:
611 mimes = [ out['data'] for out in outputs ]
612 mimes = [ out['data'] for out in outputs ]
612 self.assertEqual(mimes, expected)
613 self.assertEqual(mimes, expected)
@@ -44,6 +44,7 b' from IPython.external.decorator import decorator'
44 # IPython imports
44 # IPython imports
45 from IPython.config.application import Application
45 from IPython.config.application import Application
46 from IPython.utils.localinterfaces import localhost, is_public_ip, public_ips
46 from IPython.utils.localinterfaces import localhost, is_public_ip, public_ips
47 from IPython.utils.py3compat import string_types, iteritems, itervalues
47 from IPython.kernel.zmq.log import EnginePUBHandler
48 from IPython.kernel.zmq.log import EnginePUBHandler
48 from IPython.kernel.zmq.serialize import (
49 from IPython.kernel.zmq.serialize import (
49 unserialize_object, serialize_object, pack_apply_message, unpack_apply_message
50 unserialize_object, serialize_object, pack_apply_message, unpack_apply_message
@@ -58,7 +59,7 b' class Namespace(dict):'
58
59
59 def __getattr__(self, key):
60 def __getattr__(self, key):
60 """getattr aliased to getitem"""
61 """getattr aliased to getitem"""
61 if key in self.iterkeys():
62 if key in self:
62 return self[key]
63 return self[key]
63 else:
64 else:
64 raise NameError(key)
65 raise NameError(key)
@@ -76,7 +77,7 b' class ReverseDict(dict):'
76 def __init__(self, *args, **kwargs):
77 def __init__(self, *args, **kwargs):
77 dict.__init__(self, *args, **kwargs)
78 dict.__init__(self, *args, **kwargs)
78 self._reverse = dict()
79 self._reverse = dict()
79 for key, value in self.iteritems():
80 for key, value in iteritems(self):
80 self._reverse[value] = key
81 self._reverse[value] = key
81
82
82 def __getitem__(self, key):
83 def __getitem__(self, key):
@@ -130,7 +131,7 b' def is_url(url):'
130
131
131 def validate_url(url):
132 def validate_url(url):
132 """validate a url for zeromq"""
133 """validate a url for zeromq"""
133 if not isinstance(url, basestring):
134 if not isinstance(url, string_types):
134 raise TypeError("url must be a string, not %r"%type(url))
135 raise TypeError("url must be a string, not %r"%type(url))
135 url = url.lower()
136 url = url.lower()
136
137
@@ -163,11 +164,11 b' def validate_url(url):'
163
164
164 def validate_url_container(container):
165 def validate_url_container(container):
165 """validate a potentially nested collection of urls."""
166 """validate a potentially nested collection of urls."""
166 if isinstance(container, basestring):
167 if isinstance(container, string_types):
167 url = container
168 url = container
168 return validate_url(url)
169 return validate_url(url)
169 elif isinstance(container, dict):
170 elif isinstance(container, dict):
170 container = container.itervalues()
171 container = itervalues(container)
171
172
172 for element in container:
173 for element in container:
173 validate_url_container(element)
174 validate_url_container(element)
@@ -230,9 +231,9 b' def _push(**ns):'
230 while tmp in user_ns:
231 while tmp in user_ns:
231 tmp = tmp + '_'
232 tmp = tmp + '_'
232 try:
233 try:
233 for name, value in ns.iteritems():
234 for name, value in ns.items():
234 user_ns[tmp] = value
235 user_ns[tmp] = value
235 exec "%s = %s" % (name, tmp) in user_ns
236 exec("%s = %s" % (name, tmp), user_ns)
236 finally:
237 finally:
237 user_ns.pop(tmp, None)
238 user_ns.pop(tmp, None)
238
239
@@ -240,14 +241,14 b' def _push(**ns):'
240 def _pull(keys):
241 def _pull(keys):
241 """helper method for implementing `client.pull` via `client.apply`"""
242 """helper method for implementing `client.pull` via `client.apply`"""
242 if isinstance(keys, (list,tuple, set)):
243 if isinstance(keys, (list,tuple, set)):
243 return map(lambda key: eval(key, globals()), keys)
244 return [eval(key, globals()) for key in keys]
244 else:
245 else:
245 return eval(keys, globals())
246 return eval(keys, globals())
246
247
247 @interactive
248 @interactive
248 def _execute(code):
249 def _execute(code):
249 """helper method for implementing `client.execute` via `client.apply`"""
250 """helper method for implementing `client.execute` via `client.apply`"""
250 exec code in globals()
251 exec(code, globals())
251
252
252 #--------------------------------------------------------------------------
253 #--------------------------------------------------------------------------
253 # extra process management utilities
254 # extra process management utilities
@@ -258,7 +259,7 b' _random_ports = set()'
258 def select_random_ports(n):
259 def select_random_ports(n):
259 """Selects and return n random ports that are available."""
260 """Selects and return n random ports that are available."""
260 ports = []
261 ports = []
261 for i in xrange(n):
262 for i in range(n):
262 sock = socket.socket()
263 sock = socket.socket()
263 sock.bind(('', 0))
264 sock.bind(('', 0))
264 while sock.getsockname()[1] in _random_ports:
265 while sock.getsockname()[1] in _random_ports:
@@ -11,6 +11,9 b' import re'
11 # System library imports
11 # System library imports
12 from IPython.external.qt import QtGui
12 from IPython.external.qt import QtGui
13
13
14 # Local imports
15 from IPython.utils.py3compat import string_types
16
14 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
15 # Constants and datatypes
18 # Constants and datatypes
16 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
@@ -103,7 +106,7 b' class AnsiCodeProcessor(object):'
103 self.actions = []
106 self.actions = []
104 start = match.end()
107 start = match.end()
105
108
106 groups = filter(lambda x: x is not None, match.groups())
109 groups = [g for g in match.groups() if (g is not None)]
107 g0 = groups[0]
110 g0 = groups[0]
108 if g0 == '\a':
111 if g0 == '\a':
109 self.actions.append(BeepAction('beep'))
112 self.actions.append(BeepAction('beep'))
@@ -126,7 +129,7 b' class AnsiCodeProcessor(object):'
126 if g0.startswith('['):
129 if g0.startswith('['):
127 # Case 1: CSI code.
130 # Case 1: CSI code.
128 try:
131 try:
129 params = map(int, params)
132 params = list(map(int, params))
130 except ValueError:
133 except ValueError:
131 # Silently discard badly formed codes.
134 # Silently discard badly formed codes.
132 pass
135 pass
@@ -318,7 +321,7 b' class QtAnsiCodeProcessor(AnsiCodeProcessor):'
318 color += 8
321 color += 8
319
322
320 constructor = self.color_map.get(color, None)
323 constructor = self.color_map.get(color, None)
321 if isinstance(constructor, basestring):
324 if isinstance(constructor, string_types):
322 # If this is an X11 color name, we just hope there is a close SVG
325 # If this is an X11 color name, we just hope there is a close SVG
323 # color name. We could use QColor's static method
326 # color name. We could use QColor's static method
324 # 'setAllowX11ColorNames()', but this is global and only available
327 # 'setAllowX11ColorNames()', but this is global and only available
@@ -365,7 +368,7 b' class QtAnsiCodeProcessor(AnsiCodeProcessor):'
365 if color.value() >= 127:
368 if color.value() >= 127:
366 # Colors appropriate for a terminal with a light background. For
369 # Colors appropriate for a terminal with a light background. For
367 # now, only use non-bright colors...
370 # now, only use non-bright colors...
368 for i in xrange(8):
371 for i in range(8):
369 self.default_color_map[i + 8] = self.default_color_map[i]
372 self.default_color_map[i + 8] = self.default_color_map[i]
370
373
371 # ...and replace white with black.
374 # ...and replace white with black.
@@ -23,11 +23,11 b' from IPython.qt.rich_text import HtmlExporter'
23 from IPython.qt.util import MetaQObjectHasTraits, get_font
23 from IPython.qt.util import MetaQObjectHasTraits, get_font
24 from IPython.utils.text import columnize
24 from IPython.utils.text import columnize
25 from IPython.utils.traitlets import Bool, Enum, Integer, Unicode
25 from IPython.utils.traitlets import Bool, Enum, Integer, Unicode
26 from ansi_code_processor import QtAnsiCodeProcessor
26 from .ansi_code_processor import QtAnsiCodeProcessor
27 from completion_widget import CompletionWidget
27 from .completion_widget import CompletionWidget
28 from completion_html import CompletionHtml
28 from .completion_html import CompletionHtml
29 from completion_plain import CompletionPlain
29 from .completion_plain import CompletionPlain
30 from kill_ring import QtKillRing
30 from .kill_ring import QtKillRing
31
31
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
@@ -69,7 +69,7 b' def is_letter_or_number(char):'
69 # Classes
69 # Classes
70 #-----------------------------------------------------------------------------
70 #-----------------------------------------------------------------------------
71
71
72 class ConsoleWidget(LoggingConfigurable, QtGui.QWidget):
72 class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui.QWidget), {})):
73 """ An abstract base class for console-type widgets. This class has
73 """ An abstract base class for console-type widgets. This class has
74 functionality for:
74 functionality for:
75
75
@@ -82,7 +82,6 b' class ConsoleWidget(LoggingConfigurable, QtGui.QWidget):'
82 ConsoleWidget also provides a number of utility methods that will be
82 ConsoleWidget also provides a number of utility methods that will be
83 convenient to implementors of a console-style widget.
83 convenient to implementors of a console-style widget.
84 """
84 """
85 __metaclass__ = MetaQObjectHasTraits
86
85
87 #------ Configuration ------------------------------------------------------
86 #------ Configuration ------------------------------------------------------
88
87
@@ -221,9 +220,9 b' class ConsoleWidget(LoggingConfigurable, QtGui.QWidget):'
221
220
222 # The shortcuts defined by this widget. We need to keep track of these to
221 # The shortcuts defined by this widget. We need to keep track of these to
223 # support 'override_shortcuts' above.
222 # support 'override_shortcuts' above.
224 _shortcuts = set(_ctrl_down_remap.keys() +
223 _shortcuts = set(_ctrl_down_remap.keys()) | \
225 [ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
224 { QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
226 QtCore.Qt.Key_V ])
225 QtCore.Qt.Key_V }
227
226
228 _temp_buffer_filled = False
227 _temp_buffer_filled = False
229
228
@@ -16,11 +16,11 b' from IPython.core.inputtransformer import classic_prompt'
16 from IPython.core.oinspect import call_tip
16 from IPython.core.oinspect import call_tip
17 from IPython.qt.base_frontend_mixin import BaseFrontendMixin
17 from IPython.qt.base_frontend_mixin import BaseFrontendMixin
18 from IPython.utils.traitlets import Bool, Instance, Unicode
18 from IPython.utils.traitlets import Bool, Instance, Unicode
19 from bracket_matcher import BracketMatcher
19 from .bracket_matcher import BracketMatcher
20 from call_tip_widget import CallTipWidget
20 from .call_tip_widget import CallTipWidget
21 from completion_lexer import CompletionLexer
21 from .completion_lexer import CompletionLexer
22 from history_console_widget import HistoryConsoleWidget
22 from .history_console_widget import HistoryConsoleWidget
23 from pygments_highlighter import PygmentsHighlighter
23 from .pygments_highlighter import PygmentsHighlighter
24
24
25
25
26 class FrontendHighlighter(PygmentsHighlighter):
26 class FrontendHighlighter(PygmentsHighlighter):
@@ -2,8 +2,9 b''
2 from IPython.external.qt import QtGui
2 from IPython.external.qt import QtGui
3
3
4 # Local imports
4 # Local imports
5 from IPython.utils.py3compat import unicode_type
5 from IPython.utils.traitlets import Bool
6 from IPython.utils.traitlets import Bool
6 from console_widget import ConsoleWidget
7 from .console_widget import ConsoleWidget
7
8
8
9
9 class HistoryConsoleWidget(ConsoleWidget):
10 class HistoryConsoleWidget(ConsoleWidget):
@@ -285,7 +286,7 b' class HistoryConsoleWidget(ConsoleWidget):'
285 if index in self._history_edits:
286 if index in self._history_edits:
286 return self._history_edits[index]
287 return self._history_edits[index]
287 elif index == len(self._history):
288 elif index == len(self._history):
288 return unicode()
289 return unicode_type()
289 return self._history[index]
290 return self._history[index]
290
291
291 def _set_history(self, history):
292 def _set_history(self, history):
@@ -22,8 +22,8 b' from IPython.external.qt import QtCore, QtGui'
22 from IPython.core.inputsplitter import IPythonInputSplitter
22 from IPython.core.inputsplitter import IPythonInputSplitter
23 from IPython.core.inputtransformer import ipy_prompt
23 from IPython.core.inputtransformer import ipy_prompt
24 from IPython.utils.traitlets import Bool, Unicode
24 from IPython.utils.traitlets import Bool, Unicode
25 from frontend_widget import FrontendWidget
25 from .frontend_widget import FrontendWidget
26 import styles
26 from . import styles
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Constants
29 # Constants
@@ -5,6 +5,8 b' from pygments.lexer import RegexLexer, _TokenType, Text, Error'
5 from pygments.lexers import PythonLexer
5 from pygments.lexers import PythonLexer
6 from pygments.styles import get_style_by_name
6 from pygments.styles import get_style_by_name
7
7
8 # Local imports
9 from IPython.utils.py3compat import string_types
8
10
9 def get_tokens_unprocessed(self, text, stack=('root',)):
11 def get_tokens_unprocessed(self, text, stack=('root',)):
10 """ Split ``text`` into (tokentype, text) pairs.
12 """ Split ``text`` into (tokentype, text) pairs.
@@ -73,7 +75,7 b' class PygmentsBlockUserData(QtGui.QTextBlockUserData):'
73 syntax_stack = ('root',)
75 syntax_stack = ('root',)
74
76
75 def __init__(self, **kwds):
77 def __init__(self, **kwds):
76 for key, value in kwds.iteritems():
78 for key, value in kwds.items():
77 setattr(self, key, value)
79 setattr(self, key, value)
78 QtGui.QTextBlockUserData.__init__(self)
80 QtGui.QTextBlockUserData.__init__(self)
79
81
@@ -129,7 +131,7 b' class PygmentsHighlighter(QtGui.QSyntaxHighlighter):'
129 def set_style(self, style):
131 def set_style(self, style):
130 """ Sets the style to the specified Pygments style.
132 """ Sets the style to the specified Pygments style.
131 """
133 """
132 if isinstance(style, basestring):
134 if isinstance(style, string_types):
133 style = get_style_by_name(style)
135 style = get_style_by_name(style)
134 self._style = style
136 self._style = style
135 self._clear_caches()
137 self._clear_caches()
@@ -39,7 +39,7 b" if os.name == 'nt':"
39 def gui_excepthook(exctype, value, tb):
39 def gui_excepthook(exctype, value, tb):
40 try:
40 try:
41 import ctypes, traceback
41 import ctypes, traceback
42 MB_ICONERROR = 0x00000010L
42 MB_ICONERROR = 0x00000010
43 title = u'Error starting IPython QtConsole'
43 title = u'Error starting IPython QtConsole'
44 msg = u''.join(traceback.format_exception(exctype, value, tb))
44 msg = u''.join(traceback.format_exception(exctype, value, tb))
45 ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR)
45 ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR)
@@ -17,7 +17,7 b' from IPython.external.qt import QtCore, QtGui'
17 # Local imports
17 # Local imports
18 from IPython.utils.traitlets import Bool
18 from IPython.utils.traitlets import Bool
19 from IPython.qt.svg import save_svg, svg_to_clipboard, svg_to_image
19 from IPython.qt.svg import save_svg, svg_to_clipboard, svg_to_image
20 from ipython_widget import IPythonWidget
20 from .ipython_widget import IPythonWidget
21
21
22
22
23 class RichIPythonWidget(IPythonWidget):
23 class RichIPythonWidget(IPythonWidget):
@@ -6,7 +6,7 b' from IPython.external.qt import QtCore'
6
6
7 # IPython imports.
7 # IPython imports.
8 from IPython.utils.traitlets import HasTraits, Type
8 from IPython.utils.traitlets import HasTraits, Type
9 from util import MetaQObjectHasTraits, SuperQObject
9 from .util import MetaQObjectHasTraits, SuperQObject
10
10
11
11
12 class ChannelQObject(SuperQObject):
12 class ChannelQObject(SuperQObject):
@@ -168,27 +168,22 b' class QtHBChannelMixin(ChannelQObject):'
168 self.kernel_died.emit(since_last_heartbeat)
168 self.kernel_died.emit(since_last_heartbeat)
169
169
170
170
171 class QtKernelRestarterMixin(HasTraits, SuperQObject):
171 class QtKernelRestarterMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
172
172
173 __metaclass__ = MetaQObjectHasTraits
174 _timer = None
173 _timer = None
175
174
176
175
177 class QtKernelManagerMixin(HasTraits, SuperQObject):
176 class QtKernelManagerMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
178 """ A KernelClient that provides signals and slots.
177 """ A KernelClient that provides signals and slots.
179 """
178 """
180
179
181 __metaclass__ = MetaQObjectHasTraits
182
183 kernel_restarted = QtCore.Signal()
180 kernel_restarted = QtCore.Signal()
184
181
185
182
186 class QtKernelClientMixin(HasTraits, SuperQObject):
183 class QtKernelClientMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
187 """ A KernelClient that provides signals and slots.
184 """ A KernelClient that provides signals and slots.
188 """
185 """
189
186
190 __metaclass__ = MetaQObjectHasTraits
191
192 # Emitted when the kernel client has started listening.
187 # Emitted when the kernel client has started listening.
193 started_channels = QtCore.Signal()
188 started_channels = QtCore.Signal()
194
189
@@ -4,6 +4,8 b''
4 # System library imports.
4 # System library imports.
5 from IPython.external.qt import QtCore, QtGui, QtSvg
5 from IPython.external.qt import QtCore, QtGui, QtSvg
6
6
7 # Our own imports
8 from IPython.utils.py3compat import unicode_type
7
9
8 def save_svg(string, parent=None):
10 def save_svg(string, parent=None):
9 """ Prompts the user to save an SVG document to disk.
11 """ Prompts the user to save an SVG document to disk.
@@ -21,7 +23,7 b' def save_svg(string, parent=None):'
21 The name of the file to which the document was saved, or None if the save
23 The name of the file to which the document was saved, or None if the save
22 was cancelled.
24 was cancelled.
23 """
25 """
24 if isinstance(string, unicode):
26 if isinstance(string, unicode_type):
25 string = string.encode('utf-8')
27 string = string.encode('utf-8')
26
28
27 dialog = QtGui.QFileDialog(parent, 'Save SVG Document')
29 dialog = QtGui.QFileDialog(parent, 'Save SVG Document')
@@ -30,7 +32,7 b' def save_svg(string, parent=None):'
30 dialog.setNameFilter('SVG document (*.svg)')
32 dialog.setNameFilter('SVG document (*.svg)')
31 if dialog.exec_():
33 if dialog.exec_():
32 filename = dialog.selectedFiles()[0]
34 filename = dialog.selectedFiles()[0]
33 f = open(filename, 'w')
35 f = open(filename, 'wb')
34 try:
36 try:
35 f.write(string)
37 f.write(string)
36 finally:
38 finally:
@@ -46,7 +48,7 b' def svg_to_clipboard(string):'
46 string : basestring
48 string : basestring
47 A Python string containing a SVG document.
49 A Python string containing a SVG document.
48 """
50 """
49 if isinstance(string, unicode):
51 if isinstance(string, unicode_type):
50 string = string.encode('utf-8')
52 string = string.encode('utf-8')
51
53
52 mime_data = QtCore.QMimeData()
54 mime_data = QtCore.QMimeData()
@@ -74,7 +76,7 b' def svg_to_image(string, size=None):'
74 --------
76 --------
75 A QImage of format QImage.Format_ARGB32.
77 A QImage of format QImage.Format_ARGB32.
76 """
78 """
77 if isinstance(string, unicode):
79 if isinstance(string, unicode_type):
78 string = string.encode('utf-8')
80 string = string.encode('utf-8')
79
81
80 renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
82 renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
@@ -8,6 +8,7 b' import inspect'
8 from IPython.external.qt import QtCore, QtGui
8 from IPython.external.qt import QtCore, QtGui
9
9
10 # IPython imports.
10 # IPython imports.
11 from IPython.utils.py3compat import iteritems
11 from IPython.utils.traitlets import HasTraits, TraitType
12 from IPython.utils.traitlets import HasTraits, TraitType
12
13
13 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
@@ -27,7 +28,7 b' class MetaQObjectHasTraits(MetaQObject, MetaHasTraits):'
27 def __new__(mcls, name, bases, classdict):
28 def __new__(mcls, name, bases, classdict):
28 # FIXME: this duplicates the code from MetaHasTraits.
29 # FIXME: this duplicates the code from MetaHasTraits.
29 # I don't think a super() call will help me here.
30 # I don't think a super() call will help me here.
30 for k,v in classdict.iteritems():
31 for k,v in iteritems(classdict):
31 if isinstance(v, TraitType):
32 if isinstance(v, TraitType):
32 v.name = k
33 v.name = k
33 elif inspect.isclass(v):
34 elif inspect.isclass(v):
@@ -51,13 +51,13 b' Authors'
51 - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
51 - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
52 - Skipper Seabold, refactoring, cleanups, pure python addition
52 - Skipper Seabold, refactoring, cleanups, pure python addition
53 """
53 """
54 from __future__ import print_function
54
55
55 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
56 # Imports
57 # Imports
57 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
58
59
59 # Stdlib
60 # Stdlib
60 import cStringIO
61 import os
61 import os
62 import re
62 import re
63 import sys
63 import sys
@@ -83,6 +83,12 b" matplotlib.use('Agg')"
83 from IPython import Config, InteractiveShell
83 from IPython import Config, InteractiveShell
84 from IPython.core.profiledir import ProfileDir
84 from IPython.core.profiledir import ProfileDir
85 from IPython.utils import io
85 from IPython.utils import io
86 from IPython.utils.py3compat import PY3
87
88 if PY3:
89 from io import StringIO
90 else:
91 from StringIO import StringIO
86
92
87 #-----------------------------------------------------------------------------
93 #-----------------------------------------------------------------------------
88 # Globals
94 # Globals
@@ -192,7 +198,7 b' class EmbeddedSphinxShell(object):'
192
198
193 def __init__(self):
199 def __init__(self):
194
200
195 self.cout = cStringIO.StringIO()
201 self.cout = StringIO()
196
202
197
203
198 # Create config object for IPython
204 # Create config object for IPython
@@ -649,7 +655,7 b' class IPythonDirective(Directive):'
649 #print lines
655 #print lines
650 if len(lines)>2:
656 if len(lines)>2:
651 if debug:
657 if debug:
652 print '\n'.join(lines)
658 print('\n'.join(lines))
653 else: #NOTE: this raises some errors, what's it for?
659 else: #NOTE: this raises some errors, what's it for?
654 #print 'INSERTING %d lines'%len(lines)
660 #print 'INSERTING %d lines'%len(lines)
655 self.state_machine.insert_input(
661 self.state_machine.insert_input(
@@ -826,4 +832,4 b" if __name__=='__main__':"
826 if not os.path.isdir('_static'):
832 if not os.path.isdir('_static'):
827 os.mkdir('_static')
833 os.mkdir('_static')
828 test()
834 test()
829 print 'All OK? Check figures in _static/'
835 print('All OK? Check figures in _static/')
@@ -1,6 +1,9 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 import readline
2 import readline
3 from Queue import Empty
3 try:
4 from queue import Empty # Py 3
5 except ImportError:
6 from Queue import Empty # Py 2
4
7
5 from IPython.config import Configurable
8 from IPython.config import Configurable
6 from IPython.utils.traitlets import Float
9 from IPython.utils.traitlets import Float
@@ -23,11 +23,15 b' import subprocess'
23 from io import BytesIO
23 from io import BytesIO
24 import base64
24 import base64
25
25
26 from Queue import Empty
26 try:
27 from queue import Empty # Py 3
28 except ImportError:
29 from Queue import Empty # Py 2
27
30
28 from IPython.core import page
31 from IPython.core import page
29 from IPython.utils.warn import warn, error
32 from IPython.utils.warn import warn, error
30 from IPython.utils import io
33 from IPython.utils import io
34 from IPython.utils.py3compat import string_types, input
31 from IPython.utils.traitlets import List, Enum, Any, Instance, Unicode, Float
35 from IPython.utils.traitlets import List, Enum, Any, Instance, Unicode, Float
32 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
36 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
33
37
@@ -326,7 +330,7 b' class ZMQTerminalInteractiveShell(TerminalInteractiveShell):'
326 signal.signal(signal.SIGINT, double_int)
330 signal.signal(signal.SIGINT, double_int)
327
331
328 try:
332 try:
329 raw_data = raw_input(msg_rep["content"]["prompt"])
333 raw_data = input(msg_rep["content"]["prompt"])
330 except EOFError:
334 except EOFError:
331 # turn EOFError into EOF character
335 # turn EOFError into EOF character
332 raw_data = '\x04'
336 raw_data = '\x04'
@@ -387,7 +391,7 b' class ZMQTerminalInteractiveShell(TerminalInteractiveShell):'
387 if display_banner is None:
391 if display_banner is None:
388 display_banner = self.display_banner
392 display_banner = self.display_banner
389
393
390 if isinstance(display_banner, basestring):
394 if isinstance(display_banner, string_types):
391 self.show_banner(display_banner)
395 self.show_banner(display_banner)
392 elif display_banner:
396 elif display_banner:
393 self.show_banner()
397 self.show_banner()
@@ -23,6 +23,7 b' Notes'
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 from __future__ import with_statement
25 from __future__ import with_statement
26 from __future__ import print_function
26
27
27 import sys
28 import sys
28 import warnings
29 import warnings
@@ -154,7 +155,7 b' class InteractiveShellEmbed(TerminalInteractiveShell):'
154 self.banner2 = self.old_banner2
155 self.banner2 = self.old_banner2
155
156
156 if self.exit_msg is not None:
157 if self.exit_msg is not None:
157 print self.exit_msg
158 print(self.exit_msg)
158
159
159 def mainloop(self, local_ns=None, module=None, stack_depth=0,
160 def mainloop(self, local_ns=None, module=None, stack_depth=0,
160 display_banner=None, global_ns=None, compile_flags=None):
161 display_banner=None, global_ns=None, compile_flags=None):
@@ -105,7 +105,7 b' class TerminalMagics(Magics):'
105 # Sanity checks
105 # Sanity checks
106 if b is None:
106 if b is None:
107 raise UsageError('No previous pasted block available')
107 raise UsageError('No previous pasted block available')
108 if not isinstance(b, basestring):
108 if not isinstance(b, py3compat.string_types):
109 raise UsageError(
109 raise UsageError(
110 "Variable 'pasted_block' is not a string, can't execute")
110 "Variable 'pasted_block' is not a string, can't execute")
111
111
@@ -473,7 +473,7 b' class TerminalInteractiveShell(InteractiveShell):'
473 if display_banner is None:
473 if display_banner is None:
474 display_banner = self.display_banner
474 display_banner = self.display_banner
475
475
476 if isinstance(display_banner, basestring):
476 if isinstance(display_banner, py3compat.string_types):
477 self.show_banner(display_banner)
477 self.show_banner(display_banner)
478 elif display_banner:
478 elif display_banner:
479 self.show_banner()
479 self.show_banner()
@@ -24,6 +24,7 b' Authors'
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import absolute_import
26 from __future__ import absolute_import
27 from __future__ import print_function
27
28
28 import logging
29 import logging
29 import os
30 import os
@@ -196,7 +197,7 b' class LocateIPythonApp(BaseIPythonApplication):'
196 if self.subapp is not None:
197 if self.subapp is not None:
197 return self.subapp.start()
198 return self.subapp.start()
198 else:
199 else:
199 print self.ipython_dir
200 print(self.ipython_dir)
200
201
201
202
202 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
203 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
@@ -344,7 +345,7 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
344 if self.display_banner and self.interact:
345 if self.display_banner and self.interact:
345 self.shell.show_banner()
346 self.shell.show_banner()
346 # Make sure there is a space below the banner.
347 # Make sure there is a space below the banner.
347 if self.log_level <= logging.INFO: print
348 if self.log_level <= logging.INFO: print()
348
349
349 def _pylab_changed(self, name, old, new):
350 def _pylab_changed(self, name, old, new):
350 """Replace --pylab='inline' with --pylab='auto'"""
351 """Replace --pylab='inline' with --pylab='auto'"""
@@ -21,7 +21,7 b' def test(all=False):'
21
21
22 # Do the import internally, so that this function doesn't increase total
22 # Do the import internally, so that this function doesn't increase total
23 # import time
23 # import time
24 from iptest import run_iptestall
24 from .iptest import run_iptestall
25 run_iptestall(inc_slow=all)
25 run_iptestall(inc_slow=all)
26
26
27 # So nose doesn't try to run this as a test itself and we end up with an
27 # So nose doesn't try to run this as a test itself and we end up with an
@@ -55,7 +55,7 b' import unittest'
55 from IPython.external.decorator import decorator
55 from IPython.external.decorator import decorator
56
56
57 # Expose the unittest-driven decorators
57 # Expose the unittest-driven decorators
58 from ipunittest import ipdoctest, ipdocstring
58 from .ipunittest import ipdoctest, ipdocstring
59
59
60 # Grab the numpy-specific decorators which we keep in a file that we
60 # Grab the numpy-specific decorators which we keep in a file that we
61 # occasionally update from upstream: decorators.py is a copy of
61 # occasionally update from upstream: decorators.py is a copy of
@@ -64,6 +64,7 b' from IPython.external.decorators import *'
64
64
65 # For onlyif_cmd_exists decorator
65 # For onlyif_cmd_exists decorator
66 from IPython.utils.process import is_cmd_found
66 from IPython.utils.process import is_cmd_found
67 from IPython.utils.py3compat import string_types
67
68
68 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
69 # Classes and functions
70 # Classes and functions
@@ -141,7 +142,7 b' def make_label_dec(label,ds=None):'
141 True
142 True
142 """
143 """
143
144
144 if isinstance(label,basestring):
145 if isinstance(label, string_types):
145 labels = [label]
146 labels = [label]
146 else:
147 else:
147 labels = label
148 labels = label
@@ -20,7 +20,6 b' from __future__ import print_function'
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 # stdlib
22 # stdlib
23 import __builtin__ as builtin_mod
24 import os
23 import os
25 import sys
24 import sys
26
25
@@ -30,6 +29,7 b' from . import tools'
30 from IPython.core import page
29 from IPython.core import page
31 from IPython.utils import io
30 from IPython.utils import io
32 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 from IPython.utils.py3compat import builtin_mod
33 from IPython.terminal.interactiveshell import TerminalInteractiveShell
33 from IPython.terminal.interactiveshell import TerminalInteractiveShell
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
@@ -382,9 +382,21 b' class StreamCapturer(Thread):'
382 continue
382 continue
383
383
384 ready = select(streams, [], [], 0.5)[0]
384 ready = select(streams, [], [], 0.5)[0]
385 dead = []
385 with self.buffer_lock:
386 with self.buffer_lock:
386 for fd in ready:
387 for fd in ready:
387 self.buffer.write(os.read(fd, 1024))
388 try:
389 self.buffer.write(os.read(fd, 1024))
390 except OSError as e:
391 import errno
392 if e.errno == errno.EBADF:
393 dead.append(fd)
394 else:
395 raise
396
397 with self.streams_lock:
398 for fd in dead:
399 self.streams.remove(fd)
388
400
389 def add_stream(self, fd):
401 def add_stream(self, fd):
390 with self.streams_lock:
402 with self.streams_lock:
@@ -224,7 +224,8 b' def prepare_controllers(options):'
224 testgroups = options.testgroups
224 testgroups = options.testgroups
225
225
226 if testgroups:
226 if testgroups:
227 py_testgroups = [g for g in testgroups if g in py_test_group_names]
227 py_testgroups = [g for g in testgroups if (g in py_test_group_names) \
228 or g.startswith('IPython')]
228 js_testgroups = [g for g in testgroups if g in js_test_group_names]
229 js_testgroups = [g for g in testgroups if g in js_test_group_names]
229 else:
230 else:
230 py_testgroups = py_test_group_names
231 py_testgroups = py_test_group_names
@@ -236,7 +237,7 b' def prepare_controllers(options):'
236 c_py = [PyTestController(name) for name in py_testgroups]
237 c_py = [PyTestController(name) for name in py_testgroups]
237
238
238 configure_py_controllers(c_py, xunit=options.xunit,
239 configure_py_controllers(c_py, xunit=options.xunit,
239 coverage=options.coverage)
240 coverage=options.coverage, extra_args=options.extra_args)
240
241
241 controllers = c_py + c_js
242 controllers = c_py + c_js
242 to_run = [c for c in controllers if c.will_run]
243 to_run = [c for c in controllers if c.will_run]
@@ -3,7 +3,7 b''
3 This file just contains doctests both using plain python and IPython prompts.
3 This file just contains doctests both using plain python and IPython prompts.
4 All tests should be loaded by nose.
4 All tests should be loaded by nose.
5 """
5 """
6 from IPython.utils.py3compat import doctest_refactor_print
6 from __future__ import print_function
7
7
8 def pyfunc():
8 def pyfunc():
9 """Some pure python tests...
9 """Some pure python tests...
@@ -17,14 +17,13 b' def pyfunc():'
17 5
17 5
18
18
19 >>> for i in range(3):
19 >>> for i in range(3):
20 ... print i,
20 ... print(i, end=' ')
21 ... print i+1,
21 ... print(i+1, end=' ')
22 ...
22 ...
23 0 1 1 2 2 3
23 0 1 1 2 2 3
24 """
24 """
25 return 'pyfunc'
25 return 'pyfunc'
26
26
27 @doctest_refactor_print
28 def ipfunc():
27 def ipfunc():
29 """Some ipython tests...
28 """Some ipython tests...
30
29
@@ -34,10 +33,10 b' def ipfunc():'
34 Out[3]: 5
33 Out[3]: 5
35
34
36 In [26]: for i in range(3):
35 In [26]: for i in range(3):
37 ....: print i,
36 ....: print(i, end=' ')
38 ....: print i+1,
37 ....: print(i+1, end=' ')
39 ....:
38 ....:
40 0 1 1 2 2 3
39 0 1 1 2 2 3
41
40
42
41
43 Examples that access the operating system work:
42 Examples that access the operating system work:
@@ -59,7 +58,7 b' def ipfunc():'
59 In [7]: 'hi'
58 In [7]: 'hi'
60 Out[7]: 'hi'
59 Out[7]: 'hi'
61
60
62 In [8]: print repr(_)
61 In [8]: print(repr(_))
63 'hi'
62 'hi'
64
63
65 In [7]: 3+4
64 In [7]: 3+4
@@ -128,14 +127,13 b' def random_all():'
128 """
127 """
129 pass
128 pass
130
129
131 @doctest_refactor_print
132 def iprand():
130 def iprand():
133 """Some ipython tests with random output.
131 """Some ipython tests with random output.
134
132
135 In [7]: 3+4
133 In [7]: 3+4
136 Out[7]: 7
134 Out[7]: 7
137
135
138 In [8]: print 'hello'
136 In [8]: print('hello')
139 world # random
137 world # random
140
138
141 In [9]: iprand()
139 In [9]: iprand()
@@ -143,7 +141,6 b' def iprand():'
143 """
141 """
144 return 'iprand'
142 return 'iprand'
145
143
146 @doctest_refactor_print
147 def iprand_all():
144 def iprand_all():
148 """Some ipython tests with fully random output.
145 """Some ipython tests with fully random output.
149
146
@@ -152,13 +149,10 b' def iprand_all():'
152 In [7]: 1
149 In [7]: 1
153 Out[7]: 99
150 Out[7]: 99
154
151
155 In [8]: print 'hello'
152 In [8]: print('hello')
156 world
153 world
157
154
158 In [9]: iprand_all()
155 In [9]: iprand_all()
159 Out[9]: 'junk'
156 Out[9]: 'junk'
160 """
157 """
161 return 'iprand_all'
158 return 'iprand_all'
162
163
164
@@ -19,8 +19,6 b' Limitations:'
19 # Module imports
19 # Module imports
20
20
21 # From the standard library
21 # From the standard library
22 import __builtin__ as builtin_mod
23 import commands
24 import doctest
22 import doctest
25 import inspect
23 import inspect
26 import logging
24 import logging
@@ -31,7 +29,6 b' import traceback'
31 import unittest
29 import unittest
32
30
33 from inspect import getmodule
31 from inspect import getmodule
34 from StringIO import StringIO
35
32
36 # We are overriding the default doctest runner, so we need to import a few
33 # We are overriding the default doctest runner, so we need to import a few
37 # things from doctest directly
34 # things from doctest directly
@@ -48,6 +45,12 b' from nose.plugins import doctests, Plugin'
48 from nose.util import anyp, getpackage, test_address, resolve_name, tolist
45 from nose.util import anyp, getpackage, test_address, resolve_name, tolist
49
46
50 # Our own imports
47 # Our own imports
48 from IPython.utils.py3compat import builtin_mod, PY3
49
50 if PY3:
51 from io import StringIO
52 else:
53 from StringIO import StringIO
51
54
52 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
53 # Module globals and other constants
56 # Module globals and other constants
@@ -96,7 +99,7 b' class DocTestFinder(doctest.DocTestFinder):'
96 if module is None:
99 if module is None:
97 return True
100 return True
98 elif inspect.isfunction(object):
101 elif inspect.isfunction(object):
99 return module.__dict__ is object.func_globals
102 return module.__dict__ is object.__globals__
100 elif inspect.isbuiltin(object):
103 elif inspect.isbuiltin(object):
101 return module.__name__ == object.__module__
104 return module.__name__ == object.__module__
102 elif inspect.isclass(object):
105 elif inspect.isclass(object):
@@ -106,7 +109,7 b' class DocTestFinder(doctest.DocTestFinder):'
106 # __module__ attribute of methods, but since the same error is easy
109 # __module__ attribute of methods, but since the same error is easy
107 # to make by extension code writers, having this safety in place
110 # to make by extension code writers, having this safety in place
108 # isn't such a bad idea
111 # isn't such a bad idea
109 return module.__name__ == object.im_class.__module__
112 return module.__name__ == object.__self__.__class__.__module__
110 elif inspect.getmodule(object) is not None:
113 elif inspect.getmodule(object) is not None:
111 return module is inspect.getmodule(object)
114 return module is inspect.getmodule(object)
112 elif hasattr(object, '__module__'):
115 elif hasattr(object, '__module__'):
@@ -114,7 +117,7 b' class DocTestFinder(doctest.DocTestFinder):'
114 elif isinstance(object, property):
117 elif isinstance(object, property):
115 return True # [XX] no way not be sure.
118 return True # [XX] no way not be sure.
116 else:
119 else:
117 raise ValueError("object must be a class or function")
120 raise ValueError("object must be a class or function, got %r" % object)
118
121
119 def _find(self, tests, obj, name, module, source_lines, globs, seen):
122 def _find(self, tests, obj, name, module, source_lines, globs, seen):
120 """
123 """
@@ -154,7 +157,7 b' class DocTestFinder(doctest.DocTestFinder):'
154 if isinstance(val, staticmethod):
157 if isinstance(val, staticmethod):
155 val = getattr(obj, valname)
158 val = getattr(obj, valname)
156 if isinstance(val, classmethod):
159 if isinstance(val, classmethod):
157 val = getattr(obj, valname).im_func
160 val = getattr(obj, valname).__func__
158
161
159 # Recurse to methods, properties, and nested classes.
162 # Recurse to methods, properties, and nested classes.
160 if ((inspect.isfunction(val) or inspect.isclass(val) or
163 if ((inspect.isfunction(val) or inspect.isclass(val) or
@@ -296,7 +299,7 b' class DocTestCase(doctests.DocTestCase):'
296 # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
299 # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
297 # it does look like one to me: its tearDown method tries to run
300 # it does look like one to me: its tearDown method tries to run
298 #
301 #
299 # delattr(__builtin__, self._result_var)
302 # delattr(builtin_mod, self._result_var)
300 #
303 #
301 # without checking that the attribute really is there; it implicitly
304 # without checking that the attribute really is there; it implicitly
302 # assumes it should have been set via displayhook. But if the
305 # assumes it should have been set via displayhook. But if the
@@ -1,17 +1,18 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Nose-based test runner.
2 """Nose-based test runner.
3 """
3 """
4 from __future__ import print_function
4
5
5 from nose.core import main
6 from nose.core import main
6 from nose.plugins.builtin import plugins
7 from nose.plugins.builtin import plugins
7 from nose.plugins.doctests import Doctest
8 from nose.plugins.doctests import Doctest
8
9
9 import ipdoctest
10 from . import ipdoctest
10 from ipdoctest import IPDocTestRunner
11 from .ipdoctest import IPDocTestRunner
11
12
12 if __name__ == '__main__':
13 if __name__ == '__main__':
13 print 'WARNING: this code is incomplete!'
14 print('WARNING: this code is incomplete!')
14 print
15 print()
15
16
16 pp = [x() for x in plugins] # activate all builtin plugins first
17 pp = [x() for x in plugins] # activate all builtin plugins first
17 main(testRunner=IPDocTestRunner(),
18 main(testRunner=IPDocTestRunner(),
@@ -2,6 +2,7 b''
2
2
3 This is used by a companion test case.
3 This is used by a companion test case.
4 """
4 """
5 from __future__ import print_function
5
6
6 import gc
7 import gc
7
8
@@ -14,6 +15,6 b" if __name__ == '__main__':"
14 c = C()
15 c = C()
15
16
16 c_refs = gc.get_referrers(c)
17 c_refs = gc.get_referrers(c)
17 ref_ids = map(id,c_refs)
18 ref_ids = list(map(id,c_refs))
18
19
19 print 'c referrers:',map(type,c_refs)
20 print('c referrers:',list(map(type,c_refs)))
@@ -3,6 +3,7 b''
3 This file just contains doctests both using plain python and IPython prompts.
3 This file just contains doctests both using plain python and IPython prompts.
4 All tests should be loaded by nose.
4 All tests should be loaded by nose.
5 """
5 """
6 from __future__ import print_function
6
7
7 def pyfunc():
8 def pyfunc():
8 """Some pure python tests...
9 """Some pure python tests...
@@ -16,10 +17,10 b' def pyfunc():'
16 5
17 5
17
18
18 >>> for i in range(3):
19 >>> for i in range(3):
19 ... print i,
20 ... print(i, end=' ')
20 ... print i+1,
21 ... print(i+1, end=' ')
21 ...
22 ...
22 0 1 1 2 2 3
23 0 1 1 2 2 3
23 """
24 """
24 return 'pyfunc'
25 return 'pyfunc'
25
26
@@ -1,2 +1,3 b''
1 from __future__ import print_function
1 x = 1
2 x = 1
2 print 'x is:',x
3 print('x is:',x)
@@ -1,5 +1,6 b''
1 """Tests for the decorators we've created for IPython.
1 """Tests for the decorators we've created for IPython.
2 """
2 """
3 from __future__ import print_function
3
4
4 # Module imports
5 # Module imports
5 # Std lib
6 # Std lib
@@ -32,11 +33,11 b' def getargspec(obj):'
32 if inspect.isfunction(obj):
33 if inspect.isfunction(obj):
33 func_obj = obj
34 func_obj = obj
34 elif inspect.ismethod(obj):
35 elif inspect.ismethod(obj):
35 func_obj = obj.im_func
36 func_obj = obj.__func__
36 else:
37 else:
37 raise TypeError('arg is not a Python function')
38 raise TypeError('arg is not a Python function')
38 args, varargs, varkw = inspect.getargs(func_obj.func_code)
39 args, varargs, varkw = inspect.getargs(func_obj.__code__)
39 return args, varargs, varkw, func_obj.func_defaults
40 return args, varargs, varkw, func_obj.__defaults__
40
41
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42 # Testing functions
43 # Testing functions
@@ -67,9 +68,9 b' def doctest_bad(x,y=1,**k):'
67 >>> 1+1
68 >>> 1+1
68 3
69 3
69 """
70 """
70 print 'x:',x
71 print('x:',x)
71 print 'y:',y
72 print('y:',y)
72 print 'k:',k
73 print('k:',k)
73
74
74
75
75 def call_doctest_bad():
76 def call_doctest_bad():
@@ -117,7 +118,7 b' class FooClass(object):'
117 >>> f = FooClass(3)
118 >>> f = FooClass(3)
118 junk
119 junk
119 """
120 """
120 print 'Making a FooClass.'
121 print('Making a FooClass.')
121 self.x = x
122 self.x = x
122
123
123 @skip_doctest
124 @skip_doctest
@@ -14,6 +14,7 b' Tests for testing.tools'
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import with_statement
16 from __future__ import with_statement
17 from __future__ import print_function
17
18
18 import os
19 import os
19 import unittest
20 import unittest
@@ -73,16 +74,16 b' def test_temp_pyfile():'
73 class TestAssertPrints(unittest.TestCase):
74 class TestAssertPrints(unittest.TestCase):
74 def test_passing(self):
75 def test_passing(self):
75 with tt.AssertPrints("abc"):
76 with tt.AssertPrints("abc"):
76 print "abcd"
77 print("abcd")
77 print "def"
78 print("def")
78 print b"ghi"
79 print(b"ghi")
79
80
80 def test_failing(self):
81 def test_failing(self):
81 def func():
82 def func():
82 with tt.AssertPrints("abc"):
83 with tt.AssertPrints("abc"):
83 print "acd"
84 print("acd")
84 print "def"
85 print("def")
85 print b"ghi"
86 print(b"ghi")
86
87
87 self.assertRaises(AssertionError, func)
88 self.assertRaises(AssertionError, func)
88
89
@@ -337,8 +337,8 b' class AssertPrints(object):'
337 Examples
337 Examples
338 --------
338 --------
339 >>> with AssertPrints("abc", suppress=False):
339 >>> with AssertPrints("abc", suppress=False):
340 ... print "abcd"
340 ... print("abcd")
341 ... print "def"
341 ... print("def")
342 ...
342 ...
343 abcd
343 abcd
344 def
344 def
@@ -29,7 +29,7 b' scan Python source code and re-emit it with no changes to its original'
29 formatting (which is the hard part).
29 formatting (which is the hard part).
30 """
30 """
31 from __future__ import print_function
31 from __future__ import print_function
32
32 from __future__ import absolute_import
33 from __future__ import unicode_literals
33 from __future__ import unicode_literals
34
34
35 __all__ = ['ANSICodeColors','Parser']
35 __all__ = ['ANSICodeColors','Parser']
@@ -38,7 +38,6 b" _scheme_default = 'Linux'"
38
38
39
39
40 # Imports
40 # Imports
41 import StringIO
42 import keyword
41 import keyword
43 import os
42 import os
44 import sys
43 import sys
@@ -53,6 +52,12 b' except AttributeError:'
53 generate_tokens = tokenize._tokenize
52 generate_tokens = tokenize._tokenize
54
53
55 from IPython.utils.coloransi import *
54 from IPython.utils.coloransi import *
55 from IPython.utils.py3compat import PY3
56
57 if PY3:
58 from io import StringIO
59 else:
60 from StringIO import StringIO
56
61
57 #############################################################################
62 #############################################################################
58 ### Python Source Parser (does Hilighting)
63 ### Python Source Parser (does Hilighting)
@@ -143,13 +148,13 b' class Parser:'
143
148
144 string_output = 0
149 string_output = 0
145 if out == 'str' or self.out == 'str' or \
150 if out == 'str' or self.out == 'str' or \
146 isinstance(self.out,StringIO.StringIO):
151 isinstance(self.out,StringIO):
147 # XXX - I don't really like this state handling logic, but at this
152 # XXX - I don't really like this state handling logic, but at this
148 # point I don't want to make major changes, so adding the
153 # point I don't want to make major changes, so adding the
149 # isinstance() check is the simplest I can do to ensure correct
154 # isinstance() check is the simplest I can do to ensure correct
150 # behavior.
155 # behavior.
151 out_old = self.out
156 out_old = self.out
152 self.out = StringIO.StringIO()
157 self.out = StringIO()
153 string_output = 1
158 string_output = 1
154 elif out is not None:
159 elif out is not None:
155 self.out = out
160 self.out = out
@@ -183,7 +188,7 b' class Parser:'
183
188
184 # parse the source and write it
189 # parse the source and write it
185 self.pos = 0
190 self.pos = 0
186 text = StringIO.StringIO(self.raw)
191 text = StringIO(self.raw)
187
192
188 error = False
193 error = False
189 try:
194 try:
@@ -16,6 +16,9 b' from __future__ import print_function'
16 import os, sys, threading
16 import os, sys, threading
17 import ctypes, msvcrt
17 import ctypes, msvcrt
18
18
19 # local imports
20 from .py3compat import unicode_type
21
19 # Win32 API types needed for the API calls
22 # Win32 API types needed for the API calls
20 from ctypes import POINTER
23 from ctypes import POINTER
21 from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
24 from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
@@ -31,6 +31,7 b' Older entry points'
31 are the same, except instead of generating tokens, tokeneater is a callback
31 are the same, except instead of generating tokens, tokeneater is a callback
32 function to which the 5 fields described above are passed as 5 arguments,
32 function to which the 5 fields described above are passed as 5 arguments,
33 each time a new token is found."""
33 each time a new token is found."""
34 from __future__ import print_function
34
35
35 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
36 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
36 __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
37 __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
@@ -161,8 +162,8 b' class StopTokenizing(Exception): pass'
161 def printtoken(type, token, srow_scol, erow_ecol, line): # for testing
162 def printtoken(type, token, srow_scol, erow_ecol, line): # for testing
162 srow, scol = srow_scol
163 srow, scol = srow_scol
163 erow, ecol = erow_ecol
164 erow, ecol = erow_ecol
164 print "%d,%d-%d,%d:\t%s\t%s" % \
165 print("%d,%d-%d,%d:\t%s\t%s" % \
165 (srow, scol, erow, ecol, tok_name[type], repr(token))
166 (srow, scol, erow, ecol, tok_name[type], repr(token)))
166
167
167 def tokenize(readline, tokeneater=printtoken):
168 def tokenize(readline, tokeneater=printtoken):
168 """
169 """
@@ -307,7 +308,7 b' def generate_tokens(readline):'
307
308
308 if contstr: # continued string
309 if contstr: # continued string
309 if not line:
310 if not line:
310 raise TokenError, ("EOF in multi-line string", strstart)
311 raise TokenError("EOF in multi-line string", strstart)
311 endmatch = endprog.match(line)
312 endmatch = endprog.match(line)
312 if endmatch:
313 if endmatch:
313 pos = end = endmatch.end(0)
314 pos = end = endmatch.end(0)
@@ -368,7 +369,7 b' def generate_tokens(readline):'
368
369
369 else: # continued statement
370 else: # continued statement
370 if not line:
371 if not line:
371 raise TokenError, ("EOF in multi-line statement", (lnum, 0))
372 raise TokenError("EOF in multi-line statement", (lnum, 0))
372 continued = 0
373 continued = 0
373
374
374 while pos < max:
375 while pos < max:
@@ -46,7 +46,7 b' class EvalDict:'
46
46
47 >>> text = "python"
47 >>> text = "python"
48
48
49 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
49 >>> print("%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict())
50 Python 2.1 rules!
50 Python 2.1 rules!
51 """
51 """
52
52
@@ -9,14 +9,20 b' IO capturing utilities.'
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 from __future__ import print_function
12 from __future__ import print_function, absolute_import
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import sys
18 import sys
19 from StringIO import StringIO
19
20 from IPython.utils.py3compat import PY3
21
22 if PY3:
23 from io import StringIO
24 else:
25 from StringIO import StringIO
20
26
21 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
22 # Classes and functions
28 # Classes and functions
@@ -24,7 +24,11 b' __docformat__ = "restructuredtext en"'
24 #-------------------------------------------------------------------------------
24 #-------------------------------------------------------------------------------
25
25
26 import sys
26 import sys
27 import types, copy_reg
27 import types
28 try:
29 import copyreg # Py 3
30 except ImportError:
31 import copy_reg as copyreg # Py 2
28
32
29 def code_ctor(*args):
33 def code_ctor(*args):
30 return types.CodeType(*args)
34 return types.CodeType(*args)
@@ -40,4 +44,4 b' def reduce_code(co):'
40 args.insert(1, co.co_kwonlyargcount)
44 args.insert(1, co.co_kwonlyargcount)
41 return code_ctor, tuple(args)
45 return code_ctor, tuple(args)
42
46
43 copy_reg.pickle(types.CodeType, reduce_code) No newline at end of file
47 copyreg.pickle(types.CodeType, reduce_code) No newline at end of file
@@ -166,7 +166,7 b' class ColorSchemeTable(dict):'
166 Names are by default compared in a case-insensitive way, but this can
166 Names are by default compared in a case-insensitive way, but this can
167 be changed by setting the parameter case_sensitive to true."""
167 be changed by setting the parameter case_sensitive to true."""
168
168
169 scheme_names = self.keys()
169 scheme_names = list(self.keys())
170 if case_sensitive:
170 if case_sensitive:
171 valid_schemes = scheme_names
171 valid_schemes = scheme_names
172 scheme_test = scheme
172 scheme_test = scheme
@@ -9,6 +9,8 b''
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 from .py3compat import xrange
13
12 def uniq_stable(elems):
14 def uniq_stable(elems):
13 """uniq_stable(elems) -> list
15 """uniq_stable(elems) -> list
14
16
@@ -12,6 +12,8 b''
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 from .py3compat import string_types
16
15 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
16 # Code
18 # Code
17 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
@@ -79,5 +81,5 b' def dir2(obj):'
79 # filter out non-string attributes which may be stuffed by dir() calls
81 # filter out non-string attributes which may be stuffed by dir() calls
80 # and poor coding in third-party modules
82 # and poor coding in third-party modules
81
83
82 words = [w for w in words if isinstance(w, basestring)]
84 words = [w for w in words if isinstance(w, string_types)]
83 return sorted(words)
85 return sorted(words)
@@ -2,6 +2,7 b''
2 """
2 """
3 Utilities for working with stack frames.
3 Utilities for working with stack frames.
4 """
4 """
5 from __future__ import print_function
5
6
6 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
8 # Copyright (C) 2008-2011 The IPython Development Team
@@ -39,7 +40,7 b' def extract_vars(*names,**kw):'
39
40
40 In [2]: def func(x):
41 In [2]: def func(x):
41 ...: y = 1
42 ...: y = 1
42 ...: print sorted(extract_vars('x','y').items())
43 ...: print(sorted(extract_vars('x','y').items()))
43 ...:
44 ...:
44
45
45 In [3]: func('hello')
46 In [3]: func('hello')
@@ -78,8 +79,8 b" def debugx(expr,pre_msg=''):"
78 expr->value pair."""
79 expr->value pair."""
79
80
80 cf = sys._getframe(1)
81 cf = sys._getframe(1)
81 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
82 print('[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
82 eval(expr,cf.f_globals,cf.f_locals))
83 eval(expr,cf.f_globals,cf.f_locals)))
83
84
84
85
85 # deactivate it by uncommenting the following line, which makes it a no-op
86 # deactivate it by uncommenting the following line, which makes it a no-op
@@ -17,8 +17,8 b' from __future__ import print_function'
17 import os
17 import os
18 import sys
18 import sys
19 import tempfile
19 import tempfile
20 from StringIO import StringIO
21 from .capture import CapturedIO, capture_output
20 from .capture import CapturedIO, capture_output
21 from .py3compat import string_types, input
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Code
24 # Code
@@ -57,7 +57,7 b' class IOStream:'
57 file=sys.stderr)
57 file=sys.stderr)
58
58
59 def writelines(self, lines):
59 def writelines(self, lines):
60 if isinstance(lines, basestring):
60 if isinstance(lines, string_types):
61 lines = [lines]
61 lines = [lines]
62 for line in lines:
62 for line in lines:
63 self.write(line)
63 self.write(line)
@@ -170,7 +170,7 b' def ask_yes_no(prompt,default=None):'
170 ans = None
170 ans = None
171 while ans not in answers.keys():
171 while ans not in answers.keys():
172 try:
172 try:
173 ans = raw_input(prompt+' ').lower()
173 ans = input(prompt+' ').lower()
174 if not ans: # response was an empty string
174 if not ans: # response was an empty string
175 ans = default
175 ans = default
176 except KeyboardInterrupt:
176 except KeyboardInterrupt:
@@ -78,7 +78,7 b' class Struct(dict):'
78 >>> try:
78 >>> try:
79 ... s['b'] = 20
79 ... s['b'] = 20
80 ... except KeyError:
80 ... except KeyError:
81 ... print 'this is not allowed'
81 ... print('this is not allowed')
82 ...
82 ...
83 this is not allowed
83 this is not allowed
84 """
84 """
@@ -103,7 +103,7 b' class Struct(dict):'
103 >>> try:
103 >>> try:
104 ... s.get = 10
104 ... s.get = 10
105 ... except AttributeError:
105 ... except AttributeError:
106 ... print "you can't set a class member"
106 ... print("you can't set a class member")
107 ...
107 ...
108 you can't set a class member
108 you can't set a class member
109 """
109 """
@@ -139,7 +139,7 b' class Struct(dict):'
139 >>> try:
139 >>> try:
140 ... s.b
140 ... s.b
141 ... except AttributeError:
141 ... except AttributeError:
142 ... print "I don't have that key"
142 ... print("I don't have that key")
143 ...
143 ...
144 I don't have that key
144 I don't have that key
145 """
145 """
@@ -24,6 +24,7 b' except ImportError:'
24 from base64 import encodestring as encodebytes
24 from base64 import encodestring as encodebytes
25
25
26 from IPython.utils import py3compat
26 from IPython.utils import py3compat
27 from IPython.utils.py3compat import string_types, unicode_type, iteritems
27 from IPython.utils.encoding import DEFAULT_ENCODING
28 from IPython.utils.encoding import DEFAULT_ENCODING
28 next_attr_name = '__next__' if py3compat.PY3 else 'next'
29 next_attr_name = '__next__' if py3compat.PY3 else 'next'
29
30
@@ -42,8 +43,8 b' ISO8601_PAT=re.compile(r"^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d+)Z?([\\+\\-]\\d{'
42 def rekey(dikt):
43 def rekey(dikt):
43 """Rekey a dict that has been forced to use str keys where there should be
44 """Rekey a dict that has been forced to use str keys where there should be
44 ints by json."""
45 ints by json."""
45 for k in dikt.iterkeys():
46 for k in dikt:
46 if isinstance(k, basestring):
47 if isinstance(k, string_types):
47 ik=fk=None
48 ik=fk=None
48 try:
49 try:
49 ik = int(k)
50 ik = int(k)
@@ -66,11 +67,11 b' def extract_dates(obj):'
66 """extract ISO8601 dates from unpacked JSON"""
67 """extract ISO8601 dates from unpacked JSON"""
67 if isinstance(obj, dict):
68 if isinstance(obj, dict):
68 obj = dict(obj) # don't clobber
69 obj = dict(obj) # don't clobber
69 for k,v in obj.iteritems():
70 for k,v in iteritems(obj):
70 obj[k] = extract_dates(v)
71 obj[k] = extract_dates(v)
71 elif isinstance(obj, (list, tuple)):
72 elif isinstance(obj, (list, tuple)):
72 obj = [ extract_dates(o) for o in obj ]
73 obj = [ extract_dates(o) for o in obj ]
73 elif isinstance(obj, basestring):
74 elif isinstance(obj, string_types):
74 m = ISO8601_PAT.match(obj)
75 m = ISO8601_PAT.match(obj)
75 if m:
76 if m:
76 # FIXME: add actual timezone support
77 # FIXME: add actual timezone support
@@ -83,7 +84,7 b' def squash_dates(obj):'
83 """squash datetime objects into ISO8601 strings"""
84 """squash datetime objects into ISO8601 strings"""
84 if isinstance(obj, dict):
85 if isinstance(obj, dict):
85 obj = dict(obj) # don't clobber
86 obj = dict(obj) # don't clobber
86 for k,v in obj.iteritems():
87 for k,v in iteritems(obj):
87 obj[k] = squash_dates(v)
88 obj[k] = squash_dates(v)
88 elif isinstance(obj, (list, tuple)):
89 elif isinstance(obj, (list, tuple)):
89 obj = [ squash_dates(o) for o in obj ]
90 obj = [ squash_dates(o) for o in obj ]
@@ -172,7 +173,7 b' def json_clean(obj):'
172 --------
173 --------
173 >>> json_clean(4)
174 >>> json_clean(4)
174 4
175 4
175 >>> json_clean(range(10))
176 >>> json_clean(list(range(10)))
176 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
177 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
177 >>> sorted(json_clean(dict(x=1, y=2)).items())
178 >>> sorted(json_clean(dict(x=1, y=2)).items())
178 [('x', 1), ('y', 2)]
179 [('x', 1), ('y', 2)]
@@ -183,7 +184,7 b' def json_clean(obj):'
183 """
184 """
184 # types that are 'atomic' and ok in json as-is. bool doesn't need to be
185 # types that are 'atomic' and ok in json as-is. bool doesn't need to be
185 # listed explicitly because bools pass as int instances
186 # listed explicitly because bools pass as int instances
186 atomic_ok = (unicode, int, types.NoneType)
187 atomic_ok = (unicode_type, int, type(None))
187
188
188 # containers that we need to convert into lists
189 # containers that we need to convert into lists
189 container_to_list = (tuple, set, types.GeneratorType)
190 container_to_list = (tuple, set, types.GeneratorType)
@@ -218,7 +219,7 b' def json_clean(obj):'
218 'key collision would lead to dropped values')
219 'key collision would lead to dropped values')
219 # If all OK, proceed by making the new dict that will be json-safe
220 # If all OK, proceed by making the new dict that will be json-safe
220 out = {}
221 out = {}
221 for k,v in obj.iteritems():
222 for k,v in iteritems(obj):
222 out[str(k)] = json_clean(v)
223 out[str(k)] = json_clean(v)
223 return out
224 return out
224
225
@@ -11,8 +11,10 b' from io import TextIOWrapper, BytesIO'
11 import os.path
11 import os.path
12 import re
12 import re
13
13
14 cookie_re = re.compile(ur"coding[:=]\s*([-\w.]+)", re.UNICODE)
14 from .py3compat import unicode_type
15 cookie_comment_re = re.compile(ur"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
15
16 cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)", re.UNICODE)
17 cookie_comment_re = re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
16
18
17 try:
19 try:
18 # Available in Python 3
20 # Available in Python 3
@@ -128,7 +130,7 b" def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True):"
128 txt can be either a bytes buffer or a string containing the source
130 txt can be either a bytes buffer or a string containing the source
129 code.
131 code.
130 """
132 """
131 if isinstance(txt, unicode):
133 if isinstance(txt, unicode_type):
132 return txt
134 return txt
133 if isinstance(txt, bytes):
135 if isinstance(txt, bytes):
134 buffer = BytesIO(txt)
136 buffer = BytesIO(txt)
@@ -162,7 +162,7 b' def filefind(filename, path_dirs=None):'
162
162
163 if path_dirs is None:
163 if path_dirs is None:
164 path_dirs = ("",)
164 path_dirs = ("",)
165 elif isinstance(path_dirs, basestring):
165 elif isinstance(path_dirs, py3compat.string_types):
166 path_dirs = (path_dirs,)
166 path_dirs = (path_dirs,)
167
167
168 for path in path_dirs:
168 for path in path_dirs:
@@ -206,7 +206,10 b' def get_home_dir(require_writable=False):'
206 if not _writable_dir(homedir) and os.name == 'nt':
206 if not _writable_dir(homedir) and os.name == 'nt':
207 # expanduser failed, use the registry to get the 'My Documents' folder.
207 # expanduser failed, use the registry to get the 'My Documents' folder.
208 try:
208 try:
209 import _winreg as wreg
209 try:
210 import winreg as wreg # Py 3
211 except ImportError:
212 import _winreg as wreg # Py 2
210 key = wreg.OpenKey(
213 key = wreg.OpenKey(
211 wreg.HKEY_CURRENT_USER,
214 wreg.HKEY_CURRENT_USER,
212 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
215 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
@@ -32,11 +32,15 b' Author: Ville Vainio <vivainio@gmail.com>'
32 License: MIT open source license.
32 License: MIT open source license.
33
33
34 """
34 """
35 from __future__ import print_function
35
36
36 from IPython.external.path import path as Path
37 from IPython.external.path import path as Path
37 import os,stat,time
38 import os,stat,time
38 import collections
39 import collections
39 import cPickle as pickle
40 try:
41 import cPickle as pickle
42 except ImportError:
43 import pickle
40 import glob
44 import glob
41
45
42 def gethashfile(key):
46 def gethashfile(key):
@@ -138,7 +142,7 b' class PickleShareDB(collections.MutableMapping):'
138 try:
142 try:
139 all.update(self[f])
143 all.update(self[f])
140 except KeyError:
144 except KeyError:
141 print "Corrupt",f,"deleted - hset is not threadsafe!"
145 print("Corrupt",f,"deleted - hset is not threadsafe!")
142 del self[f]
146 del self[f]
143
147
144 self.uncache(f)
148 self.uncache(f)
@@ -280,25 +284,25 b' class PickleShareLink:'
280 def test():
284 def test():
281 db = PickleShareDB('~/testpickleshare')
285 db = PickleShareDB('~/testpickleshare')
282 db.clear()
286 db.clear()
283 print "Should be empty:",db.items()
287 print("Should be empty:",db.items())
284 db['hello'] = 15
288 db['hello'] = 15
285 db['aku ankka'] = [1,2,313]
289 db['aku ankka'] = [1,2,313]
286 db['paths/nest/ok/keyname'] = [1,(5,46)]
290 db['paths/nest/ok/keyname'] = [1,(5,46)]
287 db.hset('hash', 'aku', 12)
291 db.hset('hash', 'aku', 12)
288 db.hset('hash', 'ankka', 313)
292 db.hset('hash', 'ankka', 313)
289 print "12 =",db.hget('hash','aku')
293 print("12 =",db.hget('hash','aku'))
290 print "313 =",db.hget('hash','ankka')
294 print("313 =",db.hget('hash','ankka'))
291 print "all hashed",db.hdict('hash')
295 print("all hashed",db.hdict('hash'))
292 print db.keys()
296 print(db.keys())
293 print db.keys('paths/nest/ok/k*')
297 print(db.keys('paths/nest/ok/k*'))
294 print dict(db) # snapsot of whole db
298 print(dict(db)) # snapsot of whole db
295 db.uncache() # frees memory, causes re-reads later
299 db.uncache() # frees memory, causes re-reads later
296
300
297 # shorthand for accessing deeply nested files
301 # shorthand for accessing deeply nested files
298 lnk = db.getlink('myobjects/test')
302 lnk = db.getlink('myobjects/test')
299 lnk.foo = 2
303 lnk.foo = 2
300 lnk.bar = lnk.foo + 5
304 lnk.bar = lnk.foo + 5
301 print lnk.bar # 7
305 print(lnk.bar) # 7
302
306
303 def stress():
307 def stress():
304 db = PickleShareDB('~/fsdbtest')
308 db = PickleShareDB('~/fsdbtest')
@@ -316,7 +320,7 b' def stress():'
316 db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())]
320 db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())]
317 db.hset('hash',j, db.hget('hash',j,15) + 1 )
321 db.hset('hash',j, db.hget('hash',j,15) + 1 )
318
322
319 print i,
323 print(i, end=' ')
320 sys.stdout.flush()
324 sys.stdout.flush()
321 if i % 10 == 0:
325 if i % 10 == 0:
322 db.uncache()
326 db.uncache()
@@ -335,7 +339,7 b' def main():'
335 DB = PickleShareDB
339 DB = PickleShareDB
336 import sys
340 import sys
337 if len(sys.argv) < 2:
341 if len(sys.argv) < 2:
338 print usage
342 print(usage)
339 return
343 return
340
344
341 cmd = sys.argv[1]
345 cmd = sys.argv[1]
@@ -355,7 +359,7 b' def main():'
355 elif cmd == 'testwait':
359 elif cmd == 'testwait':
356 db = DB(args[0])
360 db = DB(args[0])
357 db.clear()
361 db.clear()
358 print db.waitget('250')
362 print(db.waitget('250'))
359 elif cmd == 'test':
363 elif cmd == 'test':
360 test()
364 test()
361 stress()
365 stress()
@@ -25,9 +25,10 b' try:'
25 except ImportError:
25 except ImportError:
26 import pickle
26 import pickle
27
27
28 import codeutil # This registers a hook when it's imported
28 from . import codeutil # This registers a hook when it's imported
29 import py3compat
29 from . import py3compat
30 from importstring import import_item
30 from .importstring import import_item
31 from .py3compat import string_types, iteritems
31
32
32 from IPython.config import Application
33 from IPython.config import Application
33
34
@@ -85,7 +86,7 b' class CannedObject(object):'
85 class Reference(CannedObject):
86 class Reference(CannedObject):
86 """object for wrapping a remote reference by name."""
87 """object for wrapping a remote reference by name."""
87 def __init__(self, name):
88 def __init__(self, name):
88 if not isinstance(name, basestring):
89 if not isinstance(name, string_types):
89 raise TypeError("illegal name: %r"%name)
90 raise TypeError("illegal name: %r"%name)
90 self.name = name
91 self.name = name
91 self.buffers = []
92 self.buffers = []
@@ -104,9 +105,9 b' class CannedFunction(CannedObject):'
104
105
105 def __init__(self, f):
106 def __init__(self, f):
106 self._check_type(f)
107 self._check_type(f)
107 self.code = f.func_code
108 self.code = f.__code__
108 if f.func_defaults:
109 if f.__defaults__:
109 self.defaults = [ can(fd) for fd in f.func_defaults ]
110 self.defaults = [ can(fd) for fd in f.__defaults__ ]
110 else:
111 else:
111 self.defaults = None
112 self.defaults = None
112 self.module = f.__module__ or '__main__'
113 self.module = f.__module__ or '__main__'
@@ -215,8 +216,8 b' def _import_mapping(mapping, original=None):'
215 """
216 """
216 log = _logger()
217 log = _logger()
217 log.debug("Importing canning map")
218 log.debug("Importing canning map")
218 for key,value in mapping.items():
219 for key,value in list(mapping.items()):
219 if isinstance(key, basestring):
220 if isinstance(key, string_types):
220 try:
221 try:
221 cls = import_item(key)
222 cls = import_item(key)
222 except Exception:
223 except Exception:
@@ -245,8 +246,8 b' def can(obj):'
245
246
246 import_needed = False
247 import_needed = False
247
248
248 for cls,canner in can_map.iteritems():
249 for cls,canner in iteritems(can_map):
249 if isinstance(cls, basestring):
250 if isinstance(cls, string_types):
250 import_needed = True
251 import_needed = True
251 break
252 break
252 elif istype(obj, cls):
253 elif istype(obj, cls):
@@ -270,7 +271,7 b' def can_dict(obj):'
270 """can the *values* of a dict"""
271 """can the *values* of a dict"""
271 if istype(obj, dict):
272 if istype(obj, dict):
272 newobj = {}
273 newobj = {}
273 for k, v in obj.iteritems():
274 for k, v in iteritems(obj):
274 newobj[k] = can(v)
275 newobj[k] = can(v)
275 return newobj
276 return newobj
276 else:
277 else:
@@ -290,8 +291,8 b' def uncan(obj, g=None):'
290 """invert canning"""
291 """invert canning"""
291
292
292 import_needed = False
293 import_needed = False
293 for cls,uncanner in uncan_map.iteritems():
294 for cls,uncanner in iteritems(uncan_map):
294 if isinstance(cls, basestring):
295 if isinstance(cls, string_types):
295 import_needed = True
296 import_needed = True
296 break
297 break
297 elif isinstance(obj, cls):
298 elif isinstance(obj, cls):
@@ -308,7 +309,7 b' def uncan(obj, g=None):'
308 def uncan_dict(obj, g=None):
309 def uncan_dict(obj, g=None):
309 if istype(obj, dict):
310 if istype(obj, dict):
310 newobj = {}
311 newobj = {}
311 for k, v in obj.iteritems():
312 for k, v in iteritems(obj):
312 newobj[k] = uncan(v,g)
313 newobj[k] = uncan(v,g)
313 return newobj
314 return newobj
314 else:
315 else:
@@ -1,6 +1,5 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 import __builtin__
4 import functools
3 import functools
5 import sys
4 import sys
6 import re
5 import re
@@ -35,7 +34,7 b' def cast_bytes(s, encoding=None):'
35 def _modify_str_or_docstring(str_change_func):
34 def _modify_str_or_docstring(str_change_func):
36 @functools.wraps(str_change_func)
35 @functools.wraps(str_change_func)
37 def wrapper(func_or_str):
36 def wrapper(func_or_str):
38 if isinstance(func_or_str, basestring):
37 if isinstance(func_or_str, string_types):
39 func = None
38 func = None
40 doc = func_or_str
39 doc = func_or_str
41 else:
40 else:
@@ -55,7 +54,7 b' def safe_unicode(e):'
55 safe to call unicode() on.
54 safe to call unicode() on.
56 """
55 """
57 try:
56 try:
58 return unicode(e)
57 return unicode_type(e)
59 except UnicodeError:
58 except UnicodeError:
60 pass
59 pass
61
60
@@ -76,6 +75,7 b' if sys.version_info[0] >= 3:'
76
75
77 input = input
76 input = input
78 builtin_mod_name = "builtins"
77 builtin_mod_name = "builtins"
78 import builtins as builtin_mod
79
79
80 str_to_unicode = no_code
80 str_to_unicode = no_code
81 unicode_to_str = no_code
81 unicode_to_str = no_code
@@ -92,13 +92,16 b' if sys.version_info[0] >= 3:'
92 return s.isidentifier()
92 return s.isidentifier()
93
93
94 open = orig_open
94 open = orig_open
95 xrange = range
96 def iteritems(d): return iter(d.items())
97 def itervalues(d): return iter(d.values())
95
98
96 MethodType = types.MethodType
99 MethodType = types.MethodType
97
100
98 def execfile(fname, glob, loc=None):
101 def execfile(fname, glob, loc=None):
99 loc = loc if (loc is not None) else glob
102 loc = loc if (loc is not None) else glob
100 with open(fname, 'rb') as f:
103 with open(fname, 'rb') as f:
101 exec compile(f.read(), fname, 'exec') in glob, loc
104 exec(compile(f.read(), fname, 'exec'), glob, loc)
102
105
103 # Refactor print statements in doctests.
106 # Refactor print statements in doctests.
104 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
107 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
@@ -127,6 +130,7 b' else:'
127
130
128 input = raw_input
131 input = raw_input
129 builtin_mod_name = "__builtin__"
132 builtin_mod_name = "__builtin__"
133 import __builtin__ as builtin_mod
130
134
131 str_to_unicode = decode
135 str_to_unicode = decode
132 unicode_to_str = encode
136 unicode_to_str = encode
@@ -165,6 +169,10 b' else:'
165 def __exit__(self, etype, value, traceback):
169 def __exit__(self, etype, value, traceback):
166 self.f.close()
170 self.f.close()
167
171
172 xrange = xrange
173 def iteritems(d): return d.iteritems()
174 def itervalues(d): return d.itervalues()
175
168 def MethodType(func, instance):
176 def MethodType(func, instance):
169 return types.MethodType(func, instance, type(instance))
177 return types.MethodType(func, instance, type(instance))
170
178
@@ -189,18 +197,43 b' else:'
189 # The rstrip() is necessary b/c trailing whitespace in files will
197 # The rstrip() is necessary b/c trailing whitespace in files will
190 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
198 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
191 # but we still support 2.6). See issue 1027.
199 # but we still support 2.6). See issue 1027.
192 scripttext = __builtin__.open(fname).read().rstrip() + '\n'
200 scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
193 # compile converts unicode filename to str assuming
201 # compile converts unicode filename to str assuming
194 # ascii. Let's do the conversion before calling compile
202 # ascii. Let's do the conversion before calling compile
195 if isinstance(fname, unicode):
203 if isinstance(fname, unicode):
196 filename = unicode_to_str(fname)
204 filename = unicode_to_str(fname)
197 else:
205 else:
198 filename = fname
206 filename = fname
199 exec compile(scripttext, filename, 'exec') in glob, loc
207 exec(compile(scripttext, filename, 'exec'), glob, loc)
200 else:
208 else:
201 def execfile(fname, *where):
209 def execfile(fname, *where):
202 if isinstance(fname, unicode):
210 if isinstance(fname, unicode):
203 filename = fname.encode(sys.getfilesystemencoding())
211 filename = fname.encode(sys.getfilesystemencoding())
204 else:
212 else:
205 filename = fname
213 filename = fname
206 __builtin__.execfile(filename, *where)
214 builtin_mod.execfile(filename, *where)
215
216 # Parts below taken from six:
217 # Copyright (c) 2010-2013 Benjamin Peterson
218 #
219 # Permission is hereby granted, free of charge, to any person obtaining a copy
220 # of this software and associated documentation files (the "Software"), to deal
221 # in the Software without restriction, including without limitation the rights
222 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
223 # copies of the Software, and to permit persons to whom the Software is
224 # furnished to do so, subject to the following conditions:
225 #
226 # The above copyright notice and this permission notice shall be included in all
227 # copies or substantial portions of the Software.
228 #
229 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
230 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
231 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
232 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
233 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
234 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
235 # SOFTWARE.
236
237 def with_metaclass(meta, *bases):
238 """Create a base class with a metaclass."""
239 return meta("NewBase", bases, {})
@@ -17,7 +17,7 b' class StrDispatch(object):'
17 >>> dis.add_s('hei',34, priority = 4)
17 >>> dis.add_s('hei',34, priority = 4)
18 >>> dis.add_s('hei',123, priority = 2)
18 >>> dis.add_s('hei',123, priority = 2)
19 >>> dis.add_re('h.i', 686)
19 >>> dis.add_re('h.i', 686)
20 >>> print list(dis.flat_matches('hei'))
20 >>> print(list(dis.flat_matches('hei')))
21 [123, 34, 686]
21 [123, 34, 686]
22 """
22 """
23
23
@@ -15,14 +15,18 b' from __future__ import print_function'
15
15
16 import sys
16 import sys
17
17
18 from StringIO import StringIO
19 from subprocess import Popen, PIPE
18 from subprocess import Popen, PIPE
20 import unittest
19 import unittest
21
20
22 import nose.tools as nt
21 import nose.tools as nt
23
22
24 from IPython.utils.io import Tee, capture_output
23 from IPython.utils.io import Tee, capture_output
25 from IPython.utils.py3compat import doctest_refactor_print
24 from IPython.utils.py3compat import doctest_refactor_print, PY3
25
26 if PY3:
27 from io import StringIO
28 else:
29 from StringIO import StringIO
26
30
27 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
28 # Tests
32 # Tests
@@ -21,7 +21,7 b' import nose.tools as nt'
21 # our own
21 # our own
22 from IPython.utils import jsonutil, tz
22 from IPython.utils import jsonutil, tz
23 from ..jsonutil import json_clean, encode_images
23 from ..jsonutil import json_clean, encode_images
24 from ..py3compat import unicode_to_str, str_to_bytes
24 from ..py3compat import unicode_to_str, str_to_bytes, iteritems
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Test functions
27 # Test functions
@@ -71,7 +71,7 b' def test_encode_images():'
71 'image/jpeg' : jpegdata,
71 'image/jpeg' : jpegdata,
72 }
72 }
73 encoded = encode_images(fmt)
73 encoded = encode_images(fmt)
74 for key, value in fmt.iteritems():
74 for key, value in iteritems(fmt):
75 # encoded has unicode, want bytes
75 # encoded has unicode, want bytes
76 decoded = decodestring(encoded[key].encode('ascii'))
76 decoded = decodestring(encoded[key].encode('ascii'))
77 nt.assert_equal(decoded, value)
77 nt.assert_equal(decoded, value)
@@ -79,11 +79,11 b' def test_encode_images():'
79 nt.assert_equal(encoded, encoded2)
79 nt.assert_equal(encoded, encoded2)
80
80
81 b64_str = {}
81 b64_str = {}
82 for key, encoded in encoded.iteritems():
82 for key, encoded in iteritems(encoded):
83 b64_str[key] = unicode_to_str(encoded)
83 b64_str[key] = unicode_to_str(encoded)
84 encoded3 = encode_images(b64_str)
84 encoded3 = encode_images(b64_str)
85 nt.assert_equal(encoded3, b64_str)
85 nt.assert_equal(encoded3, b64_str)
86 for key, value in fmt.iteritems():
86 for key, value in iteritems(fmt):
87 # encoded3 has str, want bytes
87 # encoded3 has str, want bytes
88 decoded = decodestring(str_to_bytes(encoded3[key]))
88 decoded = decodestring(str_to_bytes(encoded3[key]))
89 nt.assert_equal(decoded, value)
89 nt.assert_equal(decoded, value)
@@ -37,15 +37,21 b' from IPython.utils.tempdir import TemporaryDirectory'
37
37
38 # Platform-dependent imports
38 # Platform-dependent imports
39 try:
39 try:
40 import _winreg as wreg
40 import winreg as wreg # Py 3
41 except ImportError:
41 except ImportError:
42 #Fake _winreg module on none windows platforms
42 try:
43 import types
43 import _winreg as wreg # Py 2
44 wr_name = "winreg" if py3compat.PY3 else "_winreg"
44 except ImportError:
45 sys.modules[wr_name] = types.ModuleType(wr_name)
45 #Fake _winreg module on none windows platforms
46 import _winreg as wreg
46 import types
47 #Add entries that needs to be stubbed by the testing code
47 wr_name = "winreg" if py3compat.PY3 else "_winreg"
48 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
48 sys.modules[wr_name] = types.ModuleType(wr_name)
49 try:
50 import winreg as wreg
51 except ImportError:
52 import _winreg as wreg
53 #Add entries that needs to be stubbed by the testing code
54 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
49
55
50 try:
56 try:
51 reload
57 reload
@@ -110,7 +116,7 b' def teardown_environment():'
110 os.chdir(old_wd)
116 os.chdir(old_wd)
111 reload(path)
117 reload(path)
112
118
113 for key in env.keys():
119 for key in list(env):
114 if key not in oldenv:
120 if key not in oldenv:
115 del env[key]
121 del env[key]
116 env.update(oldenv)
122 env.update(oldenv)
@@ -499,8 +505,8 b' class TestShellGlob(object):'
499
505
500 @classmethod
506 @classmethod
501 def setUpClass(cls):
507 def setUpClass(cls):
502 cls.filenames_start_with_a = map('a{0}'.format, range(3))
508 cls.filenames_start_with_a = ['a0', 'a1', 'a2']
503 cls.filenames_end_with_b = map('{0}b'.format, range(3))
509 cls.filenames_end_with_b = ['0b', '1b', '2b']
504 cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b
510 cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b
505 cls.tempdir = TemporaryDirectory()
511 cls.tempdir = TemporaryDirectory()
506 td = cls.tempdir.name
512 td = cls.tempdir.name
@@ -1,5 +1,6 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.utils.text"""
2 """Tests for IPython.utils.text"""
3 from __future__ import print_function
3
4
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (C) 2011 The IPython Development Team
6 # Copyright (C) 2011 The IPython Development Team
@@ -45,11 +46,11 b' def test_columnize_random():'
45 longer_line = max([len(x) for x in out.split('\n')])
46 longer_line = max([len(x) for x in out.split('\n')])
46 longer_element = max(rand_len)
47 longer_element = max(rand_len)
47 if longer_line > displaywidth:
48 if longer_line > displaywidth:
48 print "Columnize displayed something lager than displaywidth : %s " % longer_line
49 print("Columnize displayed something lager than displaywidth : %s " % longer_line)
49 print "longer element : %s " % longer_element
50 print("longer element : %s " % longer_element)
50 print "displaywidth : %s " % displaywidth
51 print("displaywidth : %s " % displaywidth)
51 print "number of element : %s " % nitems
52 print("number of element : %s " % nitems)
52 print "size of each element :\n %s" % rand_len
53 print("size of each element :\n %s" % rand_len)
53 assert False
54 assert False
54
55
55 def test_columnize_medium():
56 def test_columnize_medium():
@@ -148,16 +148,16 b' class TestTraitType(TestCase):'
148
148
149 a = A()
149 a = A()
150 self.assertEqual(a._trait_values, {})
150 self.assertEqual(a._trait_values, {})
151 self.assertEqual(a._trait_dyn_inits.keys(), ['x'])
151 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
152 self.assertEqual(a.x, 11)
152 self.assertEqual(a.x, 11)
153 self.assertEqual(a._trait_values, {'x': 11})
153 self.assertEqual(a._trait_values, {'x': 11})
154 b = B()
154 b = B()
155 self.assertEqual(b._trait_values, {'x': 20})
155 self.assertEqual(b._trait_values, {'x': 20})
156 self.assertEqual(a._trait_dyn_inits.keys(), ['x'])
156 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
157 self.assertEqual(b.x, 20)
157 self.assertEqual(b.x, 20)
158 c = C()
158 c = C()
159 self.assertEqual(c._trait_values, {})
159 self.assertEqual(c._trait_values, {})
160 self.assertEqual(a._trait_dyn_inits.keys(), ['x'])
160 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
161 self.assertEqual(c.x, 21)
161 self.assertEqual(c.x, 21)
162 self.assertEqual(c._trait_values, {'x': 21})
162 self.assertEqual(c._trait_values, {'x': 21})
163 # Ensure that the base class remains unmolested when the _default
163 # Ensure that the base class remains unmolested when the _default
@@ -165,7 +165,7 b' class TestTraitType(TestCase):'
165 a = A()
165 a = A()
166 c = C()
166 c = C()
167 self.assertEqual(a._trait_values, {})
167 self.assertEqual(a._trait_values, {})
168 self.assertEqual(a._trait_dyn_inits.keys(), ['x'])
168 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
169 self.assertEqual(a.x, 11)
169 self.assertEqual(a.x, 11)
170 self.assertEqual(a._trait_values, {'x': 11})
170 self.assertEqual(a._trait_values, {'x': 11})
171
171
@@ -718,26 +718,27 b' class TestInt(TraitTestBase):'
718 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
718 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
719 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
719 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
720 if not py3compat.PY3:
720 if not py3compat.PY3:
721 _bad_values.extend([10L, -10L, 10*sys.maxint, -10*sys.maxint])
721 _bad_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
722
722
723
723
724 class LongTrait(HasTraits):
724 class LongTrait(HasTraits):
725
725
726 value = Long(99L)
726 value = Long(99 if py3compat.PY3 else long(99))
727
727
728 class TestLong(TraitTestBase):
728 class TestLong(TraitTestBase):
729
729
730 obj = LongTrait()
730 obj = LongTrait()
731
731
732 _default_value = 99L
732 _default_value = 99 if py3compat.PY3 else long(99)
733 _good_values = [10, -10, 10L, -10L]
733 _good_values = [10, -10]
734 _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,),
734 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
735 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
735 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
736 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
736 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
737 u'-10.1']
737 u'-10.1']
738 if not py3compat.PY3:
738 if not py3compat.PY3:
739 # maxint undefined on py3, because int == long
739 # maxint undefined on py3, because int == long
740 _good_values.extend([10*sys.maxint, -10*sys.maxint])
740 _good_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
741 _bad_values.extend([[long(10)], (long(10),)])
741
742
742 @skipif(py3compat.PY3, "not relevant on py3")
743 @skipif(py3compat.PY3, "not relevant on py3")
743 def test_cast_small(self):
744 def test_cast_small(self):
@@ -762,7 +763,7 b' class TestInteger(TestLong):'
762 if py3compat.PY3:
763 if py3compat.PY3:
763 raise SkipTest("not relevant on py3")
764 raise SkipTest("not relevant on py3")
764
765
765 self.obj.value = 100L
766 self.obj.value = long(100)
766 self.assertEqual(type(self.obj.value), int)
767 self.assertEqual(type(self.obj.value), int)
767
768
768
769
@@ -780,7 +781,7 b' class TestFloat(TraitTestBase):'
780 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
781 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
781 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
782 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
782 if not py3compat.PY3:
783 if not py3compat.PY3:
783 _bad_values.extend([10L, -10L])
784 _bad_values.extend([long(10), long(-10)])
784
785
785
786
786 class ComplexTrait(HasTraits):
787 class ComplexTrait(HasTraits):
@@ -796,7 +797,7 b' class TestComplex(TraitTestBase):'
796 10.1j, 10.1+10.1j, 10.1-10.1j]
797 10.1j, 10.1+10.1j, 10.1-10.1j]
797 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
798 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
798 if not py3compat.PY3:
799 if not py3compat.PY3:
799 _bad_values.extend([10L, -10L])
800 _bad_values.extend([long(10), long(-10)])
800
801
801
802
802 class BytesTrait(HasTraits):
803 class BytesTrait(HasTraits):
@@ -810,8 +811,10 b' class TestBytes(TraitTestBase):'
810 _default_value = b'string'
811 _default_value = b'string'
811 _good_values = [b'10', b'-10', b'10L',
812 _good_values = [b'10', b'-10', b'10L',
812 b'-10L', b'10.1', b'-10.1', b'string']
813 b'-10L', b'10.1', b'-10.1', b'string']
813 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10],
814 _bad_values = [10, -10, 10.1, -10.1, 1j, [10],
814 ['ten'],{'ten': 10},(10,), None, u'string']
815 ['ten'],{'ten': 10},(10,), None, u'string']
816 if not py3compat.PY3:
817 _bad_values.extend([long(10), long(-10)])
815
818
816
819
817 class UnicodeTrait(HasTraits):
820 class UnicodeTrait(HasTraits):
@@ -825,8 +828,10 b' class TestUnicode(TraitTestBase):'
825 _default_value = u'unicode'
828 _default_value = u'unicode'
826 _good_values = ['10', '-10', '10L', '-10L', '10.1',
829 _good_values = ['10', '-10', '10L', '-10L', '10.1',
827 '-10.1', '', u'', 'string', u'string', u"€"]
830 '-10.1', '', u'', 'string', u'string', u"€"]
828 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
831 _bad_values = [10, -10, 10.1, -10.1, 1j,
829 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
832 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
833 if not py3compat.PY3:
834 _bad_values.extend([long(10), long(-10)])
830
835
831
836
832 class ObjectNameTrait(HasTraits):
837 class ObjectNameTrait(HasTraits):
@@ -881,7 +886,7 b' class TestList(TraitTestBase):'
881 obj = ListTrait()
886 obj = ListTrait()
882
887
883 _default_value = []
888 _default_value = []
884 _good_values = [[], [1], range(10)]
889 _good_values = [[], [1], list(range(10))]
885 _bad_values = [10, [1,'a'], 'a', (1,2)]
890 _bad_values = [10, [1,'a'], 'a', (1,2)]
886
891
887 class LenListTrait(HasTraits):
892 class LenListTrait(HasTraits):
@@ -893,8 +898,8 b' class TestLenList(TraitTestBase):'
893 obj = LenListTrait()
898 obj = LenListTrait()
894
899
895 _default_value = [0]
900 _default_value = [0]
896 _good_values = [[1], range(2)]
901 _good_values = [[1], list(range(2))]
897 _bad_values = [10, [1,'a'], 'a', (1,2), [], range(3)]
902 _bad_values = [10, [1,'a'], 'a', (1,2), [], list(range(3))]
898
903
899 class TupleTrait(HasTraits):
904 class TupleTrait(HasTraits):
900
905
@@ -59,9 +59,8 b' class Tests (unittest.TestCase):'
59 ]
59 ]
60 for pat,res in tests:
60 for pat,res in tests:
61 res.sort()
61 res.sort()
62 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,
62 a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=False,
63 show_all=False).keys()
63 show_all=False).keys())
64 a.sort()
65 self.assertEqual(a,res)
64 self.assertEqual(a,res)
66
65
67 def test_case_showall(self):
66 def test_case_showall(self):
@@ -75,9 +74,8 b' class Tests (unittest.TestCase):'
75 ]
74 ]
76 for pat,res in tests:
75 for pat,res in tests:
77 res.sort()
76 res.sort()
78 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,
77 a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=False,
79 show_all=True).keys()
78 show_all=True).keys())
80 a.sort()
81 self.assertEqual(a,res)
79 self.assertEqual(a,res)
82
80
83
81
@@ -93,9 +91,8 b' class Tests (unittest.TestCase):'
93 ]
91 ]
94 for pat,res in tests:
92 for pat,res in tests:
95 res.sort()
93 res.sort()
96 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,
94 a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=True,
97 show_all=False).keys()
95 show_all=False).keys())
98 a.sort()
99 self.assertEqual(a,res)
96 self.assertEqual(a,res)
100
97
101 def test_nocase_showall(self):
98 def test_nocase_showall(self):
@@ -110,8 +107,8 b' class Tests (unittest.TestCase):'
110 ]
107 ]
111 for pat,res in tests:
108 for pat,res in tests:
112 res.sort()
109 res.sort()
113 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,
110 a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=True,
114 show_all=True).keys()
111 show_all=True).keys())
115 a.sort()
112 a.sort()
116 self.assertEqual(a,res)
113 self.assertEqual(a,res)
117
114
@@ -126,9 +123,8 b' class Tests (unittest.TestCase):'
126 ]
123 ]
127 for pat, res in tests:
124 for pat, res in tests:
128 res.sort()
125 res.sort()
129 a = wildcard.list_namespace(ns, "all", pat, ignore_case=False,
126 a = sorted(wildcard.list_namespace(ns, "all", pat, ignore_case=False,
130 show_all=True).keys()
127 show_all=True).keys())
131 a.sort()
132 self.assertEqual(a, res)
128 self.assertEqual(a, res)
133
129
134 def test_dict_dir(self):
130 def test_dict_dir(self):
@@ -29,7 +29,6 b' from IPython.external.path import path'
29 from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
29 from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31
31
32
33 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
34 # Declarations
33 # Declarations
35 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
@@ -177,7 +176,7 b' class SList(list):'
177 except IndexError:
176 except IndexError:
178 return ""
177 return ""
179
178
180 if isinstance(pattern, basestring):
179 if isinstance(pattern, py3compat.string_types):
181 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
180 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
182 else:
181 else:
183 pred = pattern
182 pred = pattern
@@ -321,7 +320,7 b' def list_strings(arg):'
321 Out[9]: ['A', 'list', 'of', 'strings']
320 Out[9]: ['A', 'list', 'of', 'strings']
322 """
321 """
323
322
324 if isinstance(arg,basestring): return [arg]
323 if isinstance(arg, py3compat.string_types): return [arg]
325 else: return arg
324 else: return arg
326
325
327
326
@@ -615,14 +614,14 b' class DollarFormatter(FullEvalFormatter):'
615
614
616 def _chunks(l, n):
615 def _chunks(l, n):
617 """Yield successive n-sized chunks from l."""
616 """Yield successive n-sized chunks from l."""
618 for i in xrange(0, len(l), n):
617 for i in py3compat.xrange(0, len(l), n):
619 yield l[i:i+n]
618 yield l[i:i+n]
620
619
621
620
622 def _find_optimal(rlist , separator_size=2 , displaywidth=80):
621 def _find_optimal(rlist , separator_size=2 , displaywidth=80):
623 """Calculate optimal info to columnize a list of string"""
622 """Calculate optimal info to columnize a list of string"""
624 for nrow in range(1, len(rlist)+1) :
623 for nrow in range(1, len(rlist)+1) :
625 chk = map(max,_chunks(rlist, nrow))
624 chk = list(map(max,_chunks(rlist, nrow)))
626 sumlength = sum(chk)
625 sumlength = sum(chk)
627 ncols = len(chk)
626 ncols = len(chk)
628 if sumlength+separator_size*(ncols-1) <= displaywidth :
627 if sumlength+separator_size*(ncols-1) <= displaywidth :
@@ -695,7 +694,7 b' def compute_item_matrix(items, empty=None, *args, **kwargs) :'
695 'rows_numbers': 5})
694 'rows_numbers': 5})
696
695
697 """
696 """
698 info = _find_optimal(map(len, items), *args, **kwargs)
697 info = _find_optimal(list(map(len, items)), *args, **kwargs)
699 nrow, ncol = info['rows_numbers'], info['columns_numbers']
698 nrow, ncol = info['rows_numbers'], info['columns_numbers']
700 return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range(nrow) ], info)
699 return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range(nrow) ], info)
701
700
@@ -16,6 +16,8 b' Utilities for timing code execution.'
16
16
17 import time
17 import time
18
18
19 from .py3compat import xrange
20
19 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
20 # Code
22 # Code
21 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
@@ -4,6 +4,6 b''
4 import sys
4 import sys
5
5
6 if sys.version_info[0] >= 3:
6 if sys.version_info[0] >= 3:
7 from _tokenize_py3 import *
7 from ._tokenize_py3 import *
8 else:
8 else:
9 from _tokenize_py2 import *
9 from ._tokenize_py2 import *
@@ -66,6 +66,7 b' except:'
66
66
67 from .importstring import import_item
67 from .importstring import import_item
68 from IPython.utils import py3compat
68 from IPython.utils import py3compat
69 from IPython.utils.py3compat import iteritems
69
70
70 SequenceTypes = (list, tuple, set, frozenset)
71 SequenceTypes = (list, tuple, set, frozenset)
71
72
@@ -94,7 +95,7 b' def class_of ( object ):'
94 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
95 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
95 'a PlotValue').
96 'a PlotValue').
96 """
97 """
97 if isinstance( object, basestring ):
98 if isinstance( object, py3compat.string_types ):
98 return add_article( object )
99 return add_article( object )
99
100
100 return add_article( object.__class__.__name__ )
101 return add_article( object.__class__.__name__ )
@@ -373,7 +374,7 b' class MetaHasTraits(type):'
373 # print "MetaHasTraitlets (mcls, name): ", mcls, name
374 # print "MetaHasTraitlets (mcls, name): ", mcls, name
374 # print "MetaHasTraitlets (bases): ", bases
375 # print "MetaHasTraitlets (bases): ", bases
375 # print "MetaHasTraitlets (classdict): ", classdict
376 # print "MetaHasTraitlets (classdict): ", classdict
376 for k,v in classdict.iteritems():
377 for k,v in iteritems(classdict):
377 if isinstance(v, TraitType):
378 if isinstance(v, TraitType):
378 v.name = k
379 v.name = k
379 elif inspect.isclass(v):
380 elif inspect.isclass(v):
@@ -389,14 +390,12 b' class MetaHasTraits(type):'
389 This sets the :attr:`this_class` attribute of each TraitType in the
390 This sets the :attr:`this_class` attribute of each TraitType in the
390 class dict to the newly created class ``cls``.
391 class dict to the newly created class ``cls``.
391 """
392 """
392 for k, v in classdict.iteritems():
393 for k, v in iteritems(classdict):
393 if isinstance(v, TraitType):
394 if isinstance(v, TraitType):
394 v.this_class = cls
395 v.this_class = cls
395 super(MetaHasTraits, cls).__init__(name, bases, classdict)
396 super(MetaHasTraits, cls).__init__(name, bases, classdict)
396
397
397 class HasTraits(object):
398 class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)):
398
399 __metaclass__ = MetaHasTraits
400
399
401 def __new__(cls, *args, **kw):
400 def __new__(cls, *args, **kw):
402 # This is needed because in Python 2.6 object.__new__ only accepts
401 # This is needed because in Python 2.6 object.__new__ only accepts
@@ -429,7 +428,7 b' class HasTraits(object):'
429 # Allow trait values to be set using keyword arguments.
428 # Allow trait values to be set using keyword arguments.
430 # We need to use setattr for this to trigger validation and
429 # We need to use setattr for this to trigger validation and
431 # notifications.
430 # notifications.
432 for key, value in kw.iteritems():
431 for key, value in iteritems(kw):
433 setattr(self, key, value)
432 setattr(self, key, value)
434
433
435 def _notify_trait(self, name, old_value, new_value):
434 def _notify_trait(self, name, old_value, new_value):
@@ -680,7 +679,7 b' class Type(ClassBasedTraitType):'
680 elif klass is None:
679 elif klass is None:
681 klass = default_value
680 klass = default_value
682
681
683 if not (inspect.isclass(klass) or isinstance(klass, basestring)):
682 if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
684 raise TraitError("A Type trait must specify a class.")
683 raise TraitError("A Type trait must specify a class.")
685
684
686 self.klass = klass
685 self.klass = klass
@@ -701,7 +700,7 b' class Type(ClassBasedTraitType):'
701
700
702 def info(self):
701 def info(self):
703 """ Returns a description of the trait."""
702 """ Returns a description of the trait."""
704 if isinstance(self.klass, basestring):
703 if isinstance(self.klass, py3compat.string_types):
705 klass = self.klass
704 klass = self.klass
706 else:
705 else:
707 klass = self.klass.__name__
706 klass = self.klass.__name__
@@ -715,9 +714,9 b' class Type(ClassBasedTraitType):'
715 super(Type, self).instance_init(obj)
714 super(Type, self).instance_init(obj)
716
715
717 def _resolve_classes(self):
716 def _resolve_classes(self):
718 if isinstance(self.klass, basestring):
717 if isinstance(self.klass, py3compat.string_types):
719 self.klass = import_item(self.klass)
718 self.klass = import_item(self.klass)
720 if isinstance(self.default_value, basestring):
719 if isinstance(self.default_value, py3compat.string_types):
721 self.default_value = import_item(self.default_value)
720 self.default_value = import_item(self.default_value)
722
721
723 def get_default_value(self):
722 def get_default_value(self):
@@ -772,7 +771,7 b' class Instance(ClassBasedTraitType):'
772
771
773 self._allow_none = allow_none
772 self._allow_none = allow_none
774
773
775 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, basestring))):
774 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types))):
776 raise TraitError('The klass argument must be a class'
775 raise TraitError('The klass argument must be a class'
777 ' you gave: %r' % klass)
776 ' you gave: %r' % klass)
778 self.klass = klass
777 self.klass = klass
@@ -809,7 +808,7 b' class Instance(ClassBasedTraitType):'
809 self.error(obj, value)
808 self.error(obj, value)
810
809
811 def info(self):
810 def info(self):
812 if isinstance(self.klass, basestring):
811 if isinstance(self.klass, py3compat.string_types):
813 klass = self.klass
812 klass = self.klass
814 else:
813 else:
815 klass = self.klass.__name__
814 klass = self.klass.__name__
@@ -824,7 +823,7 b' class Instance(ClassBasedTraitType):'
824 super(Instance, self).instance_init(obj)
823 super(Instance, self).instance_init(obj)
825
824
826 def _resolve_classes(self):
825 def _resolve_classes(self):
827 if isinstance(self.klass, basestring):
826 if isinstance(self.klass, py3compat.string_types):
828 self.klass = import_item(self.klass)
827 self.klass = import_item(self.klass)
829
828
830 def get_default_value(self):
829 def get_default_value(self):
@@ -901,7 +900,7 b' else:'
901 class Long(TraitType):
900 class Long(TraitType):
902 """A long integer trait."""
901 """A long integer trait."""
903
902
904 default_value = 0L
903 default_value = 0
905 info_text = 'a long'
904 info_text = 'a long'
906
905
907 def validate(self, obj, value):
906 def validate(self, obj, value):
@@ -1022,10 +1021,10 b' class Unicode(TraitType):'
1022 info_text = 'a unicode string'
1021 info_text = 'a unicode string'
1023
1022
1024 def validate(self, obj, value):
1023 def validate(self, obj, value):
1025 if isinstance(value, unicode):
1024 if isinstance(value, py3compat.unicode_type):
1026 return value
1025 return value
1027 if isinstance(value, bytes):
1026 if isinstance(value, bytes):
1028 return unicode(value)
1027 return py3compat.unicode_type(value)
1029 self.error(obj, value)
1028 self.error(obj, value)
1030
1029
1031
1030
@@ -1034,7 +1033,7 b' class CUnicode(Unicode):'
1034
1033
1035 def validate(self, obj, value):
1034 def validate(self, obj, value):
1036 try:
1035 try:
1037 return unicode(value)
1036 return py3compat.unicode_type(value)
1038 except:
1037 except:
1039 self.error(obj, value)
1038 self.error(obj, value)
1040
1039
@@ -1131,7 +1130,7 b' class CaselessStrEnum(Enum):'
1131 if self._allow_none:
1130 if self._allow_none:
1132 return value
1131 return value
1133
1132
1134 if not isinstance(value, basestring):
1133 if not isinstance(value, py3compat.string_types):
1135 self.error(obj, value)
1134 self.error(obj, value)
1136
1135
1137 for v in self.values:
1136 for v in self.values:
@@ -1418,7 +1417,7 b' class TCPAddress(TraitType):'
1418 def validate(self, obj, value):
1417 def validate(self, obj, value):
1419 if isinstance(value, tuple):
1418 if isinstance(value, tuple):
1420 if len(value) == 2:
1419 if len(value) == 2:
1421 if isinstance(value[0], basestring) and isinstance(value[1], int):
1420 if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int):
1422 port = value[1]
1421 port = value[1]
1423 if port >= 0 and port <= 65535:
1422 if port >= 0 and port <= 65535:
1424 return value
1423 return value
@@ -26,7 +26,7 b' else:'
26 lines = linecache.getlines(filename, module_globals=module_globals)
26 lines = linecache.getlines(filename, module_globals=module_globals)
27
27
28 # The bits we cache ourselves can be unicode.
28 # The bits we cache ourselves can be unicode.
29 if (not lines) or isinstance(lines[0], unicode):
29 if (not lines) or isinstance(lines[0], py3compat.unicode_type):
30 return lines
30 return lines
31
31
32 readline = openpy._list_readline(lines)
32 readline = openpy._list_readline(lines)
@@ -18,6 +18,7 b' import re'
18 import types
18 import types
19
19
20 from IPython.utils.dir2 import dir2
20 from IPython.utils.dir2 import dir2
21 from .py3compat import iteritems
21
22
22 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
23 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
23 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
24 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
@@ -43,7 +44,7 b' def is_type(obj, typestr_or_type):'
43 TODO: Should be extended for choosing more than one type."""
44 TODO: Should be extended for choosing more than one type."""
44 if typestr_or_type == "all":
45 if typestr_or_type == "all":
45 return True
46 return True
46 if type(typestr_or_type) == types.TypeType:
47 if type(typestr_or_type) == type:
47 test_type = typestr_or_type
48 test_type = typestr_or_type
48 else:
49 else:
49 test_type = typestr2type.get(typestr_or_type, False)
50 test_type = typestr2type.get(typestr_or_type, False)
@@ -82,7 +83,7 b' def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,'
82 reg = re.compile(pattern+"$")
83 reg = re.compile(pattern+"$")
83
84
84 # Check each one matches regex; shouldn't be hidden; of correct type.
85 # Check each one matches regex; shouldn't be hidden; of correct type.
85 return dict((key,obj) for key, obj in ns.iteritems() if reg.match(key) \
86 return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \
86 and show_hidden(key, show_all) \
87 and show_hidden(key, show_all) \
87 and is_type(obj, type_pattern) )
88 and is_type(obj, type_pattern) )
88
89
@@ -102,10 +103,10 b' def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all='
102 type_pattern="all",
103 type_pattern="all",
103 ignore_case=ignore_case, show_all=show_all)
104 ignore_case=ignore_case, show_all=show_all)
104 results = {}
105 results = {}
105 for name, obj in filtered.iteritems():
106 for name, obj in iteritems(filtered):
106 ns = list_namespace(dict_dir(obj), type_pattern,
107 ns = list_namespace(dict_dir(obj), type_pattern,
107 ".".join(pattern_list[1:]),
108 ".".join(pattern_list[1:]),
108 ignore_case=ignore_case, show_all=show_all)
109 ignore_case=ignore_case, show_all=show_all)
109 for inner_name, inner_obj in ns.iteritems():
110 for inner_name, inner_obj in iteritems(ns):
110 results["%s.%s"%(name,inner_name)] = inner_obj
111 results["%s.%s"%(name,inner_name)] = inner_obj
111 return results
112 return results
@@ -46,6 +46,7 b' extensions = ['
46 'sphinx.ext.autodoc',
46 'sphinx.ext.autodoc',
47 'sphinx.ext.doctest',
47 'sphinx.ext.doctest',
48 'sphinx.ext.inheritance_diagram',
48 'sphinx.ext.inheritance_diagram',
49 'sphinx.ext.intersphinx',
49 'IPython.sphinxext.ipython_console_highlighting',
50 'IPython.sphinxext.ipython_console_highlighting',
50 'IPython.sphinxext.ipython_directive',
51 'IPython.sphinxext.ipython_directive',
51 'numpydoc', # to preprocess docstrings
52 'numpydoc', # to preprocess docstrings
@@ -178,6 +179,7 b' html_additional_pages = {'
178 # Output file base name for HTML help builder.
179 # Output file base name for HTML help builder.
179 htmlhelp_basename = 'ipythondoc'
180 htmlhelp_basename = 'ipythondoc'
180
181
182 intersphinx_mapping = {'http://docs.python.org/2/': None}
181
183
182 # Options for LaTeX output
184 # Options for LaTeX output
183 # ------------------------
185 # ------------------------
@@ -24,3 +24,4 b' on the IPython GitHub wiki.'
24 messaging
24 messaging
25 parallel_messages
25 parallel_messages
26 parallel_connections
26 parallel_connections
27 pycompat
@@ -51,10 +51,6 b" if os.path.exists('MANIFEST'): os.remove('MANIFEST')"
51
51
52 from distutils.core import setup
52 from distutils.core import setup
53
53
54 # On Python 3, we need distribute (new setuptools) to do the 2to3 conversion
55 if PY3:
56 import setuptools
57
58 # Our own imports
54 # Our own imports
59 from setupbase import target_update
55 from setupbase import target_update
60
56
@@ -63,6 +59,7 b' from setupbase import ('
63 find_packages,
59 find_packages,
64 find_package_data,
60 find_package_data,
65 find_scripts,
61 find_scripts,
62 build_scripts_rename,
66 find_data_files,
63 find_data_files,
67 check_for_dependencies,
64 check_for_dependencies,
68 git_prebuild,
65 git_prebuild,
@@ -266,7 +263,7 b" if 'setuptools' in sys.modules:"
266 setup_args['cmdclass']['develop'] = require_submodules(develop)
263 setup_args['cmdclass']['develop'] = require_submodules(develop)
267
264
268 setuptools_extra_args['zip_safe'] = False
265 setuptools_extra_args['zip_safe'] = False
269 setuptools_extra_args['entry_points'] = find_scripts(True)
266 setuptools_extra_args['entry_points'] = find_scripts(True, suffix = '3' if PY3 else '')
270 setup_args['extras_require'] = dict(
267 setup_args['extras_require'] = dict(
271 parallel = 'pyzmq>=2.1.11',
268 parallel = 'pyzmq>=2.1.11',
272 qtconsole = ['pyzmq>=2.1.11', 'pygments'],
269 qtconsole = ['pyzmq>=2.1.11', 'pygments'],
@@ -314,29 +311,15 b" if 'setuptools' in sys.modules:"
314 {"install_script":
311 {"install_script":
315 "ipython_win_post_install.py"}}
312 "ipython_win_post_install.py"}}
316
313
317 if PY3:
318 setuptools_extra_args['use_2to3'] = True
319 # we try to make a 2.6, 2.7, and 3.1 to 3.3 python compatible code
320 # so we explicitly disable some 2to3 fixes to be sure we aren't forgetting
321 # anything.
322 setuptools_extra_args['use_2to3_exclude_fixers'] = [
323 'lib2to3.fixes.fix_apply',
324 'lib2to3.fixes.fix_except',
325 'lib2to3.fixes.fix_has_key',
326 'lib2to3.fixes.fix_next',
327 'lib2to3.fixes.fix_repr',
328 'lib2to3.fixes.fix_tuple_params',
329 ]
330 from setuptools.command.build_py import build_py
331 setup_args['cmdclass'] = {'build_py': git_prebuild('IPython', build_cmd=build_py)}
332 setuptools_extra_args['entry_points'] = find_scripts(True, suffix='3')
333 setuptools._dont_write_bytecode = True
334 else:
314 else:
335 # If we are running without setuptools, call this function which will
315 # If we are running without setuptools, call this function which will
336 # check for dependencies an inform the user what is needed. This is
316 # check for dependencies an inform the user what is needed. This is
337 # just to make life easy for users.
317 # just to make life easy for users.
338 check_for_dependencies()
318 check_for_dependencies()
339 setup_args['scripts'] = find_scripts(False)
319 setup_args['scripts'] = find_scripts(False)
320 if PY3:
321 # Rename scripts with '3' suffix
322 setup_args['cmdclass']['build_scripts'] = build_scripts_rename
340
323
341 #---------------------------------------------------------------------------
324 #---------------------------------------------------------------------------
342 # Do the actual setup now
325 # Do the actual setup now
@@ -28,6 +28,7 b' try:'
28 except:
28 except:
29 from ConfigParser import ConfigParser
29 from ConfigParser import ConfigParser
30 from distutils.command.build_py import build_py
30 from distutils.command.build_py import build_py
31 from distutils.command.build_scripts import build_scripts
31 from distutils.cmd import Command
32 from distutils.cmd import Command
32 from glob import glob
33 from glob import glob
33 from subprocess import call
34 from subprocess import call
@@ -347,6 +348,21 b" def find_scripts(entry_points=False, suffix=''):"
347 ]
348 ]
348 return scripts
349 return scripts
349
350
351 class build_scripts_rename(build_scripts):
352 """Use this on Python 3 to rename scripts to ipython3 etc."""
353 _suffix = '3'
354
355 def copy_scripts(self):
356 outfiles, updated_files = super(build_scripts_rename, self).copy_scripts()
357 new_outfiles = [p + self._suffix for p in outfiles]
358 updated_files = [p + self._suffix for p in updated_files]
359 for old, new in zip(outfiles, new_outfiles):
360 if os.path.exists(new):
361 os.unlink(new)
362 self.move_file(old, new)
363 return new_outfiles, updated_files
364
365
350 #---------------------------------------------------------------------------
366 #---------------------------------------------------------------------------
351 # Verify all dependencies
367 # Verify all dependencies
352 #---------------------------------------------------------------------------
368 #---------------------------------------------------------------------------
@@ -3,4 +3,5 b''
3
3
4 # Import setuptools and call the actual setup
4 # Import setuptools and call the actual setup
5 import setuptools
5 import setuptools
6 execfile('setup.py')
6 with open('setup.py', 'rb') as f:
7 exec(compile(f.read(), 'setup.py', 'exec'))
General Comments 0
You need to be logged in to leave comments. Login now