Show More
@@ -1,154 +1,170 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Tests for IPython.utils.text""" |
|
2 | """Tests for IPython.utils.text""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2011 The IPython Development Team |
|
5 | # Copyright (C) 2011 The IPython Development Team | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | # Distributed under the terms of the BSD License. The full license is in | |
8 | # the file COPYING, distributed as part of this software. |
|
8 | # the file COPYING, distributed as part of this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | import os |
|
15 | import os | |
16 | import math |
|
16 | import math | |
17 | import random |
|
17 | import random | |
18 |
|
18 | |||
19 | import nose.tools as nt |
|
19 | import nose.tools as nt | |
20 |
|
20 | |||
21 | from nose import with_setup |
|
21 | from nose import with_setup | |
22 |
|
22 | |||
23 | from IPython.testing import decorators as dec |
|
23 | from IPython.testing import decorators as dec | |
24 | from IPython.utils import text |
|
24 | from IPython.utils import text | |
25 |
|
25 | |||
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 | # Globals |
|
27 | # Globals | |
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 |
|
29 | |||
30 | def test_columnize(): |
|
30 | def test_columnize(): | |
31 | """Basic columnize tests.""" |
|
31 | """Basic columnize tests.""" | |
32 | size = 5 |
|
32 | size = 5 | |
33 | items = [l*size for l in 'abc'] |
|
33 | items = [l*size for l in 'abc'] | |
34 | out = text.columnize(items, displaywidth=80) |
|
34 | out = text.columnize(items, displaywidth=80) | |
35 | nt.assert_equals(out, 'aaaaa bbbbb ccccc\n') |
|
35 | nt.assert_equals(out, 'aaaaa bbbbb ccccc\n') | |
36 | out = text.columnize(items, displaywidth=12) |
|
36 | out = text.columnize(items, displaywidth=12) | |
37 | nt.assert_equals(out, 'aaaaa ccccc\nbbbbb\n') |
|
37 | nt.assert_equals(out, 'aaaaa ccccc\nbbbbb\n') | |
38 | out = text.columnize(items, displaywidth=10) |
|
38 | out = text.columnize(items, displaywidth=10) | |
39 | nt.assert_equals(out, 'aaaaa\nbbbbb\nccccc\n') |
|
39 | nt.assert_equals(out, 'aaaaa\nbbbbb\nccccc\n') | |
40 |
|
40 | |||
41 | def test_columnize_random(): |
|
41 | def test_columnize_random(): | |
42 | """Test with random input to hopfully catch edge case """ |
|
42 | """Test with random input to hopfully catch edge case """ | |
43 | for nitems in [random.randint(2,70) for i in range(2,20)]: |
|
43 | for nitems in [random.randint(2,70) for i in range(2,20)]: | |
44 | displaywidth = random.randint(20,200) |
|
44 | displaywidth = random.randint(20,200) | |
45 | rand_len = [random.randint(2,displaywidth) for i in range(nitems)] |
|
45 | rand_len = [random.randint(2,displaywidth) for i in range(nitems)] | |
46 | items = ['x'*l for l in rand_len] |
|
46 | items = ['x'*l for l in rand_len] | |
47 | out = text.columnize(items, displaywidth=displaywidth) |
|
47 | out = text.columnize(items, displaywidth=displaywidth) | |
48 | longer_line = max([len(x) for x in out.split('\n')]) |
|
48 | longer_line = max([len(x) for x in out.split('\n')]) | |
49 | longer_element = max(rand_len) |
|
49 | longer_element = max(rand_len) | |
50 | if longer_line > displaywidth: |
|
50 | if longer_line > displaywidth: | |
51 | print "Columnize displayed something lager than displaywidth : %s " % longer_line |
|
51 | print "Columnize displayed something lager than displaywidth : %s " % longer_line | |
52 | print "longer element : %s " % longer_element |
|
52 | print "longer element : %s " % longer_element | |
53 | print "displaywidth : %s " % displaywidth |
|
53 | print "displaywidth : %s " % displaywidth | |
54 | print "number of element : %s " % nitems |
|
54 | print "number of element : %s " % nitems | |
55 | print "size of each element :\n %s" % rand_len |
|
55 | print "size of each element :\n %s" % rand_len | |
56 | assert False |
|
56 | assert False | |
57 |
|
57 | |||
58 | def test_columnize_medium(): |
|
58 | def test_columnize_medium(): | |
59 | """Test with inputs than shouldn't be wider tahn 80 """ |
|
59 | """Test with inputs than shouldn't be wider tahn 80 """ | |
60 | size = 40 |
|
60 | size = 40 | |
61 | items = [l*size for l in 'abc'] |
|
61 | items = [l*size for l in 'abc'] | |
62 | out = text.columnize(items, displaywidth=80) |
|
62 | out = text.columnize(items, displaywidth=80) | |
63 | nt.assert_equals(out, '\n'.join(items+[''])) |
|
63 | nt.assert_equals(out, '\n'.join(items+[''])) | |
64 |
|
64 | |||
65 | def test_columnize_long(): |
|
65 | def test_columnize_long(): | |
66 | """Test columnize with inputs longer than the display window""" |
|
66 | """Test columnize with inputs longer than the display window""" | |
67 | size = 11 |
|
67 | size = 11 | |
68 | items = [l*size for l in 'abc'] |
|
68 | items = [l*size for l in 'abc'] | |
69 | out = text.columnize(items, displaywidth=size-1) |
|
69 | out = text.columnize(items, displaywidth=size-1) | |
70 | nt.assert_equals(out, '\n'.join(items+[''])) |
|
70 | nt.assert_equals(out, '\n'.join(items+[''])) | |
71 |
|
71 | |||
72 | def eval_formatter_check(f): |
|
72 | def eval_formatter_check(f): | |
73 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os, u=u"cafΓ©", b="cafΓ©") |
|
73 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os, u=u"cafΓ©", b="cafΓ©") | |
74 | s = f.format("{n} {n//4} {stuff.split()[0]}", **ns) |
|
74 | s = f.format("{n} {n//4} {stuff.split()[0]}", **ns) | |
75 | nt.assert_equals(s, "12 3 hello") |
|
75 | nt.assert_equals(s, "12 3 hello") | |
76 | s = f.format(' '.join(['{n//%i}'%i for i in range(1,8)]), **ns) |
|
76 | s = f.format(' '.join(['{n//%i}'%i for i in range(1,8)]), **ns) | |
77 | nt.assert_equals(s, "12 6 4 3 2 2 1") |
|
77 | nt.assert_equals(s, "12 6 4 3 2 2 1") | |
78 | s = f.format('{[n//i for i in range(1,8)]}', **ns) |
|
78 | s = f.format('{[n//i for i in range(1,8)]}', **ns) | |
79 | nt.assert_equals(s, "[12, 6, 4, 3, 2, 2, 1]") |
|
79 | nt.assert_equals(s, "[12, 6, 4, 3, 2, 2, 1]") | |
80 | s = f.format("{stuff!s}", **ns) |
|
80 | s = f.format("{stuff!s}", **ns) | |
81 | nt.assert_equals(s, ns['stuff']) |
|
81 | nt.assert_equals(s, ns['stuff']) | |
82 | s = f.format("{stuff!r}", **ns) |
|
82 | s = f.format("{stuff!r}", **ns) | |
83 | nt.assert_equals(s, repr(ns['stuff'])) |
|
83 | nt.assert_equals(s, repr(ns['stuff'])) | |
84 |
|
84 | |||
85 | # Check with unicode: |
|
85 | # Check with unicode: | |
86 | s = f.format("{u}", **ns) |
|
86 | s = f.format("{u}", **ns) | |
87 | nt.assert_equals(s, ns['u']) |
|
87 | nt.assert_equals(s, ns['u']) | |
88 | # This decodes in a platform dependent manner, but it shouldn't error out |
|
88 | # This decodes in a platform dependent manner, but it shouldn't error out | |
89 | s = f.format("{b}", **ns) |
|
89 | s = f.format("{b}", **ns) | |
90 |
|
90 | |||
91 | nt.assert_raises(NameError, f.format, '{dne}', **ns) |
|
91 | nt.assert_raises(NameError, f.format, '{dne}', **ns) | |
92 |
|
92 | |||
93 | def eval_formatter_slicing_check(f): |
|
93 | def eval_formatter_slicing_check(f): | |
94 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os) |
|
94 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os) | |
95 | s = f.format(" {stuff.split()[:]} ", **ns) |
|
95 | s = f.format(" {stuff.split()[:]} ", **ns) | |
96 | nt.assert_equals(s, " ['hello', 'there'] ") |
|
96 | nt.assert_equals(s, " ['hello', 'there'] ") | |
97 | s = f.format(" {stuff.split()[::-1]} ", **ns) |
|
97 | s = f.format(" {stuff.split()[::-1]} ", **ns) | |
98 | nt.assert_equals(s, " ['there', 'hello'] ") |
|
98 | nt.assert_equals(s, " ['there', 'hello'] ") | |
99 | s = f.format("{stuff[::2]}", **ns) |
|
99 | s = f.format("{stuff[::2]}", **ns) | |
100 | nt.assert_equals(s, ns['stuff'][::2]) |
|
100 | nt.assert_equals(s, ns['stuff'][::2]) | |
101 |
|
101 | |||
102 | nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns) |
|
102 | nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns) | |
103 |
|
103 | |||
104 | def eval_formatter_no_slicing_check(f): |
|
104 | def eval_formatter_no_slicing_check(f): | |
105 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os) |
|
105 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os) | |
106 |
|
106 | |||
107 | s = f.format('{n:x} {pi**2:+f}', **ns) |
|
107 | s = f.format('{n:x} {pi**2:+f}', **ns) | |
108 | nt.assert_equals(s, "c +9.869604") |
|
108 | nt.assert_equals(s, "c +9.869604") | |
109 |
|
109 | |||
110 | s = f.format('{stuff[slice(1,4)]}', **ns) |
|
110 | s = f.format('{stuff[slice(1,4)]}', **ns) | |
111 | nt.assert_equals(s, 'ell') |
|
111 | nt.assert_equals(s, 'ell') | |
112 |
|
112 | |||
113 | nt.assert_raises(SyntaxError, f.format, "{a[:]}") |
|
113 | nt.assert_raises(SyntaxError, f.format, "{a[:]}") | |
114 |
|
114 | |||
115 | def test_eval_formatter(): |
|
115 | def test_eval_formatter(): | |
116 | f = text.EvalFormatter() |
|
116 | f = text.EvalFormatter() | |
117 | eval_formatter_check(f) |
|
117 | eval_formatter_check(f) | |
118 | eval_formatter_no_slicing_check(f) |
|
118 | eval_formatter_no_slicing_check(f) | |
119 |
|
119 | |||
120 | def test_full_eval_formatter(): |
|
120 | def test_full_eval_formatter(): | |
121 | f = text.FullEvalFormatter() |
|
121 | f = text.FullEvalFormatter() | |
122 | eval_formatter_check(f) |
|
122 | eval_formatter_check(f) | |
123 | eval_formatter_slicing_check(f) |
|
123 | eval_formatter_slicing_check(f) | |
124 |
|
124 | |||
125 | def test_dollar_formatter(): |
|
125 | def test_dollar_formatter(): | |
126 | f = text.DollarFormatter() |
|
126 | f = text.DollarFormatter() | |
127 | eval_formatter_check(f) |
|
127 | eval_formatter_check(f) | |
128 | eval_formatter_slicing_check(f) |
|
128 | eval_formatter_slicing_check(f) | |
129 |
|
129 | |||
130 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os) |
|
130 | ns = dict(n=12, pi=math.pi, stuff='hello there', os=os) | |
131 | s = f.format("$n", **ns) |
|
131 | s = f.format("$n", **ns) | |
132 | nt.assert_equals(s, "12") |
|
132 | nt.assert_equals(s, "12") | |
133 | s = f.format("$n.real", **ns) |
|
133 | s = f.format("$n.real", **ns) | |
134 | nt.assert_equals(s, "12") |
|
134 | nt.assert_equals(s, "12") | |
135 | s = f.format("$n/{stuff[:5]}", **ns) |
|
135 | s = f.format("$n/{stuff[:5]}", **ns) | |
136 | nt.assert_equals(s, "12/hello") |
|
136 | nt.assert_equals(s, "12/hello") | |
137 | s = f.format("$n $$HOME", **ns) |
|
137 | s = f.format("$n $$HOME", **ns) | |
138 | nt.assert_equals(s, "12 $HOME") |
|
138 | nt.assert_equals(s, "12 $HOME") | |
139 | s = f.format("${foo}", foo="HOME") |
|
139 | s = f.format("${foo}", foo="HOME") | |
140 | nt.assert_equals(s, "$HOME") |
|
140 | nt.assert_equals(s, "$HOME") | |
141 |
|
141 | |||
142 |
|
142 | |||
|
143 | def test_long_substr(): | |||
|
144 | data = ['hi'] | |||
|
145 | nt.assert_equals(text.long_substr(data), 'hi') | |||
|
146 | ||||
|
147 | ||||
|
148 | def test_long_substr2(): | |||
|
149 | data = ['abc', 'abd', 'abf', 'ab'] | |||
|
150 | nt.assert_equals(text.long_substr(data), 'ab') | |||
|
151 | ||||
|
152 | ||||
143 | def test_strip_email(): |
|
153 | def test_strip_email(): | |
144 | src = """\ |
|
154 | src = """\ | |
145 | >> >>> def f(x): |
|
155 | >> >>> def f(x): | |
146 | >> ... return x+1 |
|
156 | >> ... return x+1 | |
147 | >> ... |
|
157 | >> ... | |
148 | >> >>> zz = f(2.5)""" |
|
158 | >> >>> zz = f(2.5)""" | |
149 | cln = """\ |
|
159 | cln = """\ | |
150 | >>> def f(x): |
|
160 | >>> def f(x): | |
151 | ... return x+1 |
|
161 | ... return x+1 | |
152 | ... |
|
162 | ... | |
153 | >>> zz = f(2.5)""" |
|
163 | >>> zz = f(2.5)""" | |
154 | nt.assert_equals(text.strip_email_quotes(src), cln) |
|
164 | nt.assert_equals(text.strip_email_quotes(src), cln) | |
|
165 | ||||
|
166 | ||||
|
167 | def test_strip_email2(): | |||
|
168 | src = '> > > list()' | |||
|
169 | cln = 'list()' | |||
|
170 | nt.assert_equals(text.strip_email_quotes(src), cln) |
@@ -1,807 +1,809 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Utilities for working with strings and text. |
|
3 | Utilities for working with strings and text. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
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 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | import __main__ |
|
17 | import __main__ | |
18 |
|
18 | |||
19 | import os |
|
19 | import os | |
20 | import re |
|
20 | import re | |
21 | import shutil |
|
21 | import shutil | |
22 | import sys |
|
22 | import sys | |
23 | import textwrap |
|
23 | import textwrap | |
24 | from string import Formatter |
|
24 | from string import Formatter | |
25 |
|
25 | |||
26 | from IPython.external.path import path |
|
26 | from IPython.external.path import path | |
27 | from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest |
|
27 | from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest | |
28 | from IPython.utils import py3compat |
|
28 | from IPython.utils import py3compat | |
29 | from IPython.utils.io import nlprint |
|
29 | from IPython.utils.io import nlprint | |
30 | from IPython.utils.data import flatten |
|
30 | from IPython.utils.data import flatten | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Code |
|
33 | # Code | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | def unquote_ends(istr): |
|
36 | def unquote_ends(istr): | |
37 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
37 | """Remove a single pair of quotes from the endpoints of a string.""" | |
38 |
|
38 | |||
39 | if not istr: |
|
39 | if not istr: | |
40 | return istr |
|
40 | return istr | |
41 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
41 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
42 | (istr[0]=='"' and istr[-1]=='"'): |
|
42 | (istr[0]=='"' and istr[-1]=='"'): | |
43 | return istr[1:-1] |
|
43 | return istr[1:-1] | |
44 | else: |
|
44 | else: | |
45 | return istr |
|
45 | return istr | |
46 |
|
46 | |||
47 |
|
47 | |||
48 | class LSString(str): |
|
48 | class LSString(str): | |
49 | """String derivative with a special access attributes. |
|
49 | """String derivative with a special access attributes. | |
50 |
|
50 | |||
51 | These are normal strings, but with the special attributes: |
|
51 | These are normal strings, but with the special attributes: | |
52 |
|
52 | |||
53 | .l (or .list) : value as list (split on newlines). |
|
53 | .l (or .list) : value as list (split on newlines). | |
54 | .n (or .nlstr): original value (the string itself). |
|
54 | .n (or .nlstr): original value (the string itself). | |
55 | .s (or .spstr): value as whitespace-separated string. |
|
55 | .s (or .spstr): value as whitespace-separated string. | |
56 | .p (or .paths): list of path objects |
|
56 | .p (or .paths): list of path objects | |
57 |
|
57 | |||
58 | Any values which require transformations are computed only once and |
|
58 | Any values which require transformations are computed only once and | |
59 | cached. |
|
59 | cached. | |
60 |
|
60 | |||
61 | Such strings are very useful to efficiently interact with the shell, which |
|
61 | Such strings are very useful to efficiently interact with the shell, which | |
62 | typically only understands whitespace-separated options for commands.""" |
|
62 | typically only understands whitespace-separated options for commands.""" | |
63 |
|
63 | |||
64 | def get_list(self): |
|
64 | def get_list(self): | |
65 | try: |
|
65 | try: | |
66 | return self.__list |
|
66 | return self.__list | |
67 | except AttributeError: |
|
67 | except AttributeError: | |
68 | self.__list = self.split('\n') |
|
68 | self.__list = self.split('\n') | |
69 | return self.__list |
|
69 | return self.__list | |
70 |
|
70 | |||
71 | l = list = property(get_list) |
|
71 | l = list = property(get_list) | |
72 |
|
72 | |||
73 | def get_spstr(self): |
|
73 | def get_spstr(self): | |
74 | try: |
|
74 | try: | |
75 | return self.__spstr |
|
75 | return self.__spstr | |
76 | except AttributeError: |
|
76 | except AttributeError: | |
77 | self.__spstr = self.replace('\n',' ') |
|
77 | self.__spstr = self.replace('\n',' ') | |
78 | return self.__spstr |
|
78 | return self.__spstr | |
79 |
|
79 | |||
80 | s = spstr = property(get_spstr) |
|
80 | s = spstr = property(get_spstr) | |
81 |
|
81 | |||
82 | def get_nlstr(self): |
|
82 | def get_nlstr(self): | |
83 | return self |
|
83 | return self | |
84 |
|
84 | |||
85 | n = nlstr = property(get_nlstr) |
|
85 | n = nlstr = property(get_nlstr) | |
86 |
|
86 | |||
87 | def get_paths(self): |
|
87 | def get_paths(self): | |
88 | try: |
|
88 | try: | |
89 | return self.__paths |
|
89 | return self.__paths | |
90 | except AttributeError: |
|
90 | except AttributeError: | |
91 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
91 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] | |
92 | return self.__paths |
|
92 | return self.__paths | |
93 |
|
93 | |||
94 | p = paths = property(get_paths) |
|
94 | p = paths = property(get_paths) | |
95 |
|
95 | |||
96 | # FIXME: We need to reimplement type specific displayhook and then add this |
|
96 | # FIXME: We need to reimplement type specific displayhook and then add this | |
97 | # back as a custom printer. This should also be moved outside utils into the |
|
97 | # back as a custom printer. This should also be moved outside utils into the | |
98 | # core. |
|
98 | # core. | |
99 |
|
99 | |||
100 | # def print_lsstring(arg): |
|
100 | # def print_lsstring(arg): | |
101 | # """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
101 | # """ Prettier (non-repr-like) and more informative printer for LSString """ | |
102 | # print "LSString (.p, .n, .l, .s available). Value:" |
|
102 | # print "LSString (.p, .n, .l, .s available). Value:" | |
103 | # print arg |
|
103 | # print arg | |
104 | # |
|
104 | # | |
105 | # |
|
105 | # | |
106 | # print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
106 | # print_lsstring = result_display.when_type(LSString)(print_lsstring) | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | class SList(list): |
|
109 | class SList(list): | |
110 | """List derivative with a special access attributes. |
|
110 | """List derivative with a special access attributes. | |
111 |
|
111 | |||
112 | These are normal lists, but with the special attributes: |
|
112 | These are normal lists, but with the special attributes: | |
113 |
|
113 | |||
114 | .l (or .list) : value as list (the list itself). |
|
114 | .l (or .list) : value as list (the list itself). | |
115 | .n (or .nlstr): value as a string, joined on newlines. |
|
115 | .n (or .nlstr): value as a string, joined on newlines. | |
116 | .s (or .spstr): value as a string, joined on spaces. |
|
116 | .s (or .spstr): value as a string, joined on spaces. | |
117 | .p (or .paths): list of path objects |
|
117 | .p (or .paths): list of path objects | |
118 |
|
118 | |||
119 | Any values which require transformations are computed only once and |
|
119 | Any values which require transformations are computed only once and | |
120 | cached.""" |
|
120 | cached.""" | |
121 |
|
121 | |||
122 | def get_list(self): |
|
122 | def get_list(self): | |
123 | return self |
|
123 | return self | |
124 |
|
124 | |||
125 | l = list = property(get_list) |
|
125 | l = list = property(get_list) | |
126 |
|
126 | |||
127 | def get_spstr(self): |
|
127 | def get_spstr(self): | |
128 | try: |
|
128 | try: | |
129 | return self.__spstr |
|
129 | return self.__spstr | |
130 | except AttributeError: |
|
130 | except AttributeError: | |
131 | self.__spstr = ' '.join(self) |
|
131 | self.__spstr = ' '.join(self) | |
132 | return self.__spstr |
|
132 | return self.__spstr | |
133 |
|
133 | |||
134 | s = spstr = property(get_spstr) |
|
134 | s = spstr = property(get_spstr) | |
135 |
|
135 | |||
136 | def get_nlstr(self): |
|
136 | def get_nlstr(self): | |
137 | try: |
|
137 | try: | |
138 | return self.__nlstr |
|
138 | return self.__nlstr | |
139 | except AttributeError: |
|
139 | except AttributeError: | |
140 | self.__nlstr = '\n'.join(self) |
|
140 | self.__nlstr = '\n'.join(self) | |
141 | return self.__nlstr |
|
141 | return self.__nlstr | |
142 |
|
142 | |||
143 | n = nlstr = property(get_nlstr) |
|
143 | n = nlstr = property(get_nlstr) | |
144 |
|
144 | |||
145 | def get_paths(self): |
|
145 | def get_paths(self): | |
146 | try: |
|
146 | try: | |
147 | return self.__paths |
|
147 | return self.__paths | |
148 | except AttributeError: |
|
148 | except AttributeError: | |
149 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
149 | self.__paths = [path(p) for p in self if os.path.exists(p)] | |
150 | return self.__paths |
|
150 | return self.__paths | |
151 |
|
151 | |||
152 | p = paths = property(get_paths) |
|
152 | p = paths = property(get_paths) | |
153 |
|
153 | |||
154 | def grep(self, pattern, prune = False, field = None): |
|
154 | def grep(self, pattern, prune = False, field = None): | |
155 | """ Return all strings matching 'pattern' (a regex or callable) |
|
155 | """ Return all strings matching 'pattern' (a regex or callable) | |
156 |
|
156 | |||
157 | This is case-insensitive. If prune is true, return all items |
|
157 | This is case-insensitive. If prune is true, return all items | |
158 | NOT matching the pattern. |
|
158 | NOT matching the pattern. | |
159 |
|
159 | |||
160 | If field is specified, the match must occur in the specified |
|
160 | If field is specified, the match must occur in the specified | |
161 | whitespace-separated field. |
|
161 | whitespace-separated field. | |
162 |
|
162 | |||
163 | Examples:: |
|
163 | Examples:: | |
164 |
|
164 | |||
165 | a.grep( lambda x: x.startswith('C') ) |
|
165 | a.grep( lambda x: x.startswith('C') ) | |
166 | a.grep('Cha.*log', prune=1) |
|
166 | a.grep('Cha.*log', prune=1) | |
167 | a.grep('chm', field=-1) |
|
167 | a.grep('chm', field=-1) | |
168 | """ |
|
168 | """ | |
169 |
|
169 | |||
170 | def match_target(s): |
|
170 | def match_target(s): | |
171 | if field is None: |
|
171 | if field is None: | |
172 | return s |
|
172 | return s | |
173 | parts = s.split() |
|
173 | parts = s.split() | |
174 | try: |
|
174 | try: | |
175 | tgt = parts[field] |
|
175 | tgt = parts[field] | |
176 | return tgt |
|
176 | return tgt | |
177 | except IndexError: |
|
177 | except IndexError: | |
178 | return "" |
|
178 | return "" | |
179 |
|
179 | |||
180 | if isinstance(pattern, basestring): |
|
180 | if isinstance(pattern, basestring): | |
181 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
|
181 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) | |
182 | else: |
|
182 | else: | |
183 | pred = pattern |
|
183 | pred = pattern | |
184 | if not prune: |
|
184 | if not prune: | |
185 | return SList([el for el in self if pred(match_target(el))]) |
|
185 | return SList([el for el in self if pred(match_target(el))]) | |
186 | else: |
|
186 | else: | |
187 | return SList([el for el in self if not pred(match_target(el))]) |
|
187 | return SList([el for el in self if not pred(match_target(el))]) | |
188 |
|
188 | |||
189 | def fields(self, *fields): |
|
189 | def fields(self, *fields): | |
190 | """ Collect whitespace-separated fields from string list |
|
190 | """ Collect whitespace-separated fields from string list | |
191 |
|
191 | |||
192 | Allows quick awk-like usage of string lists. |
|
192 | Allows quick awk-like usage of string lists. | |
193 |
|
193 | |||
194 | Example data (in var a, created by 'a = !ls -l'):: |
|
194 | Example data (in var a, created by 'a = !ls -l'):: | |
195 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog |
|
195 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog | |
196 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython |
|
196 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython | |
197 |
|
197 | |||
198 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] |
|
198 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] | |
199 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] |
|
199 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] | |
200 | (note the joining by space). |
|
200 | (note the joining by space). | |
201 | a.fields(-1) is ['ChangeLog', 'IPython'] |
|
201 | a.fields(-1) is ['ChangeLog', 'IPython'] | |
202 |
|
202 | |||
203 | IndexErrors are ignored. |
|
203 | IndexErrors are ignored. | |
204 |
|
204 | |||
205 | Without args, fields() just split()'s the strings. |
|
205 | Without args, fields() just split()'s the strings. | |
206 | """ |
|
206 | """ | |
207 | if len(fields) == 0: |
|
207 | if len(fields) == 0: | |
208 | return [el.split() for el in self] |
|
208 | return [el.split() for el in self] | |
209 |
|
209 | |||
210 | res = SList() |
|
210 | res = SList() | |
211 | for el in [f.split() for f in self]: |
|
211 | for el in [f.split() for f in self]: | |
212 | lineparts = [] |
|
212 | lineparts = [] | |
213 |
|
213 | |||
214 | for fd in fields: |
|
214 | for fd in fields: | |
215 | try: |
|
215 | try: | |
216 | lineparts.append(el[fd]) |
|
216 | lineparts.append(el[fd]) | |
217 | except IndexError: |
|
217 | except IndexError: | |
218 | pass |
|
218 | pass | |
219 | if lineparts: |
|
219 | if lineparts: | |
220 | res.append(" ".join(lineparts)) |
|
220 | res.append(" ".join(lineparts)) | |
221 |
|
221 | |||
222 | return res |
|
222 | return res | |
223 |
|
223 | |||
224 | def sort(self,field= None, nums = False): |
|
224 | def sort(self,field= None, nums = False): | |
225 | """ sort by specified fields (see fields()) |
|
225 | """ sort by specified fields (see fields()) | |
226 |
|
226 | |||
227 | Example:: |
|
227 | Example:: | |
228 | a.sort(1, nums = True) |
|
228 | a.sort(1, nums = True) | |
229 |
|
229 | |||
230 | Sorts a by second field, in numerical order (so that 21 > 3) |
|
230 | Sorts a by second field, in numerical order (so that 21 > 3) | |
231 |
|
231 | |||
232 | """ |
|
232 | """ | |
233 |
|
233 | |||
234 | #decorate, sort, undecorate |
|
234 | #decorate, sort, undecorate | |
235 | if field is not None: |
|
235 | if field is not None: | |
236 | dsu = [[SList([line]).fields(field), line] for line in self] |
|
236 | dsu = [[SList([line]).fields(field), line] for line in self] | |
237 | else: |
|
237 | else: | |
238 | dsu = [[line, line] for line in self] |
|
238 | dsu = [[line, line] for line in self] | |
239 | if nums: |
|
239 | if nums: | |
240 | for i in range(len(dsu)): |
|
240 | for i in range(len(dsu)): | |
241 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) |
|
241 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) | |
242 | try: |
|
242 | try: | |
243 | n = int(numstr) |
|
243 | n = int(numstr) | |
244 | except ValueError: |
|
244 | except ValueError: | |
245 | n = 0; |
|
245 | n = 0; | |
246 | dsu[i][0] = n |
|
246 | dsu[i][0] = n | |
247 |
|
247 | |||
248 |
|
248 | |||
249 | dsu.sort() |
|
249 | dsu.sort() | |
250 | return SList([t[1] for t in dsu]) |
|
250 | return SList([t[1] for t in dsu]) | |
251 |
|
251 | |||
252 |
|
252 | |||
253 | # FIXME: We need to reimplement type specific displayhook and then add this |
|
253 | # FIXME: We need to reimplement type specific displayhook and then add this | |
254 | # back as a custom printer. This should also be moved outside utils into the |
|
254 | # back as a custom printer. This should also be moved outside utils into the | |
255 | # core. |
|
255 | # core. | |
256 |
|
256 | |||
257 | # def print_slist(arg): |
|
257 | # def print_slist(arg): | |
258 | # """ Prettier (non-repr-like) and more informative printer for SList """ |
|
258 | # """ Prettier (non-repr-like) and more informative printer for SList """ | |
259 | # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" |
|
259 | # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" | |
260 | # if hasattr(arg, 'hideonce') and arg.hideonce: |
|
260 | # if hasattr(arg, 'hideonce') and arg.hideonce: | |
261 | # arg.hideonce = False |
|
261 | # arg.hideonce = False | |
262 | # return |
|
262 | # return | |
263 | # |
|
263 | # | |
264 | # nlprint(arg) |
|
264 | # nlprint(arg) | |
265 | # |
|
265 | # | |
266 | # print_slist = result_display.when_type(SList)(print_slist) |
|
266 | # print_slist = result_display.when_type(SList)(print_slist) | |
267 |
|
267 | |||
268 |
|
268 | |||
269 | def esc_quotes(strng): |
|
269 | def esc_quotes(strng): | |
270 | """Return the input string with single and double quotes escaped out""" |
|
270 | """Return the input string with single and double quotes escaped out""" | |
271 |
|
271 | |||
272 | return strng.replace('"','\\"').replace("'","\\'") |
|
272 | return strng.replace('"','\\"').replace("'","\\'") | |
273 |
|
273 | |||
274 |
|
274 | |||
275 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
275 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
276 | """Similar to Perl's qw() operator, but with some more options. |
|
276 | """Similar to Perl's qw() operator, but with some more options. | |
277 |
|
277 | |||
278 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
278 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
279 |
|
279 | |||
280 | words can also be a list itself, and with flat=1, the output will be |
|
280 | words can also be a list itself, and with flat=1, the output will be | |
281 | recursively flattened. |
|
281 | recursively flattened. | |
282 |
|
282 | |||
283 | Examples: |
|
283 | Examples: | |
284 |
|
284 | |||
285 | >>> qw('1 2') |
|
285 | >>> qw('1 2') | |
286 | ['1', '2'] |
|
286 | ['1', '2'] | |
287 |
|
287 | |||
288 | >>> qw(['a b','1 2',['m n','p q']]) |
|
288 | >>> qw(['a b','1 2',['m n','p q']]) | |
289 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
289 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
290 |
|
290 | |||
291 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
291 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
292 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] |
|
292 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] | |
293 | """ |
|
293 | """ | |
294 |
|
294 | |||
295 | if isinstance(words, basestring): |
|
295 | if isinstance(words, basestring): | |
296 | return [word.strip() for word in words.split(sep,maxsplit) |
|
296 | return [word.strip() for word in words.split(sep,maxsplit) | |
297 | if word and not word.isspace() ] |
|
297 | if word and not word.isspace() ] | |
298 | if flat: |
|
298 | if flat: | |
299 | return flatten(map(qw,words,[1]*len(words))) |
|
299 | return flatten(map(qw,words,[1]*len(words))) | |
300 | return map(qw,words) |
|
300 | return map(qw,words) | |
301 |
|
301 | |||
302 |
|
302 | |||
303 | def qwflat(words,sep=None,maxsplit=-1): |
|
303 | def qwflat(words,sep=None,maxsplit=-1): | |
304 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
304 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
305 | return qw(words,1,sep,maxsplit) |
|
305 | return qw(words,1,sep,maxsplit) | |
306 |
|
306 | |||
307 |
|
307 | |||
308 | def qw_lol(indata): |
|
308 | def qw_lol(indata): | |
309 | """qw_lol('a b') -> [['a','b']], |
|
309 | """qw_lol('a b') -> [['a','b']], | |
310 | otherwise it's just a call to qw(). |
|
310 | otherwise it's just a call to qw(). | |
311 |
|
311 | |||
312 | We need this to make sure the modules_some keys *always* end up as a |
|
312 | We need this to make sure the modules_some keys *always* end up as a | |
313 | list of lists.""" |
|
313 | list of lists.""" | |
314 |
|
314 | |||
315 | if isinstance(indata, basestring): |
|
315 | if isinstance(indata, basestring): | |
316 | return [qw(indata)] |
|
316 | return [qw(indata)] | |
317 | else: |
|
317 | else: | |
318 | return qw(indata) |
|
318 | return qw(indata) | |
319 |
|
319 | |||
320 |
|
320 | |||
321 | def grep(pat,list,case=1): |
|
321 | def grep(pat,list,case=1): | |
322 | """Simple minded grep-like function. |
|
322 | """Simple minded grep-like function. | |
323 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
323 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
324 |
|
324 | |||
325 | It only does simple string matching, with no support for regexps. Use the |
|
325 | It only does simple string matching, with no support for regexps. Use the | |
326 | option case=0 for case-insensitive matching.""" |
|
326 | option case=0 for case-insensitive matching.""" | |
327 |
|
327 | |||
328 | # This is pretty crude. At least it should implement copying only references |
|
328 | # This is pretty crude. At least it should implement copying only references | |
329 | # to the original data in case it's big. Now it copies the data for output. |
|
329 | # to the original data in case it's big. Now it copies the data for output. | |
330 | out=[] |
|
330 | out=[] | |
331 | if case: |
|
331 | if case: | |
332 | for term in list: |
|
332 | for term in list: | |
333 | if term.find(pat)>-1: out.append(term) |
|
333 | if term.find(pat)>-1: out.append(term) | |
334 | else: |
|
334 | else: | |
335 | lpat=pat.lower() |
|
335 | lpat=pat.lower() | |
336 | for term in list: |
|
336 | for term in list: | |
337 | if term.lower().find(lpat)>-1: out.append(term) |
|
337 | if term.lower().find(lpat)>-1: out.append(term) | |
338 |
|
338 | |||
339 | if len(out): return out |
|
339 | if len(out): return out | |
340 | else: return None |
|
340 | else: return None | |
341 |
|
341 | |||
342 |
|
342 | |||
343 | def dgrep(pat,*opts): |
|
343 | def dgrep(pat,*opts): | |
344 | """Return grep() on dir()+dir(__builtins__). |
|
344 | """Return grep() on dir()+dir(__builtins__). | |
345 |
|
345 | |||
346 | A very common use of grep() when working interactively.""" |
|
346 | A very common use of grep() when working interactively.""" | |
347 |
|
347 | |||
348 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
348 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
349 |
|
349 | |||
350 |
|
350 | |||
351 | def idgrep(pat): |
|
351 | def idgrep(pat): | |
352 | """Case-insensitive dgrep()""" |
|
352 | """Case-insensitive dgrep()""" | |
353 |
|
353 | |||
354 | return dgrep(pat,0) |
|
354 | return dgrep(pat,0) | |
355 |
|
355 | |||
356 |
|
356 | |||
357 | def igrep(pat,list): |
|
357 | def igrep(pat,list): | |
358 | """Synonym for case-insensitive grep.""" |
|
358 | """Synonym for case-insensitive grep.""" | |
359 |
|
359 | |||
360 | return grep(pat,list,case=0) |
|
360 | return grep(pat,list,case=0) | |
361 |
|
361 | |||
362 |
|
362 | |||
363 | def indent(instr,nspaces=4, ntabs=0, flatten=False): |
|
363 | def indent(instr,nspaces=4, ntabs=0, flatten=False): | |
364 | """Indent a string a given number of spaces or tabstops. |
|
364 | """Indent a string a given number of spaces or tabstops. | |
365 |
|
365 | |||
366 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
366 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
367 |
|
367 | |||
368 | Parameters |
|
368 | Parameters | |
369 | ---------- |
|
369 | ---------- | |
370 |
|
370 | |||
371 | instr : basestring |
|
371 | instr : basestring | |
372 | The string to be indented. |
|
372 | The string to be indented. | |
373 | nspaces : int (default: 4) |
|
373 | nspaces : int (default: 4) | |
374 | The number of spaces to be indented. |
|
374 | The number of spaces to be indented. | |
375 | ntabs : int (default: 0) |
|
375 | ntabs : int (default: 0) | |
376 | The number of tabs to be indented. |
|
376 | The number of tabs to be indented. | |
377 | flatten : bool (default: False) |
|
377 | flatten : bool (default: False) | |
378 | Whether to scrub existing indentation. If True, all lines will be |
|
378 | Whether to scrub existing indentation. If True, all lines will be | |
379 | aligned to the same indentation. If False, existing indentation will |
|
379 | aligned to the same indentation. If False, existing indentation will | |
380 | be strictly increased. |
|
380 | be strictly increased. | |
381 |
|
381 | |||
382 | Returns |
|
382 | Returns | |
383 | ------- |
|
383 | ------- | |
384 |
|
384 | |||
385 | str|unicode : string indented by ntabs and nspaces. |
|
385 | str|unicode : string indented by ntabs and nspaces. | |
386 |
|
386 | |||
387 | """ |
|
387 | """ | |
388 | if instr is None: |
|
388 | if instr is None: | |
389 | return |
|
389 | return | |
390 | ind = '\t'*ntabs+' '*nspaces |
|
390 | ind = '\t'*ntabs+' '*nspaces | |
391 | if flatten: |
|
391 | if flatten: | |
392 | pat = re.compile(r'^\s*', re.MULTILINE) |
|
392 | pat = re.compile(r'^\s*', re.MULTILINE) | |
393 | else: |
|
393 | else: | |
394 | pat = re.compile(r'^', re.MULTILINE) |
|
394 | pat = re.compile(r'^', re.MULTILINE) | |
395 | outstr = re.sub(pat, ind, instr) |
|
395 | outstr = re.sub(pat, ind, instr) | |
396 | if outstr.endswith(os.linesep+ind): |
|
396 | if outstr.endswith(os.linesep+ind): | |
397 | return outstr[:-len(ind)] |
|
397 | return outstr[:-len(ind)] | |
398 | else: |
|
398 | else: | |
399 | return outstr |
|
399 | return outstr | |
400 |
|
400 | |||
401 | def native_line_ends(filename,backup=1): |
|
401 | def native_line_ends(filename,backup=1): | |
402 | """Convert (in-place) a file to line-ends native to the current OS. |
|
402 | """Convert (in-place) a file to line-ends native to the current OS. | |
403 |
|
403 | |||
404 | If the optional backup argument is given as false, no backup of the |
|
404 | If the optional backup argument is given as false, no backup of the | |
405 | original file is left. """ |
|
405 | original file is left. """ | |
406 |
|
406 | |||
407 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
407 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
408 |
|
408 | |||
409 | bak_filename = filename + backup_suffixes[os.name] |
|
409 | bak_filename = filename + backup_suffixes[os.name] | |
410 |
|
410 | |||
411 | original = open(filename).read() |
|
411 | original = open(filename).read() | |
412 | shutil.copy2(filename,bak_filename) |
|
412 | shutil.copy2(filename,bak_filename) | |
413 | try: |
|
413 | try: | |
414 | new = open(filename,'wb') |
|
414 | new = open(filename,'wb') | |
415 | new.write(os.linesep.join(original.splitlines())) |
|
415 | new.write(os.linesep.join(original.splitlines())) | |
416 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
416 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
417 | new.close() |
|
417 | new.close() | |
418 | except: |
|
418 | except: | |
419 | os.rename(bak_filename,filename) |
|
419 | os.rename(bak_filename,filename) | |
420 | if not backup: |
|
420 | if not backup: | |
421 | try: |
|
421 | try: | |
422 | os.remove(bak_filename) |
|
422 | os.remove(bak_filename) | |
423 | except: |
|
423 | except: | |
424 | pass |
|
424 | pass | |
425 |
|
425 | |||
426 |
|
426 | |||
427 | def list_strings(arg): |
|
427 | def list_strings(arg): | |
428 | """Always return a list of strings, given a string or list of strings |
|
428 | """Always return a list of strings, given a string or list of strings | |
429 | as input. |
|
429 | as input. | |
430 |
|
430 | |||
431 | :Examples: |
|
431 | :Examples: | |
432 |
|
432 | |||
433 | In [7]: list_strings('A single string') |
|
433 | In [7]: list_strings('A single string') | |
434 | Out[7]: ['A single string'] |
|
434 | Out[7]: ['A single string'] | |
435 |
|
435 | |||
436 | In [8]: list_strings(['A single string in a list']) |
|
436 | In [8]: list_strings(['A single string in a list']) | |
437 | Out[8]: ['A single string in a list'] |
|
437 | Out[8]: ['A single string in a list'] | |
438 |
|
438 | |||
439 | In [9]: list_strings(['A','list','of','strings']) |
|
439 | In [9]: list_strings(['A','list','of','strings']) | |
440 | Out[9]: ['A', 'list', 'of', 'strings'] |
|
440 | Out[9]: ['A', 'list', 'of', 'strings'] | |
441 | """ |
|
441 | """ | |
442 |
|
442 | |||
443 | if isinstance(arg,basestring): return [arg] |
|
443 | if isinstance(arg,basestring): return [arg] | |
444 | else: return arg |
|
444 | else: return arg | |
445 |
|
445 | |||
446 |
|
446 | |||
447 | def marquee(txt='',width=78,mark='*'): |
|
447 | def marquee(txt='',width=78,mark='*'): | |
448 | """Return the input string centered in a 'marquee'. |
|
448 | """Return the input string centered in a 'marquee'. | |
449 |
|
449 | |||
450 | :Examples: |
|
450 | :Examples: | |
451 |
|
451 | |||
452 | In [16]: marquee('A test',40) |
|
452 | In [16]: marquee('A test',40) | |
453 | Out[16]: '**************** A test ****************' |
|
453 | Out[16]: '**************** A test ****************' | |
454 |
|
454 | |||
455 | In [17]: marquee('A test',40,'-') |
|
455 | In [17]: marquee('A test',40,'-') | |
456 | Out[17]: '---------------- A test ----------------' |
|
456 | Out[17]: '---------------- A test ----------------' | |
457 |
|
457 | |||
458 | In [18]: marquee('A test',40,' ') |
|
458 | In [18]: marquee('A test',40,' ') | |
459 | Out[18]: ' A test ' |
|
459 | Out[18]: ' A test ' | |
460 |
|
460 | |||
461 | """ |
|
461 | """ | |
462 | if not txt: |
|
462 | if not txt: | |
463 | return (mark*width)[:width] |
|
463 | return (mark*width)[:width] | |
464 | nmark = (width-len(txt)-2)//len(mark)//2 |
|
464 | nmark = (width-len(txt)-2)//len(mark)//2 | |
465 | if nmark < 0: nmark =0 |
|
465 | if nmark < 0: nmark =0 | |
466 | marks = mark*nmark |
|
466 | marks = mark*nmark | |
467 | return '%s %s %s' % (marks,txt,marks) |
|
467 | return '%s %s %s' % (marks,txt,marks) | |
468 |
|
468 | |||
469 |
|
469 | |||
470 | ini_spaces_re = re.compile(r'^(\s+)') |
|
470 | ini_spaces_re = re.compile(r'^(\s+)') | |
471 |
|
471 | |||
472 | def num_ini_spaces(strng): |
|
472 | def num_ini_spaces(strng): | |
473 | """Return the number of initial spaces in a string""" |
|
473 | """Return the number of initial spaces in a string""" | |
474 |
|
474 | |||
475 | ini_spaces = ini_spaces_re.match(strng) |
|
475 | ini_spaces = ini_spaces_re.match(strng) | |
476 | if ini_spaces: |
|
476 | if ini_spaces: | |
477 | return ini_spaces.end() |
|
477 | return ini_spaces.end() | |
478 | else: |
|
478 | else: | |
479 | return 0 |
|
479 | return 0 | |
480 |
|
480 | |||
481 |
|
481 | |||
482 | def format_screen(strng): |
|
482 | def format_screen(strng): | |
483 | """Format a string for screen printing. |
|
483 | """Format a string for screen printing. | |
484 |
|
484 | |||
485 | This removes some latex-type format codes.""" |
|
485 | This removes some latex-type format codes.""" | |
486 | # Paragraph continue |
|
486 | # Paragraph continue | |
487 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
487 | par_re = re.compile(r'\\$',re.MULTILINE) | |
488 | strng = par_re.sub('',strng) |
|
488 | strng = par_re.sub('',strng) | |
489 | return strng |
|
489 | return strng | |
490 |
|
490 | |||
491 |
|
491 | |||
492 | def dedent(text): |
|
492 | def dedent(text): | |
493 | """Equivalent of textwrap.dedent that ignores unindented first line. |
|
493 | """Equivalent of textwrap.dedent that ignores unindented first line. | |
494 |
|
494 | |||
495 | This means it will still dedent strings like: |
|
495 | This means it will still dedent strings like: | |
496 | '''foo |
|
496 | '''foo | |
497 | is a bar |
|
497 | is a bar | |
498 | ''' |
|
498 | ''' | |
499 |
|
499 | |||
500 | For use in wrap_paragraphs. |
|
500 | For use in wrap_paragraphs. | |
501 | """ |
|
501 | """ | |
502 |
|
502 | |||
503 | if text.startswith('\n'): |
|
503 | if text.startswith('\n'): | |
504 | # text starts with blank line, don't ignore the first line |
|
504 | # text starts with blank line, don't ignore the first line | |
505 | return textwrap.dedent(text) |
|
505 | return textwrap.dedent(text) | |
506 |
|
506 | |||
507 | # split first line |
|
507 | # split first line | |
508 | splits = text.split('\n',1) |
|
508 | splits = text.split('\n',1) | |
509 | if len(splits) == 1: |
|
509 | if len(splits) == 1: | |
510 | # only one line |
|
510 | # only one line | |
511 | return textwrap.dedent(text) |
|
511 | return textwrap.dedent(text) | |
512 |
|
512 | |||
513 | first, rest = splits |
|
513 | first, rest = splits | |
514 | # dedent everything but the first line |
|
514 | # dedent everything but the first line | |
515 | rest = textwrap.dedent(rest) |
|
515 | rest = textwrap.dedent(rest) | |
516 | return '\n'.join([first, rest]) |
|
516 | return '\n'.join([first, rest]) | |
517 |
|
517 | |||
518 |
|
518 | |||
519 | def wrap_paragraphs(text, ncols=80): |
|
519 | def wrap_paragraphs(text, ncols=80): | |
520 | """Wrap multiple paragraphs to fit a specified width. |
|
520 | """Wrap multiple paragraphs to fit a specified width. | |
521 |
|
521 | |||
522 | This is equivalent to textwrap.wrap, but with support for multiple |
|
522 | This is equivalent to textwrap.wrap, but with support for multiple | |
523 | paragraphs, as separated by empty lines. |
|
523 | paragraphs, as separated by empty lines. | |
524 |
|
524 | |||
525 | Returns |
|
525 | Returns | |
526 | ------- |
|
526 | ------- | |
527 |
|
527 | |||
528 | list of complete paragraphs, wrapped to fill `ncols` columns. |
|
528 | list of complete paragraphs, wrapped to fill `ncols` columns. | |
529 | """ |
|
529 | """ | |
530 | paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) |
|
530 | paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) | |
531 | text = dedent(text).strip() |
|
531 | text = dedent(text).strip() | |
532 | paragraphs = paragraph_re.split(text)[::2] # every other entry is space |
|
532 | paragraphs = paragraph_re.split(text)[::2] # every other entry is space | |
533 | out_ps = [] |
|
533 | out_ps = [] | |
534 | indent_re = re.compile(r'\n\s+', re.MULTILINE) |
|
534 | indent_re = re.compile(r'\n\s+', re.MULTILINE) | |
535 | for p in paragraphs: |
|
535 | for p in paragraphs: | |
536 | # presume indentation that survives dedent is meaningful formatting, |
|
536 | # presume indentation that survives dedent is meaningful formatting, | |
537 | # so don't fill unless text is flush. |
|
537 | # so don't fill unless text is flush. | |
538 | if indent_re.search(p) is None: |
|
538 | if indent_re.search(p) is None: | |
539 | # wrap paragraph |
|
539 | # wrap paragraph | |
540 | p = textwrap.fill(p, ncols) |
|
540 | p = textwrap.fill(p, ncols) | |
541 | out_ps.append(p) |
|
541 | out_ps.append(p) | |
542 | return out_ps |
|
542 | return out_ps | |
543 |
|
543 | |||
544 |
|
544 | |||
545 | def long_substr(data): |
|
545 | def long_substr(data): | |
546 | """Return the longest common substring in a list of strings. |
|
546 | """Return the longest common substring in a list of strings. | |
547 |
|
547 | |||
548 | Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python |
|
548 | Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python | |
549 | """ |
|
549 | """ | |
550 | substr = '' |
|
550 | substr = '' | |
551 | if len(data) > 1 and len(data[0]) > 0: |
|
551 | if len(data) > 1 and len(data[0]) > 0: | |
552 | for i in range(len(data[0])): |
|
552 | for i in range(len(data[0])): | |
553 | for j in range(len(data[0])-i+1): |
|
553 | for j in range(len(data[0])-i+1): | |
554 | if j > len(substr) and all(data[0][i:i+j] in x for x in data): |
|
554 | if j > len(substr) and all(data[0][i:i+j] in x for x in data): | |
555 | substr = data[0][i:i+j] |
|
555 | substr = data[0][i:i+j] | |
|
556 | else: | |||
|
557 | substr = data[0] | |||
556 | return substr |
|
558 | return substr | |
557 |
|
559 | |||
558 |
|
560 | |||
559 | def strip_email_quotes(text): |
|
561 | def strip_email_quotes(text): | |
560 | """Strip leading email quotation characters ('>'). |
|
562 | """Strip leading email quotation characters ('>'). | |
561 | """ |
|
563 | """ | |
562 | lines = text.splitlines() |
|
564 | lines = text.splitlines() | |
563 | matches = set() |
|
565 | matches = set() | |
564 | for line in lines: |
|
566 | for line in lines: | |
565 | prefix = re.match(r'^(\s*>[ >]*)', line) |
|
567 | prefix = re.match(r'^(\s*>[ >]*)', line) | |
566 | if prefix: |
|
568 | if prefix: | |
567 | matches.add(prefix.group(1)) |
|
569 | matches.add(prefix.group(1)) | |
568 | else: |
|
570 | else: | |
569 | break |
|
571 | break | |
570 | else: |
|
572 | else: | |
571 | prefix = long_substr(list(matches)) |
|
573 | prefix = long_substr(list(matches)) | |
572 | if prefix: |
|
574 | if prefix: | |
573 | strip = len(prefix) |
|
575 | strip = len(prefix) | |
574 | text = '\n'.join([ ln[strip:] for ln in lines]) |
|
576 | text = '\n'.join([ ln[strip:] for ln in lines]) | |
575 | return text |
|
577 | return text | |
576 |
|
578 | |||
577 |
|
579 | |||
578 | class EvalFormatter(Formatter): |
|
580 | class EvalFormatter(Formatter): | |
579 | """A String Formatter that allows evaluation of simple expressions. |
|
581 | """A String Formatter that allows evaluation of simple expressions. | |
580 |
|
582 | |||
581 | Note that this version interprets a : as specifying a format string (as per |
|
583 | Note that this version interprets a : as specifying a format string (as per | |
582 | standard string formatting), so if slicing is required, you must explicitly |
|
584 | standard string formatting), so if slicing is required, you must explicitly | |
583 | create a slice. |
|
585 | create a slice. | |
584 |
|
586 | |||
585 | This is to be used in templating cases, such as the parallel batch |
|
587 | This is to be used in templating cases, such as the parallel batch | |
586 | script templates, where simple arithmetic on arguments is useful. |
|
588 | script templates, where simple arithmetic on arguments is useful. | |
587 |
|
589 | |||
588 | Examples |
|
590 | Examples | |
589 | -------- |
|
591 | -------- | |
590 |
|
592 | |||
591 | In [1]: f = EvalFormatter() |
|
593 | In [1]: f = EvalFormatter() | |
592 | In [2]: f.format('{n//4}', n=8) |
|
594 | In [2]: f.format('{n//4}', n=8) | |
593 | Out [2]: '2' |
|
595 | Out [2]: '2' | |
594 |
|
596 | |||
595 | In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello") |
|
597 | In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello") | |
596 | Out [3]: 'll' |
|
598 | Out [3]: 'll' | |
597 | """ |
|
599 | """ | |
598 | def get_field(self, name, args, kwargs): |
|
600 | def get_field(self, name, args, kwargs): | |
599 | v = eval(name, kwargs) |
|
601 | v = eval(name, kwargs) | |
600 | return v, name |
|
602 | return v, name | |
601 |
|
603 | |||
602 | @skip_doctest_py3 |
|
604 | @skip_doctest_py3 | |
603 | class FullEvalFormatter(Formatter): |
|
605 | class FullEvalFormatter(Formatter): | |
604 | """A String Formatter that allows evaluation of simple expressions. |
|
606 | """A String Formatter that allows evaluation of simple expressions. | |
605 |
|
607 | |||
606 | Any time a format key is not found in the kwargs, |
|
608 | Any time a format key is not found in the kwargs, | |
607 | it will be tried as an expression in the kwargs namespace. |
|
609 | it will be tried as an expression in the kwargs namespace. | |
608 |
|
610 | |||
609 | Note that this version allows slicing using [1:2], so you cannot specify |
|
611 | Note that this version allows slicing using [1:2], so you cannot specify | |
610 | a format string. Use :class:`EvalFormatter` to permit format strings. |
|
612 | a format string. Use :class:`EvalFormatter` to permit format strings. | |
611 |
|
613 | |||
612 | Examples |
|
614 | Examples | |
613 | -------- |
|
615 | -------- | |
614 |
|
616 | |||
615 | In [1]: f = FullEvalFormatter() |
|
617 | In [1]: f = FullEvalFormatter() | |
616 | In [2]: f.format('{n//4}', n=8) |
|
618 | In [2]: f.format('{n//4}', n=8) | |
617 | Out[2]: u'2' |
|
619 | Out[2]: u'2' | |
618 |
|
620 | |||
619 | In [3]: f.format('{list(range(5))[2:4]}') |
|
621 | In [3]: f.format('{list(range(5))[2:4]}') | |
620 | Out[3]: u'[2, 3]' |
|
622 | Out[3]: u'[2, 3]' | |
621 |
|
623 | |||
622 | In [4]: f.format('{3*2}') |
|
624 | In [4]: f.format('{3*2}') | |
623 | Out[4]: u'6' |
|
625 | Out[4]: u'6' | |
624 | """ |
|
626 | """ | |
625 | # copied from Formatter._vformat with minor changes to allow eval |
|
627 | # copied from Formatter._vformat with minor changes to allow eval | |
626 | # and replace the format_spec code with slicing |
|
628 | # and replace the format_spec code with slicing | |
627 | def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): |
|
629 | def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): | |
628 | if recursion_depth < 0: |
|
630 | if recursion_depth < 0: | |
629 | raise ValueError('Max string recursion exceeded') |
|
631 | raise ValueError('Max string recursion exceeded') | |
630 | result = [] |
|
632 | result = [] | |
631 | for literal_text, field_name, format_spec, conversion in \ |
|
633 | for literal_text, field_name, format_spec, conversion in \ | |
632 | self.parse(format_string): |
|
634 | self.parse(format_string): | |
633 |
|
635 | |||
634 | # output the literal text |
|
636 | # output the literal text | |
635 | if literal_text: |
|
637 | if literal_text: | |
636 | result.append(literal_text) |
|
638 | result.append(literal_text) | |
637 |
|
639 | |||
638 | # if there's a field, output it |
|
640 | # if there's a field, output it | |
639 | if field_name is not None: |
|
641 | if field_name is not None: | |
640 | # this is some markup, find the object and do |
|
642 | # this is some markup, find the object and do | |
641 | # the formatting |
|
643 | # the formatting | |
642 |
|
644 | |||
643 | if format_spec: |
|
645 | if format_spec: | |
644 | # override format spec, to allow slicing: |
|
646 | # override format spec, to allow slicing: | |
645 | field_name = ':'.join([field_name, format_spec]) |
|
647 | field_name = ':'.join([field_name, format_spec]) | |
646 |
|
648 | |||
647 | # eval the contents of the field for the object |
|
649 | # eval the contents of the field for the object | |
648 | # to be formatted |
|
650 | # to be formatted | |
649 | obj = eval(field_name, kwargs) |
|
651 | obj = eval(field_name, kwargs) | |
650 |
|
652 | |||
651 | # do any conversion on the resulting object |
|
653 | # do any conversion on the resulting object | |
652 | obj = self.convert_field(obj, conversion) |
|
654 | obj = self.convert_field(obj, conversion) | |
653 |
|
655 | |||
654 | # format the object and append to the result |
|
656 | # format the object and append to the result | |
655 | result.append(self.format_field(obj, '')) |
|
657 | result.append(self.format_field(obj, '')) | |
656 |
|
658 | |||
657 | return u''.join(py3compat.cast_unicode(s) for s in result) |
|
659 | return u''.join(py3compat.cast_unicode(s) for s in result) | |
658 |
|
660 | |||
659 | @skip_doctest_py3 |
|
661 | @skip_doctest_py3 | |
660 | class DollarFormatter(FullEvalFormatter): |
|
662 | class DollarFormatter(FullEvalFormatter): | |
661 | """Formatter allowing Itpl style $foo replacement, for names and attribute |
|
663 | """Formatter allowing Itpl style $foo replacement, for names and attribute | |
662 | access only. Standard {foo} replacement also works, and allows full |
|
664 | access only. Standard {foo} replacement also works, and allows full | |
663 | evaluation of its arguments. |
|
665 | evaluation of its arguments. | |
664 |
|
666 | |||
665 | Examples |
|
667 | Examples | |
666 | -------- |
|
668 | -------- | |
667 | In [1]: f = DollarFormatter() |
|
669 | In [1]: f = DollarFormatter() | |
668 | In [2]: f.format('{n//4}', n=8) |
|
670 | In [2]: f.format('{n//4}', n=8) | |
669 | Out[2]: u'2' |
|
671 | Out[2]: u'2' | |
670 |
|
672 | |||
671 | In [3]: f.format('23 * 76 is $result', result=23*76) |
|
673 | In [3]: f.format('23 * 76 is $result', result=23*76) | |
672 | Out[3]: u'23 * 76 is 1748' |
|
674 | Out[3]: u'23 * 76 is 1748' | |
673 |
|
675 | |||
674 | In [4]: f.format('$a or {b}', a=1, b=2) |
|
676 | In [4]: f.format('$a or {b}', a=1, b=2) | |
675 | Out[4]: u'1 or 2' |
|
677 | Out[4]: u'1 or 2' | |
676 | """ |
|
678 | """ | |
677 | _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)") |
|
679 | _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)") | |
678 | def parse(self, fmt_string): |
|
680 | def parse(self, fmt_string): | |
679 | for literal_txt, field_name, format_spec, conversion \ |
|
681 | for literal_txt, field_name, format_spec, conversion \ | |
680 | in Formatter.parse(self, fmt_string): |
|
682 | in Formatter.parse(self, fmt_string): | |
681 |
|
683 | |||
682 | # Find $foo patterns in the literal text. |
|
684 | # Find $foo patterns in the literal text. | |
683 | continue_from = 0 |
|
685 | continue_from = 0 | |
684 | txt = "" |
|
686 | txt = "" | |
685 | for m in self._dollar_pattern.finditer(literal_txt): |
|
687 | for m in self._dollar_pattern.finditer(literal_txt): | |
686 | new_txt, new_field = m.group(1,2) |
|
688 | new_txt, new_field = m.group(1,2) | |
687 | # $$foo --> $foo |
|
689 | # $$foo --> $foo | |
688 | if new_field.startswith("$"): |
|
690 | if new_field.startswith("$"): | |
689 | txt += new_txt + new_field |
|
691 | txt += new_txt + new_field | |
690 | else: |
|
692 | else: | |
691 | yield (txt + new_txt, new_field, "", None) |
|
693 | yield (txt + new_txt, new_field, "", None) | |
692 | txt = "" |
|
694 | txt = "" | |
693 | continue_from = m.end() |
|
695 | continue_from = m.end() | |
694 |
|
696 | |||
695 | # Re-yield the {foo} style pattern |
|
697 | # Re-yield the {foo} style pattern | |
696 | yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion) |
|
698 | yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion) | |
697 |
|
699 | |||
698 | #----------------------------------------------------------------------------- |
|
700 | #----------------------------------------------------------------------------- | |
699 | # Utils to columnize a list of string |
|
701 | # Utils to columnize a list of string | |
700 | #----------------------------------------------------------------------------- |
|
702 | #----------------------------------------------------------------------------- | |
701 | def _chunks(l, n): |
|
703 | def _chunks(l, n): | |
702 | """Yield successive n-sized chunks from l.""" |
|
704 | """Yield successive n-sized chunks from l.""" | |
703 | for i in xrange(0, len(l), n): |
|
705 | for i in xrange(0, len(l), n): | |
704 | yield l[i:i+n] |
|
706 | yield l[i:i+n] | |
705 |
|
707 | |||
706 | def _find_optimal(rlist , separator_size=2 , displaywidth=80): |
|
708 | def _find_optimal(rlist , separator_size=2 , displaywidth=80): | |
707 | """Calculate optimal info to columnize a list of string""" |
|
709 | """Calculate optimal info to columnize a list of string""" | |
708 | for nrow in range(1, len(rlist)+1) : |
|
710 | for nrow in range(1, len(rlist)+1) : | |
709 | chk = map(max,_chunks(rlist, nrow)) |
|
711 | chk = map(max,_chunks(rlist, nrow)) | |
710 | sumlength = sum(chk) |
|
712 | sumlength = sum(chk) | |
711 | ncols = len(chk) |
|
713 | ncols = len(chk) | |
712 | if sumlength+separator_size*(ncols-1) <= displaywidth : |
|
714 | if sumlength+separator_size*(ncols-1) <= displaywidth : | |
713 | break; |
|
715 | break; | |
714 | return {'columns_numbers' : ncols, |
|
716 | return {'columns_numbers' : ncols, | |
715 | 'optimal_separator_width':(displaywidth - sumlength)/(ncols-1) if (ncols -1) else 0, |
|
717 | 'optimal_separator_width':(displaywidth - sumlength)/(ncols-1) if (ncols -1) else 0, | |
716 | 'rows_numbers' : nrow, |
|
718 | 'rows_numbers' : nrow, | |
717 | 'columns_width' : chk |
|
719 | 'columns_width' : chk | |
718 | } |
|
720 | } | |
719 |
|
721 | |||
720 | def _get_or_default(mylist, i, default=None): |
|
722 | def _get_or_default(mylist, i, default=None): | |
721 | """return list item number, or default if don't exist""" |
|
723 | """return list item number, or default if don't exist""" | |
722 | if i >= len(mylist): |
|
724 | if i >= len(mylist): | |
723 | return default |
|
725 | return default | |
724 | else : |
|
726 | else : | |
725 | return mylist[i] |
|
727 | return mylist[i] | |
726 |
|
728 | |||
727 | @skip_doctest |
|
729 | @skip_doctest | |
728 | def compute_item_matrix(items, empty=None, *args, **kwargs) : |
|
730 | def compute_item_matrix(items, empty=None, *args, **kwargs) : | |
729 | """Returns a nested list, and info to columnize items |
|
731 | """Returns a nested list, and info to columnize items | |
730 |
|
732 | |||
731 | Parameters : |
|
733 | Parameters : | |
732 | ------------ |
|
734 | ------------ | |
733 |
|
735 | |||
734 | items : |
|
736 | items : | |
735 | list of strings to columize |
|
737 | list of strings to columize | |
736 | empty : (default None) |
|
738 | empty : (default None) | |
737 | default value to fill list if needed |
|
739 | default value to fill list if needed | |
738 | separator_size : int (default=2) |
|
740 | separator_size : int (default=2) | |
739 | How much caracters will be used as a separation between each columns. |
|
741 | How much caracters will be used as a separation between each columns. | |
740 | displaywidth : int (default=80) |
|
742 | displaywidth : int (default=80) | |
741 | The width of the area onto wich the columns should enter |
|
743 | The width of the area onto wich the columns should enter | |
742 |
|
744 | |||
743 | Returns : |
|
745 | Returns : | |
744 | --------- |
|
746 | --------- | |
745 |
|
747 | |||
746 | Returns a tuple of (strings_matrix, dict_info) |
|
748 | Returns a tuple of (strings_matrix, dict_info) | |
747 |
|
749 | |||
748 | strings_matrix : |
|
750 | strings_matrix : | |
749 |
|
751 | |||
750 | nested list of string, the outer most list contains as many list as |
|
752 | nested list of string, the outer most list contains as many list as | |
751 | rows, the innermost lists have each as many element as colums. If the |
|
753 | rows, the innermost lists have each as many element as colums. If the | |
752 | total number of elements in `items` does not equal the product of |
|
754 | total number of elements in `items` does not equal the product of | |
753 | rows*columns, the last element of some lists are filled with `None`. |
|
755 | rows*columns, the last element of some lists are filled with `None`. | |
754 |
|
756 | |||
755 | dict_info : |
|
757 | dict_info : | |
756 | some info to make columnize easier: |
|
758 | some info to make columnize easier: | |
757 |
|
759 | |||
758 | columns_numbers : number of columns |
|
760 | columns_numbers : number of columns | |
759 | rows_numbers : number of rows |
|
761 | rows_numbers : number of rows | |
760 | columns_width : list of with of each columns |
|
762 | columns_width : list of with of each columns | |
761 | optimal_separator_width : best separator width between columns |
|
763 | optimal_separator_width : best separator width between columns | |
762 |
|
764 | |||
763 | Exemple : |
|
765 | Exemple : | |
764 | --------- |
|
766 | --------- | |
765 |
|
767 | |||
766 | In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l'] |
|
768 | In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l'] | |
767 | ...: compute_item_matrix(l,displaywidth=12) |
|
769 | ...: compute_item_matrix(l,displaywidth=12) | |
768 | Out[1]: |
|
770 | Out[1]: | |
769 | ([['aaa', 'f', 'k'], |
|
771 | ([['aaa', 'f', 'k'], | |
770 | ['b', 'g', 'l'], |
|
772 | ['b', 'g', 'l'], | |
771 | ['cc', 'h', None], |
|
773 | ['cc', 'h', None], | |
772 | ['d', 'i', None], |
|
774 | ['d', 'i', None], | |
773 | ['eeeee', 'j', None]], |
|
775 | ['eeeee', 'j', None]], | |
774 | {'columns_numbers': 3, |
|
776 | {'columns_numbers': 3, | |
775 | 'columns_width': [5, 1, 1], |
|
777 | 'columns_width': [5, 1, 1], | |
776 | 'optimal_separator_width': 2, |
|
778 | 'optimal_separator_width': 2, | |
777 | 'rows_numbers': 5}) |
|
779 | 'rows_numbers': 5}) | |
778 |
|
780 | |||
779 | """ |
|
781 | """ | |
780 | info = _find_optimal(map(len, items), *args, **kwargs) |
|
782 | info = _find_optimal(map(len, items), *args, **kwargs) | |
781 | nrow, ncol = info['rows_numbers'], info['columns_numbers'] |
|
783 | nrow, ncol = info['rows_numbers'], info['columns_numbers'] | |
782 | return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range(nrow) ], info) |
|
784 | return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range(nrow) ], info) | |
783 |
|
785 | |||
784 | def columnize(items, separator=' ', displaywidth=80): |
|
786 | def columnize(items, separator=' ', displaywidth=80): | |
785 | """ Transform a list of strings into a single string with columns. |
|
787 | """ Transform a list of strings into a single string with columns. | |
786 |
|
788 | |||
787 | Parameters |
|
789 | Parameters | |
788 | ---------- |
|
790 | ---------- | |
789 | items : sequence of strings |
|
791 | items : sequence of strings | |
790 | The strings to process. |
|
792 | The strings to process. | |
791 |
|
793 | |||
792 | separator : str, optional [default is two spaces] |
|
794 | separator : str, optional [default is two spaces] | |
793 | The string that separates columns. |
|
795 | The string that separates columns. | |
794 |
|
796 | |||
795 | displaywidth : int, optional [default is 80] |
|
797 | displaywidth : int, optional [default is 80] | |
796 | Width of the display in number of characters. |
|
798 | Width of the display in number of characters. | |
797 |
|
799 | |||
798 | Returns |
|
800 | Returns | |
799 | ------- |
|
801 | ------- | |
800 | The formatted string. |
|
802 | The formatted string. | |
801 | """ |
|
803 | """ | |
802 | if not items : |
|
804 | if not items : | |
803 | return '\n' |
|
805 | return '\n' | |
804 | matrix, info = compute_item_matrix(items, separator_size=len(separator), displaywidth=displaywidth) |
|
806 | matrix, info = compute_item_matrix(items, separator_size=len(separator), displaywidth=displaywidth) | |
805 | fmatrix = [filter(None, x) for x in matrix] |
|
807 | fmatrix = [filter(None, x) for x in matrix] | |
806 | sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['columns_width'])]) |
|
808 | sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['columns_width'])]) | |
807 | return '\n'.join(map(sjoin, fmatrix))+'\n' |
|
809 | return '\n'.join(map(sjoin, fmatrix))+'\n' |
General Comments 0
You need to be logged in to leave comments.
Login now