Show More
@@ -4,3 +4,5 b' docs/source/api/generated' | |||||
4 | *.pyc |
|
4 | *.pyc | |
5 | build |
|
5 | build | |
6 | *.egg-info |
|
6 | *.egg-info | |
|
7 | *.py~ | |||
|
8 | *.bak |
@@ -47,7 +47,7 b' from .testing import test' | |||||
47 |
|
47 | |||
48 | # Release data |
|
48 | # Release data | |
49 | __author__ = '' |
|
49 | __author__ = '' | |
50 | for author, email in release.authors.values(): |
|
50 | for author, email in release.authors.itervalues(): | |
51 | __author__ += author + ' <' + email + '>\n' |
|
51 | __author__ += author + ' <' + email + '>\n' | |
52 | __license__ = release.license |
|
52 | __license__ = release.license | |
53 | __version__ = release.version |
|
53 | __version__ = release.version |
@@ -112,7 +112,7 b' class Configurable(HasTraits):' | |||||
112 | # dynamically create the section with name self.__class__.__name__. |
|
112 | # dynamically create the section with name self.__class__.__name__. | |
113 | if new._has_section(sname): |
|
113 | if new._has_section(sname): | |
114 | my_config = new[sname] |
|
114 | my_config = new[sname] | |
115 | for k, v in traits.items(): |
|
115 | for k, v in traits.iteritems(): | |
116 | # Don't allow traitlets with config=True to start with |
|
116 | # Don't allow traitlets with config=True to start with | |
117 | # uppercase. Otherwise, they are confused with Config |
|
117 | # uppercase. Otherwise, they are confused with Config | |
118 | # subsections. But, developers shouldn't have uppercase |
|
118 | # subsections. But, developers shouldn't have uppercase |
@@ -1,3 +1,4 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
1 | # coding: utf-8 |
|
2 | # coding: utf-8 | |
2 | """A simple configuration system. |
|
3 | """A simple configuration system. | |
3 |
|
4 | |||
@@ -73,7 +74,7 b' class Config(dict):' | |||||
73 |
|
74 | |||
74 | def _merge(self, other): |
|
75 | def _merge(self, other): | |
75 | to_update = {} |
|
76 | to_update = {} | |
76 | for k, v in other.items(): |
|
77 | for k, v in other.iteritems(): | |
77 | if not self.has_key(k): |
|
78 | if not self.has_key(k): | |
78 | to_update[k] = v |
|
79 | to_update[k] = v | |
79 | else: # I have this key |
|
80 | else: # I have this key | |
@@ -92,15 +93,17 b' class Config(dict):' | |||||
92 | else: |
|
93 | else: | |
93 | return False |
|
94 | return False | |
94 |
|
95 | |||
95 |
def |
|
96 | def __contains__(self, key): | |
96 | if self._is_section_key(key): |
|
97 | if self._is_section_key(key): | |
97 | return True |
|
98 | return True | |
98 | else: |
|
99 | else: | |
99 | return dict.has_key(self, key) |
|
100 | return super(Config, self).__contains__(key) | |
|
101 | # .has_key is deprecated for dictionaries. | |||
|
102 | has_key = __contains__ | |||
100 |
|
103 | |||
101 | def _has_section(self, key): |
|
104 | def _has_section(self, key): | |
102 | if self._is_section_key(key): |
|
105 | if self._is_section_key(key): | |
103 | if dict.has_key(self, key): |
|
106 | if super(Config, self).__contains__(key): | |
104 | return True |
|
107 | return True | |
105 | return False |
|
108 | return False | |
106 |
|
109 | |||
@@ -363,7 +366,7 b' class ArgParseConfigLoader(CommandLineConfigLoader):' | |||||
363 |
|
366 | |||
364 | def _convert_to_config(self): |
|
367 | def _convert_to_config(self): | |
365 | """self.parsed_data->self.config""" |
|
368 | """self.parsed_data->self.config""" | |
366 | for k, v in vars(self.parsed_data).items(): |
|
369 | for k, v in vars(self.parsed_data).iteritems(): | |
367 | exec_str = 'self.config.' + k + '= v' |
|
370 | exec_str = 'self.config.' + k + '= v' | |
368 | exec exec_str in locals(), globals() |
|
371 | exec exec_str in locals(), globals() | |
369 |
|
372 |
@@ -336,7 +336,7 b' def cd_completer(self, event):' | |||||
336 | return [compress_user(relpath, tilde_expand, tilde_val)] |
|
336 | return [compress_user(relpath, tilde_expand, tilde_val)] | |
337 |
|
337 | |||
338 | # if no completions so far, try bookmarks |
|
338 | # if no completions so far, try bookmarks | |
339 | bks = self.db.get('bookmarks',{}).keys() |
|
339 | bks = self.db.get('bookmarks',{}).iterkeys() | |
340 | bkmatches = [s for s in bks if s.startswith(event.symbol)] |
|
340 | bkmatches = [s for s in bks if s.startswith(event.symbol)] | |
341 | if bkmatches: |
|
341 | if bkmatches: | |
342 | return bkmatches |
|
342 | return bkmatches |
@@ -260,7 +260,7 b' class ShadowHist(object):' | |||||
260 |
|
260 | |||
261 | def all(self): |
|
261 | def all(self): | |
262 | d = self.db.hdict('shadowhist') |
|
262 | d = self.db.hdict('shadowhist') | |
263 | items = [(i,s) for (s,i) in d.items()] |
|
263 | items = [(i,s) for (s,i) in d.iteritems()] | |
264 | items.sort() |
|
264 | items.sort() | |
265 | return items |
|
265 | return items | |
266 |
|
266 |
@@ -22,13 +22,12 b' import __future__' | |||||
22 | import abc |
|
22 | import abc | |
23 | import atexit |
|
23 | import atexit | |
24 | import codeop |
|
24 | import codeop | |
25 | import exceptions |
|
|||
26 | import new |
|
|||
27 | import os |
|
25 | import os | |
28 | import re |
|
26 | import re | |
29 | import string |
|
27 | import string | |
30 | import sys |
|
28 | import sys | |
31 | import tempfile |
|
29 | import tempfile | |
|
30 | import types | |||
32 | from contextlib import nested |
|
31 | from contextlib import nested | |
33 |
|
32 | |||
34 | from IPython.config.configurable import Configurable |
|
33 | from IPython.config.configurable import Configurable | |
@@ -102,7 +101,7 b' def softspace(file, newvalue):' | |||||
102 |
|
101 | |||
103 | def no_op(*a, **kw): pass |
|
102 | def no_op(*a, **kw): pass | |
104 |
|
103 | |||
105 |
class SpaceInInput( |
|
104 | class SpaceInInput(Exception): pass | |
106 |
|
105 | |||
107 | class Bunch: pass |
|
106 | class Bunch: pass | |
108 |
|
107 | |||
@@ -512,7 +511,7 b' class InteractiveShell(Configurable, Magic):' | |||||
512 | def restore_sys_module_state(self): |
|
511 | def restore_sys_module_state(self): | |
513 | """Restore the state of the sys module.""" |
|
512 | """Restore the state of the sys module.""" | |
514 | try: |
|
513 | try: | |
515 | for k, v in self._orig_sys_module_state.items(): |
|
514 | for k, v in self._orig_sys_module_state.iteritems(): | |
516 | setattr(sys, k, v) |
|
515 | setattr(sys, k, v) | |
517 | except AttributeError: |
|
516 | except AttributeError: | |
518 | pass |
|
517 | pass | |
@@ -550,7 +549,7 b' class InteractiveShell(Configurable, Magic):' | |||||
550 | # accepts it. Probably at least check that the hook takes the number |
|
549 | # accepts it. Probably at least check that the hook takes the number | |
551 | # of args it's supposed to. |
|
550 | # of args it's supposed to. | |
552 |
|
551 | |||
553 |
f = |
|
552 | f = types.MethodType(hook, self) | |
554 |
|
553 | |||
555 | # check if the hook is for strdispatcher first |
|
554 | # check if the hook is for strdispatcher first | |
556 | if str_key is not None: |
|
555 | if str_key is not None: | |
@@ -1249,7 +1248,7 b' class InteractiveShell(Configurable, Magic):' | |||||
1249 | def init_shadow_hist(self): |
|
1248 | def init_shadow_hist(self): | |
1250 | try: |
|
1249 | try: | |
1251 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") |
|
1250 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
1252 |
except |
|
1251 | except UnicodeDecodeError: | |
1253 | print "Your ipython_dir can't be decoded to unicode!" |
|
1252 | print "Your ipython_dir can't be decoded to unicode!" | |
1254 | print "Please set HOME environment variable to something that" |
|
1253 | print "Please set HOME environment variable to something that" | |
1255 | print r"only has ASCII characters, e.g. c:\home" |
|
1254 | print r"only has ASCII characters, e.g. c:\home" | |
@@ -1414,7 +1413,7 b' class InteractiveShell(Configurable, Magic):' | |||||
1414 |
|
1413 | |||
1415 | if handler is None: handler = dummy_handler |
|
1414 | if handler is None: handler = dummy_handler | |
1416 |
|
1415 | |||
1417 |
self.CustomTB = |
|
1416 | self.CustomTB = types.MethodType(handler, self) | |
1418 | self.custom_exceptions = exc_tuple |
|
1417 | self.custom_exceptions = exc_tuple | |
1419 |
|
1418 | |||
1420 | def excepthook(self, etype, value, tb): |
|
1419 | def excepthook(self, etype, value, tb): | |
@@ -1756,8 +1755,7 b' class InteractiveShell(Configurable, Magic):' | |||||
1756 | The position argument (defaults to 0) is the index in the completers |
|
1755 | The position argument (defaults to 0) is the index in the completers | |
1757 | list where you want the completer to be inserted.""" |
|
1756 | list where you want the completer to be inserted.""" | |
1758 |
|
1757 | |||
1759 |
newcomp = |
|
1758 | newcomp = types.MethodType(completer, self.Completer) | |
1760 | self.Completer.__class__) |
|
|||
1761 | self.Completer.matchers.insert(pos,newcomp) |
|
1759 | self.Completer.matchers.insert(pos,newcomp) | |
1762 |
|
1760 | |||
1763 | def set_readline_completer(self): |
|
1761 | def set_readline_completer(self): | |
@@ -1828,12 +1826,11 b' class InteractiveShell(Configurable, Magic):' | |||||
1828 | print 'Magic function. Passed parameter is between < >:' |
|
1826 | print 'Magic function. Passed parameter is between < >:' | |
1829 | print '<%s>' % parameter_s |
|
1827 | print '<%s>' % parameter_s | |
1830 | print 'The self object is:',self |
|
1828 | print 'The self object is:',self | |
1831 |
|
1829 | newcomp = types.MethodType(completer, self.Completer) | ||
1832 | self.define_magic('foo',foo_impl) |
|
1830 | self.define_magic('foo',foo_impl) | |
1833 | """ |
|
1831 | """ | |
1834 |
|
1832 | |||
1835 | import new |
|
1833 | im = types.MethodType(func, self) | |
1836 | im = new.instancemethod(func,self, self.__class__) |
|
|||
1837 | old = getattr(self, "magic_" + magicname, None) |
|
1834 | old = getattr(self, "magic_" + magicname, None) | |
1838 | setattr(self, "magic_" + magicname, im) |
|
1835 | setattr(self, "magic_" + magicname, im) | |
1839 | return old |
|
1836 | return old |
@@ -237,7 +237,7 b' class PrefilterManager(Configurable):' | |||||
237 | This must be called after the priority of a transformer is changed. |
|
237 | This must be called after the priority of a transformer is changed. | |
238 | The :meth:`register_transformer` method calls this automatically. |
|
238 | The :meth:`register_transformer` method calls this automatically. | |
239 | """ |
|
239 | """ | |
240 |
self._transformers.sort( |
|
240 | self._transformers.sort(key=lambda x: x.priority) | |
241 |
|
241 | |||
242 | @property |
|
242 | @property | |
243 | def transformers(self): |
|
243 | def transformers(self): | |
@@ -273,7 +273,7 b' class PrefilterManager(Configurable):' | |||||
273 | This must be called after the priority of a checker is changed. |
|
273 | This must be called after the priority of a checker is changed. | |
274 | The :meth:`register_checker` method calls this automatically. |
|
274 | The :meth:`register_checker` method calls this automatically. | |
275 | """ |
|
275 | """ | |
276 |
self._checkers.sort( |
|
276 | self._checkers.sort(key=lambda x: x.priority) | |
277 |
|
277 | |||
278 | @property |
|
278 | @property | |
279 | def checkers(self): |
|
279 | def checkers(self): |
@@ -28,7 +28,7 b' from IPython.core import inputsplitter as isp' | |||||
28 | # Note: at the bottom, there's a slightly more complete version of this that |
|
28 | # Note: at the bottom, there's a slightly more complete version of this that | |
29 | # can be useful during development of code here. |
|
29 | # can be useful during development of code here. | |
30 |
|
30 | |||
31 |
def mini_interactive_loop( |
|
31 | def mini_interactive_loop(input_func): | |
32 | """Minimal example of the logic of an interactive interpreter loop. |
|
32 | """Minimal example of the logic of an interactive interpreter loop. | |
33 |
|
33 | |||
34 | This serves as an example, and it is used by the test system with a fake |
|
34 | This serves as an example, and it is used by the test system with a fake | |
@@ -43,7 +43,7 b' def mini_interactive_loop(raw_input):' | |||||
43 | while isp.push_accepts_more(): |
|
43 | while isp.push_accepts_more(): | |
44 | indent = ' '*isp.indent_spaces |
|
44 | indent = ' '*isp.indent_spaces | |
45 | prompt = '>>> ' + indent |
|
45 | prompt = '>>> ' + indent | |
46 |
line = indent + |
|
46 | line = indent + input_func(prompt) | |
47 | isp.push(line) |
|
47 | isp.push(line) | |
48 |
|
48 | |||
49 | # Here we just return input so we can use it in a test suite, but a real |
|
49 | # Here we just return input so we can use it in a test suite, but a real | |
@@ -356,7 +356,7 b' class InteractiveLoopTestCase(unittest.TestCase):' | |||||
356 | # We can't check that the provided ns is identical to the test_ns, |
|
356 | # We can't check that the provided ns is identical to the test_ns, | |
357 | # because Python fills test_ns with extra keys (copyright, etc). But |
|
357 | # because Python fills test_ns with extra keys (copyright, etc). But | |
358 | # we can check that the given dict is *contained* in test_ns |
|
358 | # we can check that the given dict is *contained* in test_ns | |
359 | for k,v in ns.items(): |
|
359 | for k,v in ns.iteritems(): | |
360 | self.assertEqual(test_ns[k], v) |
|
360 | self.assertEqual(test_ns[k], v) | |
361 |
|
361 | |||
362 | def test_simple(self): |
|
362 | def test_simple(self): |
@@ -33,7 +33,7 b' def test_rehashx():' | |||||
33 | # Practically ALL ipython development systems will have more than 10 aliases |
|
33 | # Practically ALL ipython development systems will have more than 10 aliases | |
34 |
|
34 | |||
35 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) |
|
35 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) | |
36 | for key, val in _ip.alias_manager.alias_table.items(): |
|
36 | for key, val in _ip.alias_manager.alias_table.iteritems(): | |
37 | # we must strip dots from alias names |
|
37 | # we must strip dots from alias names | |
38 | nt.assert_true('.' not in key) |
|
38 | nt.assert_true('.' not in key) | |
39 |
|
39 |
@@ -712,14 +712,14 b' class VerboseTB(TBTools):' | |||||
712 |
|
712 | |||
713 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
713 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, | |
714 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
714 | exc, ' '*(75-len(str(etype))-len(pyver)), | |
715 |
pyver, |
|
715 | pyver, date.rjust(75) ) | |
716 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
716 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ | |
717 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
717 | "\ncalls leading up to the error, with the most recent (innermost) call last." | |
718 | else: |
|
718 | else: | |
719 | # Simplified header |
|
719 | # Simplified header | |
720 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
720 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, | |
721 |
|
|
721 | 'Traceback (most recent call last)'.\ | |
722 | 75 - len(str(etype)) ) ) |
|
722 | rjust(75 - len(str(etype)) ) ) | |
723 | frames = [] |
|
723 | frames = [] | |
724 | # Flush cache before calling inspect. This helps alleviate some of the |
|
724 | # Flush cache before calling inspect. This helps alleviate some of the | |
725 | # problems with python 2.3's inspect.py. |
|
725 | # problems with python 2.3's inspect.py. |
@@ -78,7 +78,6 b" __license__ = 'MIT'" | |||||
78 | import string |
|
78 | import string | |
79 | import sys |
|
79 | import sys | |
80 | from tokenize import tokenprog |
|
80 | from tokenize import tokenprog | |
81 | from types import StringType |
|
|||
82 |
|
81 | |||
83 | class ItplError(ValueError): |
|
82 | class ItplError(ValueError): | |
84 | def __init__(self, text, pos): |
|
83 | def __init__(self, text, pos): | |
@@ -144,7 +143,7 b' class Itpl:' | |||||
144 | pos = 0 |
|
143 | pos = 0 | |
145 |
|
144 | |||
146 | while 1: |
|
145 | while 1: | |
147 |
dollar = |
|
146 | dollar = format.find("$", pos) | |
148 | if dollar < 0: break |
|
147 | if dollar < 0: break | |
149 | nextchar = format[dollar+1] |
|
148 | nextchar = format[dollar+1] | |
150 |
|
149 |
@@ -1,3 +1,4 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
1 | # configobj.py |
|
2 | # configobj.py | |
2 | # A config file reader/writer that supports nested sections in config files. |
|
3 | # A config file reader/writer that supports nested sections in config files. | |
3 | # Copyright (C) 2005-2008 Michael Foord, Nicola Larosa |
|
4 | # Copyright (C) 2005-2008 Michael Foord, Nicola Larosa | |
@@ -32,22 +33,7 b' except ImportError:' | |||||
32 | pass |
|
33 | pass | |
33 | from types import StringTypes |
|
34 | from types import StringTypes | |
34 | from warnings import warn |
|
35 | from warnings import warn | |
35 | try: |
|
36 | from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE | |
36 | from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE |
|
|||
37 | except ImportError: |
|
|||
38 | # Python 2.2 does not have these |
|
|||
39 | # UTF-8 |
|
|||
40 | BOM_UTF8 = '\xef\xbb\xbf' |
|
|||
41 | # UTF-16, little endian |
|
|||
42 | BOM_UTF16_LE = '\xff\xfe' |
|
|||
43 | # UTF-16, big endian |
|
|||
44 | BOM_UTF16_BE = '\xfe\xff' |
|
|||
45 | if sys.byteorder == 'little': |
|
|||
46 | # UTF-16, native endianness |
|
|||
47 | BOM_UTF16 = BOM_UTF16_LE |
|
|||
48 | else: |
|
|||
49 | # UTF-16, native endianness |
|
|||
50 | BOM_UTF16 = BOM_UTF16_BE |
|
|||
51 |
|
37 | |||
52 | # A dictionary mapping BOM to |
|
38 | # A dictionary mapping BOM to | |
53 | # the encoding to decode with, and what to set the |
|
39 | # the encoding to decode with, and what to set the | |
@@ -101,21 +87,6 b' wspace_plus = \' \\r\\t\\n\\v\\t\\\'"\'' | |||||
101 | tsquot = '"""%s"""' |
|
87 | tsquot = '"""%s"""' | |
102 | tdquot = "'''%s'''" |
|
88 | tdquot = "'''%s'''" | |
103 |
|
89 | |||
104 | try: |
|
|||
105 | enumerate |
|
|||
106 | except NameError: |
|
|||
107 | def enumerate(obj): |
|
|||
108 | """enumerate for Python 2.2.""" |
|
|||
109 | i = -1 |
|
|||
110 | for item in obj: |
|
|||
111 | i += 1 |
|
|||
112 | yield i, item |
|
|||
113 |
|
||||
114 | try: |
|
|||
115 | True, False |
|
|||
116 | except NameError: |
|
|||
117 | True, False = 1, 0 |
|
|||
118 |
|
||||
119 |
|
90 | |||
120 | __version__ = '4.5.2' |
|
91 | __version__ = '4.5.2' | |
121 |
|
92 | |||
@@ -814,7 +785,7 b' class Section(dict):' | |||||
814 | >>> c2 |
|
785 | >>> c2 | |
815 | {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}} |
|
786 | {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}} | |
816 | """ |
|
787 | """ | |
817 | for key, val in indict.items(): |
|
788 | for key, val in indict.iteritems(): | |
818 | if (key in self and isinstance(self[key], dict) and |
|
789 | if (key in self and isinstance(self[key], dict) and | |
819 | isinstance(val, dict)): |
|
790 | isinstance(val, dict)): | |
820 | self[key].merge(val) |
|
791 | self[key].merge(val) | |
@@ -1438,7 +1409,7 b' class ConfigObj(Section):' | |||||
1438 | enc = BOM_LIST[self.encoding.lower()] |
|
1409 | enc = BOM_LIST[self.encoding.lower()] | |
1439 | if enc == 'utf_16': |
|
1410 | if enc == 'utf_16': | |
1440 | # For UTF16 we try big endian and little endian |
|
1411 | # For UTF16 we try big endian and little endian | |
1441 | for BOM, (encoding, final_encoding) in BOMS.items(): |
|
1412 | for BOM, (encoding, final_encoding) in BOMS.iteritems(): | |
1442 | if not final_encoding: |
|
1413 | if not final_encoding: | |
1443 | # skip UTF8 |
|
1414 | # skip UTF8 | |
1444 | continue |
|
1415 | continue | |
@@ -1468,7 +1439,7 b' class ConfigObj(Section):' | |||||
1468 | return self._decode(infile, self.encoding) |
|
1439 | return self._decode(infile, self.encoding) | |
1469 |
|
1440 | |||
1470 | # No encoding specified - so we need to check for UTF8/UTF16 |
|
1441 | # No encoding specified - so we need to check for UTF8/UTF16 | |
1471 | for BOM, (encoding, final_encoding) in BOMS.items(): |
|
1442 | for BOM, (encoding, final_encoding) in BOMS.iteritems(): | |
1472 | if not line.startswith(BOM): |
|
1443 | if not line.startswith(BOM): | |
1473 | continue |
|
1444 | continue | |
1474 | else: |
|
1445 | else: | |
@@ -2481,7 +2452,7 b' def flatten_errors(cfg, res, levels=None, results=None):' | |||||
2481 | if levels: |
|
2452 | if levels: | |
2482 | levels.pop() |
|
2453 | levels.pop() | |
2483 | return results |
|
2454 | return results | |
2484 | for (key, val) in res.items(): |
|
2455 | for (key, val) in res.iteritems(): | |
2485 | if val == True: |
|
2456 | if val == True: | |
2486 | continue |
|
2457 | continue | |
2487 | if isinstance(cfg.get(key), dict): |
|
2458 | if isinstance(cfg.get(key), dict): |
@@ -7,7 +7,7 b" d = path('/home/guido/bin')" | |||||
7 | for f in d.files('*.py'): |
|
7 | for f in d.files('*.py'): | |
8 | f.chmod(0755) |
|
8 | f.chmod(0755) | |
9 |
|
9 | |||
10 |
This module requires Python 2. |
|
10 | This module requires Python 2.5 or later. | |
11 |
|
11 | |||
12 |
|
12 | |||
13 | URL: http://www.jorendorff.com/articles/python/path |
|
13 | URL: http://www.jorendorff.com/articles/python/path | |
@@ -30,9 +30,7 b' Date: 9 Mar 2007' | |||||
30 | from __future__ import generators |
|
30 | from __future__ import generators | |
31 |
|
31 | |||
32 | import sys, warnings, os, fnmatch, glob, shutil, codecs |
|
32 | import sys, warnings, os, fnmatch, glob, shutil, codecs | |
33 | # deprecated in python 2.6 |
|
33 | from hashlib import md5 | |
34 | warnings.filterwarnings('ignore', r'.*md5.*') |
|
|||
35 | import md5 |
|
|||
36 |
|
34 | |||
37 | __version__ = '2.2' |
|
35 | __version__ = '2.2' | |
38 | __all__ = ['path'] |
|
36 | __all__ = ['path'] | |
@@ -49,38 +47,11 b' else:' | |||||
49 | except ImportError: |
|
47 | except ImportError: | |
50 | pwd = None |
|
48 | pwd = None | |
51 |
|
49 | |||
52 | # Pre-2.3 support. Are unicode filenames supported? |
|
|||
53 | _base = str |
|
|||
54 | _getcwd = os.getcwd |
|
|||
55 | try: |
|
|||
56 | if os.path.supports_unicode_filenames: |
|
|||
57 | _base = unicode |
|
|||
58 | _getcwd = os.getcwdu |
|
|||
59 | except AttributeError: |
|
|||
60 | pass |
|
|||
61 |
|
||||
62 | # Pre-2.3 workaround for booleans |
|
|||
63 | try: |
|
|||
64 | True, False |
|
|||
65 | except NameError: |
|
|||
66 | True, False = 1, 0 |
|
|||
67 |
|
||||
68 | # Pre-2.3 workaround for basestring. |
|
|||
69 | try: |
|
|||
70 | basestring |
|
|||
71 | except NameError: |
|
|||
72 | basestring = (str, unicode) |
|
|||
73 |
|
||||
74 | # Universal newline support |
|
|||
75 | _textmode = 'r' |
|
|||
76 | if hasattr(file, 'newlines'): |
|
|||
77 | _textmode = 'U' |
|
|||
78 |
|
||||
79 |
|
50 | |||
80 | class TreeWalkWarning(Warning): |
|
51 | class TreeWalkWarning(Warning): | |
81 | pass |
|
52 | pass | |
82 |
|
53 | |||
83 |
class path( |
|
54 | class path(unicode): | |
84 | """ Represents a filesystem path. |
|
55 | """ Represents a filesystem path. | |
85 |
|
56 | |||
86 | For documentation on individual methods, consult their |
|
57 | For documentation on individual methods, consult their | |
@@ -90,12 +61,12 b' class path(_base):' | |||||
90 | # --- Special Python methods. |
|
61 | # --- Special Python methods. | |
91 |
|
62 | |||
92 | def __repr__(self): |
|
63 | def __repr__(self): | |
93 |
return 'path(%s)' % |
|
64 | return 'path(%s)' % unicode.__repr__(self) | |
94 |
|
65 | |||
95 | # Adding a path and a string yields a path. |
|
66 | # Adding a path and a string yields a path. | |
96 | def __add__(self, more): |
|
67 | def __add__(self, more): | |
97 | try: |
|
68 | try: | |
98 |
resultStr = |
|
69 | resultStr = unicode.__add__(self, more) | |
99 | except TypeError: #Python bug |
|
70 | except TypeError: #Python bug | |
100 | resultStr = NotImplemented |
|
71 | resultStr = NotImplemented | |
101 | if resultStr is NotImplemented: |
|
72 | if resultStr is NotImplemented: | |
@@ -122,7 +93,7 b' class path(_base):' | |||||
122 |
|
93 | |||
123 | def getcwd(cls): |
|
94 | def getcwd(cls): | |
124 | """ Return the current working directory as a path object. """ |
|
95 | """ Return the current working directory as a path object. """ | |
125 |
return cls( |
|
96 | return cls(os.getcwdu()) | |
126 | getcwd = classmethod(getcwd) |
|
97 | getcwd = classmethod(getcwd) | |
127 |
|
98 | |||
128 |
|
99 | |||
@@ -152,7 +123,7 b' class path(_base):' | |||||
152 | return base |
|
123 | return base | |
153 |
|
124 | |||
154 | def _get_ext(self): |
|
125 | def _get_ext(self): | |
155 |
f, ext = os.path.splitext( |
|
126 | f, ext = os.path.splitext(unicode(self)) | |
156 | return ext |
|
127 | return ext | |
157 |
|
128 | |||
158 | def _get_drive(self): |
|
129 | def _get_drive(self): | |
@@ -513,14 +484,14 b' class path(_base):' | |||||
513 | of all the files users have in their bin directories. |
|
484 | of all the files users have in their bin directories. | |
514 | """ |
|
485 | """ | |
515 | cls = self.__class__ |
|
486 | cls = self.__class__ | |
516 |
return [cls(s) for s in glob.glob( |
|
487 | return [cls(s) for s in glob.glob(unicode(self / pattern))] | |
517 |
|
488 | |||
518 |
|
489 | |||
519 | # --- Reading or writing an entire file at once. |
|
490 | # --- Reading or writing an entire file at once. | |
520 |
|
491 | |||
521 | def open(self, mode='r'): |
|
492 | def open(self, mode='r'): | |
522 | """ Open this file. Return a file object. """ |
|
493 | """ Open this file. Return a file object. """ | |
523 |
return |
|
494 | return open(self, mode) | |
524 |
|
495 | |||
525 | def bytes(self): |
|
496 | def bytes(self): | |
526 | """ Open this file, read all bytes, return them as a string. """ |
|
497 | """ Open this file, read all bytes, return them as a string. """ | |
@@ -563,7 +534,7 b' class path(_base):' | |||||
563 | """ |
|
534 | """ | |
564 | if encoding is None: |
|
535 | if encoding is None: | |
565 | # 8-bit |
|
536 | # 8-bit | |
566 |
f = self.open( |
|
537 | f = self.open('U') | |
567 | try: |
|
538 | try: | |
568 | return f.read() |
|
539 | return f.read() | |
569 | finally: |
|
540 | finally: | |
@@ -690,7 +661,7 b' class path(_base):' | |||||
690 | This uses 'U' mode in Python 2.3 and later. |
|
661 | This uses 'U' mode in Python 2.3 and later. | |
691 | """ |
|
662 | """ | |
692 | if encoding is None and retain: |
|
663 | if encoding is None and retain: | |
693 |
f = self.open( |
|
664 | f = self.open('U') | |
694 | try: |
|
665 | try: | |
695 | return f.readlines() |
|
666 | return f.readlines() | |
696 | finally: |
|
667 | finally: | |
@@ -770,7 +741,7 b' class path(_base):' | |||||
770 | """ |
|
741 | """ | |
771 | f = self.open('rb') |
|
742 | f = self.open('rb') | |
772 | try: |
|
743 | try: | |
773 |
m = md5 |
|
744 | m = md5() | |
774 | while True: |
|
745 | while True: | |
775 | d = f.read(8192) |
|
746 | d = f.read(8192) | |
776 | if not d: |
|
747 | if not d: |
@@ -101,7 +101,8 b'' | |||||
101 | Portions (c) 2009 by Robert Kern. |
|
101 | Portions (c) 2009 by Robert Kern. | |
102 | :license: BSD License. |
|
102 | :license: BSD License. | |
103 | """ |
|
103 | """ | |
104 | import __future__ |
|
104 | from __future__ import with_statement | |
|
105 | from contextlib import contextmanager | |||
105 | import sys |
|
106 | import sys | |
106 | import types |
|
107 | import types | |
107 | import re |
|
108 | import re | |
@@ -138,12 +139,6 b" def pprint(obj, verbose=False, max_width=79, newline='\\n'):" | |||||
138 | sys.stdout.write(newline) |
|
139 | sys.stdout.write(newline) | |
139 | sys.stdout.flush() |
|
140 | sys.stdout.flush() | |
140 |
|
141 | |||
141 |
|
||||
142 | # add python2.5 context managers if we have the with statement feature |
|
|||
143 | if hasattr(__future__, 'with_statement'): exec ''' |
|
|||
144 | from __future__ import with_statement |
|
|||
145 | from contextlib import contextmanager |
|
|||
146 |
|
||||
147 | class _PrettyPrinterBase(object): |
|
142 | class _PrettyPrinterBase(object): | |
148 |
|
143 | |||
149 | @contextmanager |
|
144 | @contextmanager | |
@@ -164,16 +159,6 b' class _PrettyPrinterBase(object):' | |||||
164 | yield |
|
159 | yield | |
165 | finally: |
|
160 | finally: | |
166 | self.end_group(indent, close) |
|
161 | self.end_group(indent, close) | |
167 | ''' |
|
|||
168 | else: |
|
|||
169 | class _PrettyPrinterBase(object): |
|
|||
170 |
|
||||
171 | def _unsupported(self, *a, **kw): |
|
|||
172 | """unsupported operation""" |
|
|||
173 | raise RuntimeError('not available in this python version') |
|
|||
174 | group = indent = _unsupported |
|
|||
175 | del _unsupported |
|
|||
176 |
|
||||
177 |
|
162 | |||
178 | class PrettyPrinter(_PrettyPrinterBase): |
|
163 | class PrettyPrinter(_PrettyPrinterBase): | |
179 | """ |
|
164 | """ |
@@ -1,3 +1,4 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
1 | # module pyparsing.py |
|
2 | # module pyparsing.py | |
2 | # |
|
3 | # | |
3 | # Copyright (c) 2003-2009 Paul T. McGuire |
|
4 | # Copyright (c) 2003-2009 Paul T. McGuire | |
@@ -400,7 +401,7 b' class ParseResults(object):' | |||||
400 |
|
401 | |||
401 | def values( self ): |
|
402 | def values( self ): | |
402 | """Returns all named result values.""" |
|
403 | """Returns all named result values.""" | |
403 | return [ v[-1][0] for v in self.__tokdict.values() ] |
|
404 | return [ v[-1][0] for v in self.__tokdict.itervalues() ] | |
404 |
|
405 | |||
405 | def __getattr__( self, name ): |
|
406 | def __getattr__( self, name ): | |
406 | if name not in self.__slots__: |
|
407 | if name not in self.__slots__: | |
@@ -422,7 +423,7 b' class ParseResults(object):' | |||||
422 | if other.__tokdict: |
|
423 | if other.__tokdict: | |
423 | offset = len(self.__toklist) |
|
424 | offset = len(self.__toklist) | |
424 | addoffset = ( lambda a: (a<0 and offset) or (a+offset) ) |
|
425 | addoffset = ( lambda a: (a<0 and offset) or (a+offset) ) | |
425 | otheritems = other.__tokdict.items() |
|
426 | otheritems = other.__tokdict.iteritems() | |
426 | otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) ) |
|
427 | otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) ) | |
427 | for (k,vlist) in otheritems for v in vlist] |
|
428 | for (k,vlist) in otheritems for v in vlist] | |
428 | for k,v in otherdictitems: |
|
429 | for k,v in otherdictitems: | |
@@ -488,7 +489,7 b' class ParseResults(object):' | |||||
488 | """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.""" |
|
489 | """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.""" | |
489 | nl = "\n" |
|
490 | nl = "\n" | |
490 | out = [] |
|
491 | out = [] | |
491 |
namedItems = dict( |
|
492 | namedItems = dict([(v[1],k) for (k,vlist) in self.__tokdict.iteritems() | |
492 | for v in vlist ] ) |
|
493 | for v in vlist ] ) | |
493 | nextLevelIndent = indent + " " |
|
494 | nextLevelIndent = indent + " " | |
494 |
|
495 | |||
@@ -545,7 +546,7 b' class ParseResults(object):' | |||||
545 | return "".join(out) |
|
546 | return "".join(out) | |
546 |
|
547 | |||
547 | def __lookup(self,sub): |
|
548 | def __lookup(self,sub): | |
548 | for k,vlist in self.__tokdict.items(): |
|
549 | for k,vlist in self.__tokdict.iteritems(): | |
549 | for v,loc in vlist: |
|
550 | for v,loc in vlist: | |
550 | if sub is v: |
|
551 | if sub is v: | |
551 | return k |
|
552 | return k | |
@@ -2563,7 +2564,7 b' class Each(ParseExpression):' | |||||
2563 | tmp += ParseResults(r[k]) |
|
2564 | tmp += ParseResults(r[k]) | |
2564 | dups[k] = tmp |
|
2565 | dups[k] = tmp | |
2565 | finalResults += ParseResults(r) |
|
2566 | finalResults += ParseResults(r) | |
2566 | for k,v in dups.items(): |
|
2567 | for k,v in dups.iteritems(): | |
2567 | finalResults[k] = v |
|
2568 | finalResults[k] = v | |
2568 | return loc, finalResults |
|
2569 | return loc, finalResults | |
2569 |
|
2570 | |||
@@ -3442,7 +3443,7 b' def withAttribute(*args,**attrDict):' | |||||
3442 | if args: |
|
3443 | if args: | |
3443 | attrs = args[:] |
|
3444 | attrs = args[:] | |
3444 | else: |
|
3445 | else: | |
3445 | attrs = attrDict.items() |
|
3446 | attrs = attrDict.iteritems() | |
3446 | attrs = [(k,v) for k,v in attrs] |
|
3447 | attrs = [(k,v) for k,v in attrs] | |
3447 | def pa(s,l,tokens): |
|
3448 | def pa(s,l,tokens): | |
3448 | for attrName,attrValue in attrs: |
|
3449 | for attrName,attrValue in attrs: |
@@ -617,7 +617,7 b' class WindowsHPCLauncher(BaseLauncher):' | |||||
617 | # Twisted will raise DeprecationWarnings if we try to pass unicode to this |
|
617 | # Twisted will raise DeprecationWarnings if we try to pass unicode to this | |
618 | output = yield getProcessOutput(str(self.job_cmd), |
|
618 | output = yield getProcessOutput(str(self.job_cmd), | |
619 | [str(a) for a in args], |
|
619 | [str(a) for a in args], | |
620 | env=dict((str(k),str(v)) for k,v in os.environ.items()), |
|
620 | env=dict((str(k),str(v)) for k,v in os.environ.iteritems()), | |
621 | path=self.work_dir |
|
621 | path=self.work_dir | |
622 | ) |
|
622 | ) | |
623 | except: |
|
623 | except: |
@@ -59,7 +59,7 b' class PendingDeferredManagerTest(DeferredTestCase):' | |||||
59 | did = self.pdm.save_pending_deferred(d) |
|
59 | did = self.pdm.save_pending_deferred(d) | |
60 | dDict[did] = d |
|
60 | dDict[did] = d | |
61 | # Make sure they are begin saved |
|
61 | # Make sure they are begin saved | |
62 | for k in dDict.keys(): |
|
62 | for k in dDict.iterkeys(): | |
63 | self.assert_(self.pdm.quick_has_id(k)) |
|
63 | self.assert_(self.pdm.quick_has_id(k)) | |
64 | # Get the pending deferred (block=True), then callback with 'foo' and compare |
|
64 | # Get the pending deferred (block=True), then callback with 'foo' and compare | |
65 | for did in dDict.keys()[0:5]: |
|
65 | for did in dDict.keys()[0:5]: |
@@ -212,7 +212,7 b' class WinHPCTask(Configurable):' | |||||
212 |
|
212 | |||
213 | def get_env_vars(self): |
|
213 | def get_env_vars(self): | |
214 | env_vars = ET.Element('EnvironmentVariables') |
|
214 | env_vars = ET.Element('EnvironmentVariables') | |
215 | for k, v in self.environment_variables.items(): |
|
215 | for k, v in self.environment_variables.iteritems(): | |
216 | variable = ET.SubElement(env_vars, "Variable") |
|
216 | variable = ET.SubElement(env_vars, "Variable") | |
217 | name = ET.SubElement(variable, "Name") |
|
217 | name = ET.SubElement(variable, "Name") | |
218 | name.text = k |
|
218 | name.text = k |
@@ -22,10 +22,15 b' def import_item(name):' | |||||
22 | """Import and return bar given the string foo.bar.""" |
|
22 | """Import and return bar given the string foo.bar.""" | |
23 | package = '.'.join(name.split('.')[0:-1]) |
|
23 | package = '.'.join(name.split('.')[0:-1]) | |
24 | obj = name.split('.')[-1] |
|
24 | obj = name.split('.')[-1] | |
25 | execString = 'from %s import %s' % (package, obj) |
|
25 | # execString = 'from %s import %s' % (package, obj) | |
26 | try: |
|
26 | # try: | |
27 | exec execString |
|
27 | # exec execString | |
28 | except SyntaxError: |
|
28 | # except SyntaxError: | |
29 | raise ImportError("Invalid class specification: %s" % name) |
|
29 | # raise ImportError("Invalid class specification: %s" % name) | |
30 | exec 'temp = %s' % obj |
|
30 | # exec 'temp = %s' % obj | |
31 | return temp |
|
31 | # return temp | |
|
32 | if package: | |||
|
33 | module = __import__(package,fromlist=[obj]) | |||
|
34 | return module.__dict__[obj] | |||
|
35 | else: | |||
|
36 | return __import__(obj) |
@@ -56,19 +56,7 b' from types import (' | |||||
56 | InstanceType, ClassType, FunctionType, |
|
56 | InstanceType, ClassType, FunctionType, | |
57 | ListType, TupleType |
|
57 | ListType, TupleType | |
58 | ) |
|
58 | ) | |
59 |
|
59 | from .importstring import import_item | ||
60 | def import_item(name): |
|
|||
61 | """Import and return bar given the string foo.bar.""" |
|
|||
62 | package = '.'.join(name.split('.')[0:-1]) |
|
|||
63 | obj = name.split('.')[-1] |
|
|||
64 | execString = 'from %s import %s' % (package, obj) |
|
|||
65 | try: |
|
|||
66 | exec execString |
|
|||
67 | except SyntaxError: |
|
|||
68 | raise ImportError("Invalid class specification: %s" % name) |
|
|||
69 | exec 'temp = %s' % obj |
|
|||
70 | return temp |
|
|||
71 |
|
||||
72 |
|
60 | |||
73 | ClassTypes = (ClassType, type) |
|
61 | ClassTypes = (ClassType, type) | |
74 |
|
62 |
@@ -11,7 +11,7 b' try:' | |||||
11 | except ImportError: |
|
11 | except ImportError: | |
12 | from path import path |
|
12 | from path import path | |
13 |
|
13 | |||
14 |
import |
|
14 | import hashlib, pickle | |
15 |
|
15 | |||
16 | def showdiff(old,new): |
|
16 | def showdiff(old,new): | |
17 | import difflib |
|
17 | import difflib | |
@@ -59,23 +59,23 b' def upgrade_dir(srcdir, tgtdir):' | |||||
59 | pr("Creating %s" % str(tgt)) |
|
59 | pr("Creating %s" % str(tgt)) | |
60 |
|
60 | |||
61 | tgt.write_text(src.text()) |
|
61 | tgt.write_text(src.text()) | |
62 |
rpt[str(tgt)] = md5 |
|
62 | rpt[str(tgt)] = hashlib.md5(tgt.text()).hexdigest() | |
63 | else: |
|
63 | else: | |
64 | cont = tgt.text() |
|
64 | cont = tgt.text() | |
65 | sum = rpt.get(str(tgt), None) |
|
65 | sum = rpt.get(str(tgt), None) | |
66 | #print sum |
|
66 | #print sum | |
67 |
if sum and md5 |
|
67 | if sum and hashlib.md5(cont).hexdigest() == sum: | |
68 | pr("%s: Unedited, installing new version" % tgt) |
|
68 | pr("%s: Unedited, installing new version" % tgt) | |
69 | tgt.write_text(src.text()) |
|
69 | tgt.write_text(src.text()) | |
70 |
rpt[str(tgt)] = md5 |
|
70 | rpt[str(tgt)] = hashlib.md5(tgt.text()).hexdigest() | |
71 | else: |
|
71 | else: | |
72 | pr(' == Modified, skipping %s, diffs below == ' % tgt) |
|
72 | pr(' == Modified, skipping %s, diffs below == ' % tgt) | |
73 |
#rpt[str(tgt)] = md5 |
|
73 | #rpt[str(tgt)] = hashlib.md5(tgt.bytes()).hexdigest() | |
74 | real = showdiff(tgt,src) |
|
74 | real = showdiff(tgt,src) | |
75 | pr('') # empty line |
|
75 | pr('') # empty line | |
76 | if not real: |
|
76 | if not real: | |
77 | pr("(Ok, it was identical, only upgrading checksum)") |
|
77 | pr("(Ok, it was identical, only upgrading checksum)") | |
78 |
rpt[str(tgt)] = md5 |
|
78 | rpt[str(tgt)] = hashlib.md5(tgt.text()).hexdigest() | |
79 | else: |
|
79 | else: | |
80 | modded.append(tgt) |
|
80 | modded.append(tgt) | |
81 |
|
81 |
General Comments 0
You need to be logged in to leave comments.
Login now