##// END OF EJS Templates
merge all from 0.7.3 branch to trunk
vivainio -
Show More
@@ -1,31 +1,31 b''
1 import inspect
2 import IPython.ipapi
3 from IPython.genutils import arg_split
4 ip = IPython.ipapi.get()
5
6 from IPython import Debugger
7
8 def call_pydb(self, args):
9 """Invoke pydb with the supplied parameters."""
10 try:
11 import pydb
12 except ImportError:
13 raise ImportError("pydb doesn't seem to be installed.")
14
15 if not hasattr(pydb.pydb, "runv"):
16 raise ImportError("You need pydb version 1.19 or later installed.")
17
18 argl = arg_split(args)
19 # print argl # dbg
20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
21 pdb = Debugger.Pdb()
22 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
23 else:
24 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )()
25
26
27 ip.expose_magic("pydb",call_pydb)
28
29
30
31
1 import inspect
2 import IPython.ipapi
3 from IPython.genutils import arg_split
4 ip = IPython.ipapi.get()
5
6 from IPython import Debugger
7
8 def call_pydb(self, args):
9 """Invoke pydb with the supplied parameters."""
10 try:
11 import pydb
12 except ImportError:
13 raise ImportError("pydb doesn't seem to be installed.")
14
15 if not hasattr(pydb.pydb, "runv"):
16 raise ImportError("You need pydb version 1.19 or later installed.")
17
18 argl = arg_split(args)
19 # print argl # dbg
20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
21 pdb = Debugger.Pdb()
22 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
23 else:
24 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )()
25
26
27 ip.expose_magic("pydb",call_pydb)
28
29
30
31
@@ -1,218 +1,218 b''
1 """ Tab completion support for a couple of linux package managers
2
3 This is also an example of how to write custom completer plugins
4 or hooks.
5
6 Practical use:
7
8 [ipython]|1> import ipy_linux_package_managers
9 [ipython]|2> apt-get u<<< press tab here >>>
10 update upgrade
11 [ipython]|2> apt-get up
12
13 """
14 import IPython.ipapi
15 import glob,os,shlex,sys
16
17 ip = IPython.ipapi.get()
18
19 def vcs_completer(commands, event):
20 """ utility to make writing typical version control app completers easier
21
22 VCS command line apps typically have the format:
23
24 [sudo ]PROGNAME [help] [command] file file...
25
26 """
27
28
29 cmd_param = event.line.split()
30 if event.line.endswith(' '):
31 cmd_param.append('')
32
33 if cmd_param[0] == 'sudo':
34 cmd_param = cmd_param[1:]
35
36 if len(cmd_param) == 2 or 'help' in cmd_param:
37 return commands.split()
38
39 return ip.IP.Completer.file_matches(event.symbol)
40
41
42
43 def apt_completers(self, event):
44 """ This should return a list of strings with possible completions.
45
46 Note that all the included strings that don't start with event.symbol
47 are removed, in order to not confuse readline.
48
49 """
50 # print event # dbg
51
52 # commands are only suggested for the 'command' part of package manager
53 # invocation
54
55 cmd = (event.line + "<placeholder>").rsplit(None,1)[0]
56 # print cmd
57 if cmd.endswith('apt-get') or cmd.endswith('yum'):
58 return ['update', 'upgrade', 'install', 'remove']
59
60 # later on, add dpkg -l / whatever to get list of possible
61 # packages, add switches etc. for the rest of command line
62 # filling
63
64 raise IPython.ipapi.TryNext
65
66
67 # re_key specifies the regexp that triggers the specified completer
68
69 ip.set_hook('complete_command', apt_completers, re_key = '.*apt-get')
70 ip.set_hook('complete_command', apt_completers, re_key = '.*yum')
71
72 pkg_cache = None
73
74 def module_completer(self,event):
75 """ Give completions after user has typed 'import' """
76
77 # only a local version for py 2.4, pkgutil has no walk_packages() there
78 if sys.version_info < (2,5):
79 for el in [f[:-3] for f in glob.glob("*.py")]:
80 yield el
81 return
82
83 global pkg_cache
84 import pkgutil,imp,time
85 #current =
86 if pkg_cache is None:
87 print "\n\n[Standby while scanning modules, this can take a while]\n\n"
88 pkg_cache = list(pkgutil.walk_packages())
89
90 already = set()
91 for ld, name, ispkg in pkg_cache:
92 if name.count('.') < event.symbol.count('.') + 1:
93 if name not in already:
94 already.add(name)
95 yield name + (ispkg and '.' or '')
96 return
97
98 ip.set_hook('complete_command', module_completer, str_key = 'import')
99 ip.set_hook('complete_command', module_completer, str_key = 'from')
100
101 svn_commands = """\
102 add blame praise annotate ann cat checkout co cleanup commit ci copy
103 cp delete del remove rm diff di export help ? h import info list ls
104 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
105 pe propget pget pg proplist plist pl propset pset ps resolved revert
106 status stat st switch sw unlock update
107 """
108
109 def svn_completer(self,event):
110 return vcs_completer(svn_commands, event)
111
112 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
113
114 hg_commands = """
115 add addremove annotate archive backout branch branches bundle cat
116 clone commit copy diff export grep heads help identify import incoming
117 init locate log manifest merge outgoing parents paths pull push
118 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
119 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
120 qselect qseries qtop qunapplied recover remove rename revert rollback
121 root serve showconfig status strip tag tags tip unbundle update verify
122 version
123 """
124
125 def hg_completer(self,event):
126 """ Completer for mercurial commands """
127
128 return vcs_completer(hg_commands, event)
129
130 ip.set_hook('complete_command', hg_completer, str_key = 'hg')
131
132
133 bzr_commands = """
134 add annotate bind branch break-lock bundle-revisions cat check
135 checkout commit conflicts deleted diff export gannotate gbranch
136 gcommit gdiff help ignore ignored info init init-repository inventory
137 log merge missing mkdir mv nick pull push reconcile register-branch
138 remerge remove renames resolve revert revno root serve sign-my-commits
139 status testament unbind uncommit unknowns update upgrade version
140 version-info visualise whoami
141 """
142
143 def bzr_completer(self,event):
144 """ Completer for bazaar commands """
145 cmd_param = event.line.split()
146 if event.line.endswith(' '):
147 cmd_param.append('')
148
149 if len(cmd_param) > 2:
150 cmd = cmd_param[1]
151 param = cmd_param[-1]
152 output_file = (param == '--output=')
153 if cmd == 'help':
154 return bzr_commands.split()
155 elif cmd in ['bundle-revisions','conflicts',
156 'deleted','nick','register-branch',
157 'serve','unbind','upgrade','version',
158 'whoami'] and not output_file:
159 return []
160 else:
161 # the rest are probably file names
162 return ip.IP.Completer.file_matches(event.symbol)
163
164 return bzr_commands.split()
165
166 ip.set_hook('complete_command', bzr_completer, str_key = 'bzr')
167
168
169 def runlistpy(self, event):
170 comps = shlex.split(event.line)
171 relpath = (len(comps) > 1 and comps[-1] or '')
172
173 #print "rp",relpath # dbg
174 lglob = glob.glob
175 isdir = os.path.isdir
176 if relpath.startswith('~'):
177 relpath = os.path.expanduser(relpath)
178 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
179 if isdir(f)]
180 pys = [f.replace('\\','/') for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy')]
181 return dirs + pys
182
183 ip.set_hook('complete_command', runlistpy, str_key = '%run')
184
185 def cd_completer(self, event):
186 relpath = event.symbol
187 #print event # dbg
188 if '-b' in event.line:
189 # return only bookmark completions
190 bkms = self.db.get('bookmarks',{})
191 return bkms.keys()
192
193
194 if event.symbol == '-':
195 # jump in directory history by number
196 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
197 if len(ents) > 1:
198 return ents
199 return []
200
201 if relpath.startswith('~'):
202 relpath = os.path.expanduser(relpath).replace('\\','/')
203 found = []
204 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
205 if os.path.isdir(f)]:
206 if ' ' in d:
207 # we don't want to deal with any of that, complex code
208 # for this is elsewhere
209 raise IPython.ipapi.TryNext
210 found.append( d )
211
212 if not found:
213 if os.path.isdir(relpath):
214 return [relpath]
215 raise IPython.ipapi.TryNext
216 return found
217
218 ip.set_hook('complete_command', cd_completer, str_key = '%cd')
1 """ Tab completion support for a couple of linux package managers
2
3 This is also an example of how to write custom completer plugins
4 or hooks.
5
6 Practical use:
7
8 [ipython]|1> import ipy_linux_package_managers
9 [ipython]|2> apt-get u<<< press tab here >>>
10 update upgrade
11 [ipython]|2> apt-get up
12
13 """
14 import IPython.ipapi
15 import glob,os,shlex,sys
16
17 ip = IPython.ipapi.get()
18
19 def vcs_completer(commands, event):
20 """ utility to make writing typical version control app completers easier
21
22 VCS command line apps typically have the format:
23
24 [sudo ]PROGNAME [help] [command] file file...
25
26 """
27
28
29 cmd_param = event.line.split()
30 if event.line.endswith(' '):
31 cmd_param.append('')
32
33 if cmd_param[0] == 'sudo':
34 cmd_param = cmd_param[1:]
35
36 if len(cmd_param) == 2 or 'help' in cmd_param:
37 return commands.split()
38
39 return ip.IP.Completer.file_matches(event.symbol)
40
41
42
43 def apt_completers(self, event):
44 """ This should return a list of strings with possible completions.
45
46 Note that all the included strings that don't start with event.symbol
47 are removed, in order to not confuse readline.
48
49 """
50 # print event # dbg
51
52 # commands are only suggested for the 'command' part of package manager
53 # invocation
54
55 cmd = (event.line + "<placeholder>").rsplit(None,1)[0]
56 # print cmd
57 if cmd.endswith('apt-get') or cmd.endswith('yum'):
58 return ['update', 'upgrade', 'install', 'remove']
59
60 # later on, add dpkg -l / whatever to get list of possible
61 # packages, add switches etc. for the rest of command line
62 # filling
63
64 raise IPython.ipapi.TryNext
65
66
67 # re_key specifies the regexp that triggers the specified completer
68
69 ip.set_hook('complete_command', apt_completers, re_key = '.*apt-get')
70 ip.set_hook('complete_command', apt_completers, re_key = '.*yum')
71
72 pkg_cache = None
73
74 def module_completer(self,event):
75 """ Give completions after user has typed 'import' """
76
77 # only a local version for py 2.4, pkgutil has no walk_packages() there
78 if sys.version_info < (2,5):
79 for el in [f[:-3] for f in glob.glob("*.py")]:
80 yield el
81 return
82
83 global pkg_cache
84 import pkgutil,imp,time
85 #current =
86 if pkg_cache is None:
87 print "\n\n[Standby while scanning modules, this can take a while]\n\n"
88 pkg_cache = list(pkgutil.walk_packages())
89
90 already = set()
91 for ld, name, ispkg in pkg_cache:
92 if name.count('.') < event.symbol.count('.') + 1:
93 if name not in already:
94 already.add(name)
95 yield name + (ispkg and '.' or '')
96 return
97
98 ip.set_hook('complete_command', module_completer, str_key = 'import')
99 ip.set_hook('complete_command', module_completer, str_key = 'from')
100
101 svn_commands = """\
102 add blame praise annotate ann cat checkout co cleanup commit ci copy
103 cp delete del remove rm diff di export help ? h import info list ls
104 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
105 pe propget pget pg proplist plist pl propset pset ps resolved revert
106 status stat st switch sw unlock update
107 """
108
109 def svn_completer(self,event):
110 return vcs_completer(svn_commands, event)
111
112 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
113
114 hg_commands = """
115 add addremove annotate archive backout branch branches bundle cat
116 clone commit copy diff export grep heads help identify import incoming
117 init locate log manifest merge outgoing parents paths pull push
118 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
119 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
120 qselect qseries qtop qunapplied recover remove rename revert rollback
121 root serve showconfig status strip tag tags tip unbundle update verify
122 version
123 """
124
125 def hg_completer(self,event):
126 """ Completer for mercurial commands """
127
128 return vcs_completer(hg_commands, event)
129
130 ip.set_hook('complete_command', hg_completer, str_key = 'hg')
131
132
133 bzr_commands = """
134 add annotate bind branch break-lock bundle-revisions cat check
135 checkout commit conflicts deleted diff export gannotate gbranch
136 gcommit gdiff help ignore ignored info init init-repository inventory
137 log merge missing mkdir mv nick pull push reconcile register-branch
138 remerge remove renames resolve revert revno root serve sign-my-commits
139 status testament unbind uncommit unknowns update upgrade version
140 version-info visualise whoami
141 """
142
143 def bzr_completer(self,event):
144 """ Completer for bazaar commands """
145 cmd_param = event.line.split()
146 if event.line.endswith(' '):
147 cmd_param.append('')
148
149 if len(cmd_param) > 2:
150 cmd = cmd_param[1]
151 param = cmd_param[-1]
152 output_file = (param == '--output=')
153 if cmd == 'help':
154 return bzr_commands.split()
155 elif cmd in ['bundle-revisions','conflicts',
156 'deleted','nick','register-branch',
157 'serve','unbind','upgrade','version',
158 'whoami'] and not output_file:
159 return []
160 else:
161 # the rest are probably file names
162 return ip.IP.Completer.file_matches(event.symbol)
163
164 return bzr_commands.split()
165
166 ip.set_hook('complete_command', bzr_completer, str_key = 'bzr')
167
168
169 def runlistpy(self, event):
170 comps = shlex.split(event.line)
171 relpath = (len(comps) > 1 and comps[-1] or '')
172
173 #print "rp",relpath # dbg
174 lglob = glob.glob
175 isdir = os.path.isdir
176 if relpath.startswith('~'):
177 relpath = os.path.expanduser(relpath)
178 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
179 if isdir(f)]
180 pys = [f.replace('\\','/') for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy')]
181 return dirs + pys
182
183 ip.set_hook('complete_command', runlistpy, str_key = '%run')
184
185 def cd_completer(self, event):
186 relpath = event.symbol
187 #print event # dbg
188 if '-b' in event.line:
189 # return only bookmark completions
190 bkms = self.db.get('bookmarks',{})
191 return bkms.keys()
192
193
194 if event.symbol == '-':
195 # jump in directory history by number
196 ents = ['-%d [%s]' % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
197 if len(ents) > 1:
198 return ents
199 return []
200
201 if relpath.startswith('~'):
202 relpath = os.path.expanduser(relpath).replace('\\','/')
203 found = []
204 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
205 if os.path.isdir(f)]:
206 if ' ' in d:
207 # we don't want to deal with any of that, complex code
208 # for this is elsewhere
209 raise IPython.ipapi.TryNext
210 found.append( d )
211
212 if not found:
213 if os.path.isdir(relpath):
214 return [relpath]
215 raise IPython.ipapi.TryNext
216 return found
217
218 ip.set_hook('complete_command', cd_completer, str_key = '%cd')
@@ -1,61 +1,61 b''
1 """ Preliminary "job control" extensions for IPython
2
3 requires python 2.4 (or separate 'subprocess' module
4
5 At the moment this is in a very "unhelpful" form, will be extended in the future.
6
7 Usage:
8
9 [ipython]|2> import jobctrl
10 [ipython]|3> &ls
11 <3> <jobctrl.IpyPopen object at 0x00D87FD0>
12 [ipython]|4> _3.go
13 -----------> _3.go()
14 ChangeLog
15 IPython
16 MANIFEST.in
17 README
18 README_Windows.txt
19
20 ...
21 """
22
23 from subprocess import Popen,PIPE
24 import os
25
26 from IPython import genutils
27
28 import IPython.ipapi
29
30 class IpyPopen(Popen):
31 def go(self):
32 print self.communicate()[0]
33 def __repr__(self):
34 return '<IPython job "%s" PID=%d>' % (self.line, self.pid)
35
36 def kill(self):
37 assert os.name == 'nt' # xxx add posix version
38 os.system('taskkill /PID %d' % self.pid)
39
40 def startjob(job):
41 p = IpyPopen(job, stdout=PIPE, shell = False)
42 p.line = job
43 return p
44
45 def jobctrl_prefilter_f(self,line):
46 if line.startswith('&'):
47 pre,fn,rest = self.split_user_input(line[1:])
48
49 line = ip.IP.expand_aliases(fn,rest)
50 return '_ip.startjob(%s)' % genutils.make_quoted_expr(line)
51
52 raise IPython.ipapi.TryNext
53
54 def install():
55 global ip
56 ip = IPython.ipapi.get()
57 # needed to make startjob visible as _ip.startjob('blah')
58 ip.startjob = startjob
59 ip.set_hook('input_prefilter', jobctrl_prefilter_f)
60
1 """ Preliminary "job control" extensions for IPython
2
3 requires python 2.4 (or separate 'subprocess' module
4
5 At the moment this is in a very "unhelpful" form, will be extended in the future.
6
7 Usage:
8
9 [ipython]|2> import jobctrl
10 [ipython]|3> &ls
11 <3> <jobctrl.IpyPopen object at 0x00D87FD0>
12 [ipython]|4> _3.go
13 -----------> _3.go()
14 ChangeLog
15 IPython
16 MANIFEST.in
17 README
18 README_Windows.txt
19
20 ...
21 """
22
23 from subprocess import Popen,PIPE
24 import os,shlex
25
26 from IPython import genutils
27
28 import IPython.ipapi
29
30 class IpyPopen(Popen):
31 def go(self):
32 print self.communicate()[0]
33 def __repr__(self):
34 return '<IPython job "%s" PID=%d>' % (self.line, self.pid)
35
36 def kill(self):
37 assert os.name == 'nt' # xxx add posix version
38 os.system('taskkill /PID %d' % self.pid)
39
40 def startjob(job):
41 p = IpyPopen(shlex.split(job), stdout=PIPE, shell = False)
42 p.line = job
43 return p
44
45 def jobctrl_prefilter_f(self,line):
46 if line.startswith('&'):
47 pre,fn,rest = self.split_user_input(line[1:])
48
49 line = ip.IP.expand_aliases(fn,rest)
50 return '_ip.startjob(%s)' % genutils.make_quoted_expr(line)
51
52 raise IPython.ipapi.TryNext
53
54 def install():
55 global ip
56 ip = IPython.ipapi.get()
57 # needed to make startjob visible as _ip.startjob('blah')
58 ip.startjob = startjob
59 ip.set_hook('input_prefilter', jobctrl_prefilter_f)
60
61 61 install() No newline at end of file
@@ -1,98 +1,98 b''
1 """ Fun magic line editor for ipython
2
3 Use this to easily edit lists of strings gradually without crafting long
4 list comprehensions.
5
6 'l' is the magic variable name for every line (array element). Save the current
7 result (or more exactly, retrieve the last ipython computation result into
8 %led work area) by running '%led s'. Just run '%led' to show the current work
9 area data.
10
11 Example use:
12
13 [ipython]|25> setups = !ls *setup*.py
14 ==
15 ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
16 [ipython]|26> setups
17 <26> ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
18 [ipython]|27> %led s
19 Data set from last result (_)
20 <27> ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
21 [ipython]|28> %led upper
22 cmd translated => l.upper()
23 <28> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY']
24 [ipython]|29> %led
25 Magic line editor (for lists of strings)
26 current data is:
27 ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
28 [ipython]|30> %led upper
29 cmd translated => l.upper()
30 <30> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY']
31 [ipython]|31> %led s
32 Data set from last result (_)
33 <31> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY']
34 [ipython]|32> %led "n:" + l
35 <32> ['n:EGGSETUP.PY', 'n:SETUP.PY', 'n:SETUP_BDIST_EGG.PY']
36 [ipython]|33> %led s
37 Data set from last result (_)
38 <33> ['n:EGGSETUP.PY', 'n:SETUP.PY', 'n:SETUP_BDIST_EGG.PY']
39 [ipython]|34> %led l.
40 l.__add__ l.__gt__ l.__reduce_ex__ l.endswith l.join l.rstrip
41 l.__class__ l.__hash__ l.__repr__ l.expandtabs l.ljust l.split
42
43 ... (completions for string variable shown ) ...
44
45 """
46 import IPython.ipapi
47 import pprint
48 ip = IPython.ipapi.get()
49
50 curdata = []
51
52 def line_edit_f(self, cmd ):
53 global curdata
54
55 if not cmd:
56
57 print "Magic line editor (for lists of strings)"
58 if curdata:
59 print "current data is:"
60 pprint.pprint(curdata)
61 else:
62 print "No current data, you should set it by running '%led s'"
63 print "When you have your data in _ (result of last computation)."
64 return
65
66 if cmd == 's':
67 curdata = ip.ev('_')
68 print "Data set from last result (_)"
69 newlines = curdata
70
71 else:
72 # simple method call, e.g. upper
73 if cmd.isalpha():
74 cmd = 'l.' + cmd + '()'
75 print "cmd translated =>",cmd
76
77 newlines = []
78 for l in curdata:
79 try:
80 l2 = eval(cmd)
81 except Exception,e:
82 print "Dropping exception",e,"on line:",l
83 continue
84 newlines.append(l2)
85
86
87 return newlines
88
89 def line_edit_complete_f(self,event):
90 """ Show all string methods in completions """
91 if event.symbol.startswith('l.'):
92 return ['l.' + func for func in dir('')]
93
94 return dir('') + ['l.' + func for func in dir('')]
95
96 ip.set_hook('complete_command', line_edit_complete_f , str_key = '%led')
97
1 """ Fun magic line editor for ipython
2
3 Use this to easily edit lists of strings gradually without crafting long
4 list comprehensions.
5
6 'l' is the magic variable name for every line (array element). Save the current
7 result (or more exactly, retrieve the last ipython computation result into
8 %led work area) by running '%led s'. Just run '%led' to show the current work
9 area data.
10
11 Example use:
12
13 [ipython]|25> setups = !ls *setup*.py
14 ==
15 ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
16 [ipython]|26> setups
17 <26> ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
18 [ipython]|27> %led s
19 Data set from last result (_)
20 <27> ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
21 [ipython]|28> %led upper
22 cmd translated => l.upper()
23 <28> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY']
24 [ipython]|29> %led
25 Magic line editor (for lists of strings)
26 current data is:
27 ['eggsetup.py', 'setup.py', 'setup_bdist_egg.py']
28 [ipython]|30> %led upper
29 cmd translated => l.upper()
30 <30> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY']
31 [ipython]|31> %led s
32 Data set from last result (_)
33 <31> ['EGGSETUP.PY', 'SETUP.PY', 'SETUP_BDIST_EGG.PY']
34 [ipython]|32> %led "n:" + l
35 <32> ['n:EGGSETUP.PY', 'n:SETUP.PY', 'n:SETUP_BDIST_EGG.PY']
36 [ipython]|33> %led s
37 Data set from last result (_)
38 <33> ['n:EGGSETUP.PY', 'n:SETUP.PY', 'n:SETUP_BDIST_EGG.PY']
39 [ipython]|34> %led l.
40 l.__add__ l.__gt__ l.__reduce_ex__ l.endswith l.join l.rstrip
41 l.__class__ l.__hash__ l.__repr__ l.expandtabs l.ljust l.split
42
43 ... (completions for string variable shown ) ...
44
45 """
46 import IPython.ipapi
47 import pprint
48 ip = IPython.ipapi.get()
49
50 curdata = []
51
52 def line_edit_f(self, cmd ):
53 global curdata
54
55 if not cmd:
56
57 print "Magic line editor (for lists of strings)"
58 if curdata:
59 print "current data is:"
60 pprint.pprint(curdata)
61 else:
62 print "No current data, you should set it by running '%led s'"
63 print "When you have your data in _ (result of last computation)."
64 return
65
66 if cmd == 's':
67 curdata = ip.ev('_')
68 print "Data set from last result (_)"
69 newlines = curdata
70
71 else:
72 # simple method call, e.g. upper
73 if cmd.isalpha():
74 cmd = 'l.' + cmd + '()'
75 print "cmd translated =>",cmd
76
77 newlines = []
78 for l in curdata:
79 try:
80 l2 = eval(cmd)
81 except Exception,e:
82 print "Dropping exception",e,"on line:",l
83 continue
84 newlines.append(l2)
85
86
87 return newlines
88
89 def line_edit_complete_f(self,event):
90 """ Show all string methods in completions """
91 if event.symbol.startswith('l.'):
92 return ['l.' + func for func in dir('')]
93
94 return dir('') + ['l.' + func for func in dir('')]
95
96 ip.set_hook('complete_command', line_edit_complete_f , str_key = '%led')
97
98 98 ip.expose_magic('led', line_edit_f) No newline at end of file
@@ -1,7 +1,7 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Release data for the IPython project.
3 3
4 $Id: Release.py 1976 2006-12-08 11:53:57Z vivainio $"""
4 $Id: Release.py 2010 2006-12-20 15:29:17Z vivainio $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
@@ -22,12 +22,11 b" name = 'ipython'"
22 22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 23 # bdist_deb does not accept underscores (a Debian convention).
24 24
25 revision = '1975'
25 revision = '2007'
26 26
27 #version = '0.7.3.svn'
28
29 version = '0.7.3b3.r' + revision.rstrip('M')
27 version = '0.7.3'
30 28
29 #version = '0.7.3rc2.r' + revision.rstrip('M')
31 30
32 31 description = "An enhanced interactive Python shell."
33 32
@@ -1,54 +1,54 b''
1 # -*- coding: utf-8 -*-
2 """ Imports and provides the "correct" version of readline for the platform.
3
4 Readline is used throughout IPython as "import IPython.rlineimpl as readline.
5
6 In addition to normal readline stuff, this module provides have_readline boolean
7 and _outputfile variable used in genutils.
8
9 $Id: Magic.py 1096 2006-01-28 20:08:02Z vivainio $"""
10
11
12 import sys
13
14 have_readline = False
15
16 if sys.platform == 'win32':
17 try:
18 import pyreadline.rlmain
19 #add config for inputrcpath here:
20 #pyreadline.rlmain.config_path="c:/python/test_config.ini"
21 from readline import *
22 #print "Using the new pyreadline (thanks for participating in the testing!)"
23
24 have_readline = True
25
26 import readline as _rl
27 except ImportError:
28 #print "IPython team recommends the new pyreadline for Windows use, "
29 #print "It's superior especially with non-US keyboard layouts."
30 #print "Try installing it with 'easy_install pyreadline (ctypes is required) or"
31 #print "svn co http://ipython.scipy.org/svn/ipython/pyreadline/trunk pyreadline"
32 #print "Trying 'old' windows readline."
33 #print "Using 'old' readline, you might want to try pyreadline:"
34 #print "http://projects.scipy.org/ipython/ipython/wiki/PyReadline/Intro"
35 try:
36 from readline import *
37 import readline as _rl
38 have_readline = True
39 except ImportError:
40 pass
41
42 if have_readline:
43 try:
44 _outputfile=_rl.GetOutputFile()
45 except NameError:
46 print "Failed GetOutputFile"
47 have_readline = False
48
49 else:
50 try:
51 from readline import *
52 have_readline = True
53 except ImportError:
54 pass
1 # -*- coding: utf-8 -*-
2 """ Imports and provides the "correct" version of readline for the platform.
3
4 Readline is used throughout IPython as "import IPython.rlineimpl as readline.
5
6 In addition to normal readline stuff, this module provides have_readline boolean
7 and _outputfile variable used in genutils.
8
9 $Id: Magic.py 1096 2006-01-28 20:08:02Z vivainio $"""
10
11
12 import sys
13
14 have_readline = False
15
16 if sys.platform == 'win32':
17 try:
18 import pyreadline.rlmain
19 #add config for inputrcpath here:
20 #pyreadline.rlmain.config_path="c:/python/test_config.ini"
21 from readline import *
22 #print "Using the new pyreadline (thanks for participating in the testing!)"
23
24 have_readline = True
25
26 import readline as _rl
27 except ImportError:
28 #print "IPython team recommends the new pyreadline for Windows use, "
29 #print "It's superior especially with non-US keyboard layouts."
30 #print "Try installing it with 'easy_install pyreadline (ctypes is required) or"
31 #print "svn co http://ipython.scipy.org/svn/ipython/pyreadline/trunk pyreadline"
32 #print "Trying 'old' windows readline."
33 #print "Using 'old' readline, you might want to try pyreadline:"
34 #print "http://projects.scipy.org/ipython/ipython/wiki/PyReadline/Intro"
35 try:
36 from readline import *
37 import readline as _rl
38 have_readline = True
39 except ImportError:
40 pass
41
42 if have_readline:
43 try:
44 _outputfile=_rl.GetOutputFile()
45 except NameError:
46 print "Failed GetOutputFile"
47 have_readline = False
48
49 else:
50 try:
51 from readline import *
52 have_readline = True
53 except ImportError:
54 pass
@@ -1,65 +1,65 b''
1 from IPython.hooks import CommandChainDispatcher
2 import IPython.hooks
3
4 import re
5
6 class StrDispatch(object):
7 """ Dispatch (lookup) a set of strings / regexps for match """
8 def __init__(self):
9 self.strs = {}
10 self.regexs = {}
11 def add_s(self, s, obj, priority= 0 ):
12 """ Adds a target 'string' for dispatching """
13
14 chain = self.strs.get(s, CommandChainDispatcher())
15 chain.add(obj,priority)
16 self.strs[s] = chain
17
18 def add_re(self, regex, obj, priority= 0 ):
19 """ Adds a target regexp for dispatching """
20
21 chain = self.regexs.get(regex, CommandChainDispatcher())
22 chain.add(obj,priority)
23 self.regexs[regex] = chain
24
25 def dispatch(self, key):
26 """ Get a seq of Commandchain objects that match key """
27 if key in self.strs:
28 yield self.strs[key]
29
30 for r, obj in self.regexs.items():
31 if re.match(r, key):
32 yield obj
33 else:
34 #print "nomatch",key
35 pass
36
37
38 def __repr__(self):
39 return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
40
41 def s_matches(self, key):
42 if key not in self.strs:
43 return
44 for el in self.strs[key]:
45 yield el[1]
46
47
48 def flat_matches(self, key):
49 """ Yield all 'value' targets, without priority """
50 for val in self.dispatch(key):
51 for el in val:
52 yield el[1] # only value, no priority
53 return
54
55
56 def test():
57 d = StrDispatch()
58 d.add_s('hei',34, priority = 4)
59 d.add_s('hei',123, priority = 2)
60 print list(d.dispatch('hei'))
61 d.add_re('h.i', 686)
62 print list(d.flat_matches('hei'))
63
64 if __name__ == '__main__':
1 from IPython.hooks import CommandChainDispatcher
2 import IPython.hooks
3
4 import re
5
6 class StrDispatch(object):
7 """ Dispatch (lookup) a set of strings / regexps for match """
8 def __init__(self):
9 self.strs = {}
10 self.regexs = {}
11 def add_s(self, s, obj, priority= 0 ):
12 """ Adds a target 'string' for dispatching """
13
14 chain = self.strs.get(s, CommandChainDispatcher())
15 chain.add(obj,priority)
16 self.strs[s] = chain
17
18 def add_re(self, regex, obj, priority= 0 ):
19 """ Adds a target regexp for dispatching """
20
21 chain = self.regexs.get(regex, CommandChainDispatcher())
22 chain.add(obj,priority)
23 self.regexs[regex] = chain
24
25 def dispatch(self, key):
26 """ Get a seq of Commandchain objects that match key """
27 if key in self.strs:
28 yield self.strs[key]
29
30 for r, obj in self.regexs.items():
31 if re.match(r, key):
32 yield obj
33 else:
34 #print "nomatch",key
35 pass
36
37
38 def __repr__(self):
39 return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
40
41 def s_matches(self, key):
42 if key not in self.strs:
43 return
44 for el in self.strs[key]:
45 yield el[1]
46
47
48 def flat_matches(self, key):
49 """ Yield all 'value' targets, without priority """
50 for val in self.dispatch(key):
51 for el in val:
52 yield el[1] # only value, no priority
53 return
54
55
56 def test():
57 d = StrDispatch()
58 d.add_s('hei',34, priority = 4)
59 d.add_s('hei',123, priority = 2)
60 print list(d.dispatch('hei'))
61 d.add_re('h.i', 686)
62 print list(d.flat_matches('hei'))
63
64 if __name__ == '__main__':
65 65 test() No newline at end of file
@@ -1,94 +1,94 b''
1 #!/usr/bin/env python
2 """ A script/util to upgrade all files in a directory
3
4 This is rather conservative in its approach, only copying/overwriting
5 new and unedited files.
6
7 To be used by "upgrade" feature.
8 """
9 try:
10 from IPython.Extensions.path import path
11 except ImportError:
12 try:
13 from Extensions.path import path
14 except ImportError:
15 from path import path
16
17 import md5,pickle
18
19 def showdiff(old,new):
20 import difflib
21 d = difflib.Differ()
22 lines = d.compare(old.lines(),new.lines())
23 realdiff = False
24 for l in lines:
25 print l,
26 if not realdiff and not l[0].isspace():
27 realdiff = True
28 return realdiff
29
30 def upgrade_dir(srcdir, tgtdir):
31 """ Copy over all files in srcdir to tgtdir w/ native line endings
32
33 Creates .upgrade_report in tgtdir that stores md5sums of all files
34 to notice changed files b/w upgrades.
35 """
36
37 def pr(s):
38 print s
39
40 def ignorable(p):
41 if p.lower().startswith('.svn') or p.startswith('ipythonrc'):
42 return True
43 return False
44
45
46 modded = []
47 files = [path(srcdir).relpathto(p) for p in path(srcdir).walkfiles()]
48 #print files
49 rep = tgtdir / '.upgrade_report'
50 try:
51 rpt = pickle.load(rep.open())
52 except:
53 rpt = {}
54
55 for f in files:
56 if ignorable(f):
57 continue
58 src = srcdir / f
59 tgt = tgtdir / f
60 if not tgt.isfile():
61 pr("Creating %s" % str(tgt))
62
63 tgt.write_text(src.text())
64 rpt[str(tgt)] = md5.new(tgt.text()).hexdigest()
65 else:
66 cont = tgt.text()
67 sum = rpt.get(str(tgt), None)
68 #print sum
69 if sum and md5.new(cont).hexdigest() == sum:
70 pr("Unedited, installing new %s" % tgt)
71 tgt.write_text(src.text())
72 rpt[str(tgt)] = md5.new(tgt.text()).hexdigest()
73 else:
74 pr(' == Modified, skipping %s, diffs below == ' % tgt)
75 #rpt[str(tgt)] = md5.new(tgt.bytes()).hexdigest()
76 real = showdiff(tgt,src)
77 pr('') # empty line
78 if not real:
79 pr("(Ok, it wasn't that different at all, upgrading checksum)")
80 rpt[str(tgt)] = md5.new(tgt.text()).hexdigest()
81 else:
82 modded.append(tgt)
83
84 #print rpt
85 pickle.dump(rpt, rep.open('w'))
86 if modded:
87 print "\n\nDelete the following files manually (and rerun %upgrade)\nif you need a full upgrade:"
88 for m in modded:
89 print m
90
91
92 import sys
93 if __name__ == "__main__":
94 upgrade_dir(path(sys.argv[1]), path(sys.argv[2]))
1 #!/usr/bin/env python
2 """ A script/util to upgrade all files in a directory
3
4 This is rather conservative in its approach, only copying/overwriting
5 new and unedited files.
6
7 To be used by "upgrade" feature.
8 """
9 try:
10 from IPython.Extensions.path import path
11 except ImportError:
12 try:
13 from Extensions.path import path
14 except ImportError:
15 from path import path
16
17 import md5,pickle
18
19 def showdiff(old,new):
20 import difflib
21 d = difflib.Differ()
22 lines = d.compare(old.lines(),new.lines())
23 realdiff = False
24 for l in lines:
25 print l,
26 if not realdiff and not l[0].isspace():
27 realdiff = True
28 return realdiff
29
30 def upgrade_dir(srcdir, tgtdir):
31 """ Copy over all files in srcdir to tgtdir w/ native line endings
32
33 Creates .upgrade_report in tgtdir that stores md5sums of all files
34 to notice changed files b/w upgrades.
35 """
36
37 def pr(s):
38 print s
39
40 def ignorable(p):
41 if p.lower().startswith('.svn') or p.startswith('ipythonrc'):
42 return True
43 return False
44
45
46 modded = []
47 files = [path(srcdir).relpathto(p) for p in path(srcdir).walkfiles()]
48 #print files
49 rep = tgtdir / '.upgrade_report'
50 try:
51 rpt = pickle.load(rep.open())
52 except:
53 rpt = {}
54
55 for f in files:
56 if ignorable(f):
57 continue
58 src = srcdir / f
59 tgt = tgtdir / f
60 if not tgt.isfile():
61 pr("Creating %s" % str(tgt))
62
63 tgt.write_text(src.text())
64 rpt[str(tgt)] = md5.new(tgt.text()).hexdigest()
65 else:
66 cont = tgt.text()
67 sum = rpt.get(str(tgt), None)
68 #print sum
69 if sum and md5.new(cont).hexdigest() == sum:
70 pr("Unedited, installing new %s" % tgt)
71 tgt.write_text(src.text())
72 rpt[str(tgt)] = md5.new(tgt.text()).hexdigest()
73 else:
74 pr(' == Modified, skipping %s, diffs below == ' % tgt)
75 #rpt[str(tgt)] = md5.new(tgt.bytes()).hexdigest()
76 real = showdiff(tgt,src)
77 pr('') # empty line
78 if not real:
79 pr("(Ok, it wasn't that different at all, upgrading checksum)")
80 rpt[str(tgt)] = md5.new(tgt.text()).hexdigest()
81 else:
82 modded.append(tgt)
83
84 #print rpt
85 pickle.dump(rpt, rep.open('w'))
86 if modded:
87 print "\n\nDelete the following files manually (and rerun %upgrade)\nif you need a full upgrade:"
88 for m in modded:
89 print m
90
91
92 import sys
93 if __name__ == "__main__":
94 upgrade_dir(path(sys.argv[1]), path(sys.argv[2]))
@@ -6,7 +6,7 b''
6 6 # the file COPYING, distributed as part of this software.
7 7 #*****************************************************************************
8 8
9 # $Id: usage.py 1332 2006-05-30 01:41:28Z fperez $
9 # $Id: usage.py 2010 2006-12-20 15:29:17Z vivainio $
10 10
11 11 from IPython import Release
12 12 __author__ = '%s <%s>' % Release.authors['Fernando']
@@ -623,7 +623,8 b" cd /usr/share : Obvious, also 'cd d:\\home\\_ipython' works"
623 623 History:
624 624
625 625 _i, _ii, _iii : Previous, next previous, next next previous input
626 _ih[4], _ih[2:5] : Input history line 4, lines 2-4
626 _i4, _ih[2:5] : Input history line 4, lines 2-4
627 exec _i81 : Execute input history line #81 again
627 628 _, __, ___ : previous, next previous, next next previous output
628 629 _dh : Directory history
629 630 _oh : Output history
@@ -1,3 +1,32 b''
1 2006-12-20 Ville Vainio <vivainio@gmail.com>
2
3 * 0.7.3 is out - merge all from 0.7.3 branch to trunk
4
5 2006-12-17 Ville Vainio <vivainio@gmail.com>
6
7 * Extensions/jobctrl.py: Fixed &cmd arg arg...
8 to work properly on posix too
9
10 * Release.py: Update revnum (version is still just 0.7.3).
11
12 2006-12-15 Ville Vainio <vivainio@gmail.com>
13
14 * scripts/ipython_win_post_install: create ipython.py in
15 prefix + "/scripts".
16
17 * Release.py: Update version to 0.7.3.
18
19 2006-12-14 Ville Vainio <vivainio@gmail.com>
20
21 * scripts/ipython_win_post_install: Overwrite old shortcuts
22 if they already exist
23
24 * Release.py: release 0.7.3rc2
25
26 2006-12-13 Ville Vainio <vivainio@gmail.com>
27
28 * Branch and update Release.py for 0.7.3rc1
29
1 30 2006-12-13 Fernando Perez <Fernando.Perez@colorado.edu>
2 31
3 32 * IPython/Shell.py (IPShellWX): update for current WX naming
@@ -1,15 +1,15 b''
1 import os
2
3
4 editor = r'q:/opt/np/notepad++.exe'
5
6
7 e = os.environ
8
9 e['EDITOR'] = editor
10 e['VISUAL'] = editor
11
12
13
14
15
1 import os
2
3
4 editor = r'q:/opt/np/notepad++.exe'
5
6
7 e = os.environ
8
9 e['EDITOR'] = editor
10 e['VISUAL'] = editor
11
12
13
14
15
@@ -1,14 +1,13 b''
1 1 #!python
2 2 """Windows-specific part of the installation"""
3 3
4 import os, sys
4 import os, sys, shutil
5 5
6 def create_shortcut_safe(target,description,link_file,*args,**kw):
6 def mkshortcut(target,description,link_file,*args,**kw):
7 7 """make a shortcut if it doesn't exist, and register its creation"""
8 8
9 if not os.path.isfile(link_file):
10 create_shortcut(target, description, link_file,*args,**kw)
11 file_created(link_file)
9 create_shortcut(target, description, link_file,*args,**kw)
10 file_created(link_file)
12 11
13 12 def install():
14 13 """Routine to be run by the win32 installer with the -install switch."""
@@ -49,21 +48,24 b' def install():'
49 48 # Create program shortcuts ...
50 49 f = ip_dir + r'\IPython.lnk'
51 50 a = prefix + r'\scripts\ipython'
52 create_shortcut_safe(python,'IPython',f,a)
51 mkshortcut(python,'IPython',f,a)
53 52
54 53 f = ip_dir + r'\pysh.lnk'
55 a = prefix + r'\scripts\ipython -p pysh'
56 create_shortcut_safe(python,'pysh',f,a)
54 a = prefix + r'\scripts\ipython -p sh'
55 mkshortcut(python,'IPython command prompt mode',f,a)
57 56
58 57 # Create documentation shortcuts ...
59 58 t = prefix + r'\share\doc\ipython-%s\manual.pdf' % version
60 59 f = ip_dir + r'\Manual in PDF.lnk'
61 create_shortcut_safe(t,r'IPython Manual - PDF-Format',f)
60 mkshortcut(t,r'IPython Manual - PDF-Format',f)
62 61
63 62 t = prefix + r'\share\doc\ipython-%s\manual\manual.html' % version
64 63 f = ip_dir + r'\Manual in HTML.lnk'
65 create_shortcut_safe(t,'IPython Manual - HTML-Format',f)
64 mkshortcut(t,'IPython Manual - HTML-Format',f)
66 65
66 # make ipython.py
67 shutil.copy(prefix + r'\scripts\ipython', prefix + r'\scripts\ipython.py')
68
67 69 def remove():
68 70 """Routine to be run by the win32 installer with the -remove switch."""
69 71 pass
@@ -1,100 +1,100 b''
1 # -*- coding: UTF-8 -*-
2 import sys, unittest
3 sys.path.append ('..')
4
5 from IPython import wildcard
6
7 class obj_t(object):
8 pass
9
10 root=obj_t()
11 l=["arna","abel","ABEL","active","bob","bark","abbot"]
12 q=["kate","loop","arne","vito","lucifer","koppel"]
13 for x in l:
14 o=obj_t()
15 setattr(root,x,o)
16 for y in q:
17 p=obj_t()
18 setattr(o,y,p)
19 root._apan=obj_t()
20 root._apan.a=10
21 root._apan._a=20
22 root._apan.__a=20
23 root.__anka=obj_t()
24 root.__anka.a=10
25 root.__anka._a=20
26 root.__anka.__a=20
27
28 root._APAN=obj_t()
29 root._APAN.a=10
30 root._APAN._a=20
31 root._APAN.__a=20
32 root.__ANKA=obj_t()
33 root.__ANKA.a=10
34 root.__ANKA._a=20
35 root.__ANKA.__a=20
36
37 class Tests (unittest.TestCase):
38 def test_case(self):
39 ns=root.__dict__
40 tests=[
41 ("a*", ["abbot","abel","active","arna",]),
42 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
43 ("_a*", []),
44 ("_*anka", ["__anka",]),
45 ("_*a*", ["__anka",]),
46 ]
47 for pat,res in tests:
48 res.sort()
49 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,show_all=False).keys()
50 a.sort()
51 self.assertEqual(a,res)
52
53 def test_case_showall(self):
54 ns=root.__dict__
55 tests=[
56 ("a*", ["abbot","abel","active","arna",]),
57 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
58 ("_a*", ["_apan"]),
59 ("_*anka", ["__anka",]),
60 ("_*a*", ["__anka","_apan",]),
61 ]
62 for pat,res in tests:
63 res.sort()
64 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,show_all=True).keys()
65 a.sort()
66 self.assertEqual(a,res)
67
68
69 def test_nocase(self):
70 ns=root.__dict__
71 tests=[
72 ("a*", ["abbot","abel","ABEL","active","arna",]),
73 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop","ABEL.koppel","ABEL.loop",]),
74 ("_a*", []),
75 ("_*anka", ["__anka","__ANKA",]),
76 ("_*a*", ["__anka","__ANKA",]),
77 ]
78 for pat,res in tests:
79 res.sort()
80 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,show_all=False).keys()
81 a.sort()
82 self.assertEqual(a,res)
83
84 def test_nocase_showall(self):
85 ns=root.__dict__
86 tests=[
87 ("a*", ["abbot","abel","ABEL","active","arna",]),
88 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop","ABEL.koppel","ABEL.loop",]),
89 ("_a*", ["_apan","_APAN"]),
90 ("_*anka", ["__anka","__ANKA",]),
91 ("_*a*", ["__anka","__ANKA","_apan","_APAN"]),
92 ]
93 for pat,res in tests:
94 res.sort()
95 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,show_all=True).keys()
96 a.sort()
97 self.assertEqual(a,res)
98
99 if __name__ == '__main__':
1 # -*- coding: UTF-8 -*-
2 import sys, unittest
3 sys.path.append ('..')
4
5 from IPython import wildcard
6
7 class obj_t(object):
8 pass
9
10 root=obj_t()
11 l=["arna","abel","ABEL","active","bob","bark","abbot"]
12 q=["kate","loop","arne","vito","lucifer","koppel"]
13 for x in l:
14 o=obj_t()
15 setattr(root,x,o)
16 for y in q:
17 p=obj_t()
18 setattr(o,y,p)
19 root._apan=obj_t()
20 root._apan.a=10
21 root._apan._a=20
22 root._apan.__a=20
23 root.__anka=obj_t()
24 root.__anka.a=10
25 root.__anka._a=20
26 root.__anka.__a=20
27
28 root._APAN=obj_t()
29 root._APAN.a=10
30 root._APAN._a=20
31 root._APAN.__a=20
32 root.__ANKA=obj_t()
33 root.__ANKA.a=10
34 root.__ANKA._a=20
35 root.__ANKA.__a=20
36
37 class Tests (unittest.TestCase):
38 def test_case(self):
39 ns=root.__dict__
40 tests=[
41 ("a*", ["abbot","abel","active","arna",]),
42 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
43 ("_a*", []),
44 ("_*anka", ["__anka",]),
45 ("_*a*", ["__anka",]),
46 ]
47 for pat,res in tests:
48 res.sort()
49 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,show_all=False).keys()
50 a.sort()
51 self.assertEqual(a,res)
52
53 def test_case_showall(self):
54 ns=root.__dict__
55 tests=[
56 ("a*", ["abbot","abel","active","arna",]),
57 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
58 ("_a*", ["_apan"]),
59 ("_*anka", ["__anka",]),
60 ("_*a*", ["__anka","_apan",]),
61 ]
62 for pat,res in tests:
63 res.sort()
64 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,show_all=True).keys()
65 a.sort()
66 self.assertEqual(a,res)
67
68
69 def test_nocase(self):
70 ns=root.__dict__
71 tests=[
72 ("a*", ["abbot","abel","ABEL","active","arna",]),
73 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop","ABEL.koppel","ABEL.loop",]),
74 ("_a*", []),
75 ("_*anka", ["__anka","__ANKA",]),
76 ("_*a*", ["__anka","__ANKA",]),
77 ]
78 for pat,res in tests:
79 res.sort()
80 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,show_all=False).keys()
81 a.sort()
82 self.assertEqual(a,res)
83
84 def test_nocase_showall(self):
85 ns=root.__dict__
86 tests=[
87 ("a*", ["abbot","abel","ABEL","active","arna",]),
88 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop","ABEL.koppel","ABEL.loop",]),
89 ("_a*", ["_apan","_APAN"]),
90 ("_*anka", ["__anka","__ANKA",]),
91 ("_*a*", ["__anka","__ANKA","_apan","_APAN"]),
92 ]
93 for pat,res in tests:
94 res.sort()
95 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,show_all=True).keys()
96 a.sort()
97 self.assertEqual(a,res)
98
99 if __name__ == '__main__':
100 100 unittest.main() No newline at end of file
@@ -1,15 +1,15 b''
1 from path import path
2 fs = path('..').walkfiles('*.py')
3
4 for f in fs:
5 errs = ''
6 cont = f.bytes()
7 if '\t' in cont:
8 errs+='t'
9
10 if '\r' in cont:
11 errs+='r'
12
13 if errs:
14 print "%3s" % errs, f
1 from path import path
2 fs = path('..').walkfiles('*.py')
3
4 for f in fs:
5 errs = ''
6 cont = f.bytes()
7 if '\t' in cont:
8 errs+='t'
9
10 if '\r' in cont:
11 errs+='r'
12
13 if errs:
14 print "%3s" % errs, f
15 15 No newline at end of file
@@ -1,6 +1,6 b''
1 1 import os,sys,shutil
2 2
3 repo = "http://ipython.scipy.org/svn/ipython/ipython/trunk"
3 repo = "http://ipython.scipy.org/svn/ipython/ipython/branches/0.7.3"
4 4 basename = 'ipython'
5 5 workdir = './mkdist'
6 6
@@ -1,13 +1,13 b''
1 """ Change the revision number in Release.py """
2
3 import os
4 import re
5
6 rev = os.popen('svnversion ..').read().strip()
7
8 print "current rev is",rev
9 assert ':' not in rev
10
11 rfile = open('../IPython/Release.py').read()
12 newcont = re.sub(r'revision\s*=.*', "revision = '%s'" % rev, rfile)
13 open('../IPython/Release.py','w').write(newcont)
1 """ Change the revision number in Release.py """
2
3 import os
4 import re
5
6 rev = os.popen('svnversion ..').read().strip()
7
8 print "current rev is",rev
9 assert ':' not in rev
10
11 rfile = open('../IPython/Release.py').read()
12 newcont = re.sub(r'revision\s*=.*', "revision = '%s'" % rev, rfile)
13 open('../IPython/Release.py','w').write(newcont)
General Comments 0
You need to be logged in to leave comments. Login now