1 """Definitions used by commands sent to inferior Python in python.el."""
3 # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4 # Author: Dave Love <fx@gnu.org>
6 # This file is part of GNU Emacs.
8 # GNU Emacs is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # GNU Emacs is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21 import os
, sys
, traceback
, inspect
, __main__
26 from sets
import Set
as set
28 __all__
= ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"]
30 def format_exception (filename
, should_remove_self
):
31 type, value
, tb
= sys
.exc_info ()
33 sys
.last_value
= value
34 sys
.last_traceback
= tb
35 if type is SyntaxError:
36 try: # parse the error message
37 msg
, (dummy_filename
, lineno
, offset
, line
) = value
39 pass # Not the format we expect; leave it alone
41 # Stuff in the right filename
42 value
= SyntaxError(msg
, (filename
, lineno
, offset
, line
))
43 sys
.last_value
= value
44 res
= traceback
.format_exception_only (type, value
)
45 # There are some compilation errors which do not provide traceback so we
46 # should not massage it.
47 if should_remove_self
:
48 tblist
= traceback
.extract_tb (tb
)
50 res
= traceback
.format_list (tblist
)
52 res
.insert(0, "Traceback (most recent call last):\n")
53 res
[len(res
):] = traceback
.format_exception_only (type, value
)
54 # traceback.print_exception(type, value, tb)
55 for line
in res
: print line
,
58 """Execute FILE and then remove it.
59 Execute the file within the __main__ namespace.
60 If we get an exception, print a traceback with the top frame
61 (ourselves) excluded."""
62 # We cannot use real execfile since it has a bug where the file stays
63 # locked forever (under w32) if SyntaxError occurs.
64 # --- code based on code.py and PyShell.py.
67 source
= open (file, "r").read()
68 code
= compile (source
, file, "exec")
69 # Other exceptions (shouldn't be any...) will (correctly) fall
71 except (OverflowError, SyntaxError, ValueError):
72 # FIXME: When can compile() raise anything else than
74 format_exception (file, False)
77 exec code
in __main__
.__dict
__
79 format_exception (file, True)
83 def eargs (name
, imports
):
84 "Get arglist of NAME for Eldoc &c."
86 if imports
: exec imports
87 parts
= name
.split ('.')
89 exec 'import ' + parts
[0] # might fail
91 if inspect
.isbuiltin (func
) or type(func
) is type:
93 if doc
.find (' ->') != -1:
94 print '_emacs_out', doc
.split (' ->')[0]
96 print '_emacs_out', doc
.split ('\n')[0]
98 if inspect
.ismethod (func
):
100 if not inspect
.isfunction (func
):
103 (args
, varargs
, varkw
, defaults
) = inspect
.getargspec (func
)
104 # No space between name and arglist for consistency with builtins.
105 print '_emacs_out', \
106 func
.__name
__ + inspect
.formatargspec (args
, varargs
, varkw
,
111 def all_names (object):
112 """Return (an approximation to) a list of all possible attribute
113 names reachable via the attributes of OBJECT, i.e. roughly the
114 leaves of the dictionary tree under it."""
116 def do_object (object, names
):
117 if inspect
.ismodule (object):
118 do_module (object, names
)
119 elif inspect
.isclass (object):
120 do_class (object, names
)
121 # Might have an object without its class in scope.
122 elif hasattr (object, '__class__'):
123 names
.add ('__class__')
124 do_class (object.__class
__, names
)
125 # Probably not a good idea to try to enumerate arbitrary
129 def do_module (module
, names
):
130 if hasattr (module
, '__all__'): # limited export list
131 names
.update(module
.__all
__)
132 for i
in module
.__all
__:
133 do_object (getattr (module
, i
), names
)
134 else: # use all names
135 names
.update(dir (module
))
136 for i
in dir (module
):
137 do_object (getattr (module
, i
), names
)
140 def do_class (object, names
):
143 if hasattr (object, '__bases__'): # superclasses
144 for i
in object.__bases
__: do_object (i
, names
)
147 return do_object (object, set([]))
149 def complete (name
, imports
):
150 """Complete TEXT in NAMESPACE and print a Lisp list of completions.
151 Exec IMPORTS first."""
152 import __main__
, keyword
154 def class_members(object):
156 if hasattr (object, '__bases__'):
157 for super in object.__bases
__:
158 names
= class_members (super)
164 dict = __main__
.__dict
__.copy()
165 if imports
: exec imports
in dict
168 for src
in [dir (__builtins__
), keyword
.kwlist
, dict.keys()]:
170 if elt
[:l
] == name
: names
.add(elt
)
172 base
= name
[:name
.rfind ('.')]
173 name
= name
[name
.rfind('.')+1:]
175 object = eval (base
, dict)
176 names
= set(dir (object))
177 if hasattr (object, '__class__'):
178 names
.add('__class__')
179 names
.update(class_members (object))
180 except: names
= all_names (dict)
186 print '_emacs_out (',
189 if base
: print '"%s.%s"' % (base
, n
),
190 else: print '"%s"' % n
,
193 def ehelp (name
, imports
):
194 """Get help on string NAME.
195 First try to eval name for, e.g. user definitions where we need
196 the object. Otherwise try the string form."""
199 try: exec imports
in locls
201 try: help (eval (name
, globals(), locls
))
204 def eimport (mod
, dir):
205 """Import module MOD with directory DIR at the head of the search path.
206 NB doesn't load from DIR if MOD shadows a system module."""
207 from __main__
import __dict__
213 if __dict__
.has_key(mod
) and inspect
.ismodule (__dict__
[mod
]):
214 reload (__dict__
[mod
])
216 __dict__
[mod
] = __import__ (mod
)
218 (type, value
, tb
) = sys
.exc_info ()
219 print "Traceback (most recent call last):"
220 traceback
.print_exception (type, value
, tb
.tb_next
)
224 def modpath (module
):
225 """Return the source file for the given MODULE (or None).
226 Assumes that MODULE.py and MODULE.pyc are in the same directory."""
228 path
= __import__ (module
).__file
__
229 if path
[-4:] == '.pyc' and os
.path
.exists (path
[0:-1]):
231 print "_emacs_out", path
233 print "_emacs_out ()"
235 # print '_emacs_ok' # ready for input and can call continuation
237 # arch-tag: d90408f3-90e2-4de4-99c2-6eb9c7b9ca46