1 """Definitions used by commands sent to inferior Python in python.el."""
3 # Copyright (C) 2004, 2005, 2006, 2007 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, or (at your option)
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; see the file COPYING. If not, write to the
20 # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 # Boston, MA 02110-1301, USA.
23 import os
, sys
, traceback
, inspect
, __main__
28 from sets
import Set
as set
30 __all__
= ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"]
32 def format_exception (filename
, should_remove_self
):
33 type, value
, tb
= sys
.exc_info ()
35 sys
.last_value
= value
36 sys
.last_traceback
= tb
37 if type is SyntaxError:
38 try: # parse the error message
39 msg
, (dummy_filename
, lineno
, offset
, line
) = value
41 pass # Not the format we expect; leave it alone
43 # Stuff in the right filename
44 value
= SyntaxError(msg
, (filename
, lineno
, offset
, line
))
45 sys
.last_value
= value
46 res
= traceback
.format_exception_only (type, value
)
47 # There are some compilation errors which do not provide traceback so we
48 # should not massage it.
49 if should_remove_self
:
50 tblist
= traceback
.extract_tb (tb
)
52 res
= traceback
.format_list (tblist
)
54 res
.insert(0, "Traceback (most recent call last):\n")
55 res
[len(res
):] = traceback
.format_exception_only (type, value
)
56 # traceback.print_exception(type, value, tb)
57 for line
in res
: print line
,
60 """Execute FILE and then remove it.
61 Execute the file within the __main__ namespace.
62 If we get an exception, print a traceback with the top frame
63 (ourselves) excluded."""
64 # We cannot use real execfile since it has a bug where the file stays
65 # locked forever (under w32) if SyntaxError occurs.
66 # --- code based on code.py and PyShell.py.
69 source
= open (file, "r").read()
70 code
= compile (source
, file, "exec")
71 # Other exceptions (shouldn't be any...) will (correctly) fall
73 except (OverflowError, SyntaxError, ValueError):
74 # FIXME: When can compile() raise anything else than
76 format_exception (file, False)
79 exec code
in __main__
.__dict
__
81 format_exception (file, True)
85 def eargs (name
, imports
):
86 "Get arglist of NAME for Eldoc &c."
88 if imports
: exec imports
89 parts
= name
.split ('.')
91 exec 'import ' + parts
[0] # might fail
93 if inspect
.isbuiltin (func
) or type(func
) is type:
95 if doc
.find (' ->') != -1:
96 print '_emacs_out', doc
.split (' ->')[0]
98 print '_emacs_out', doc
.split ('\n')[0]
100 if inspect
.ismethod (func
):
102 if not inspect
.isfunction (func
):
105 (args
, varargs
, varkw
, defaults
) = inspect
.getargspec (func
)
106 # No space between name and arglist for consistency with builtins.
107 print '_emacs_out', \
108 func
.__name
__ + inspect
.formatargspec (args
, varargs
, varkw
,
113 def all_names (object):
114 """Return (an approximation to) a list of all possible attribute
115 names reachable via the attributes of OBJECT, i.e. roughly the
116 leaves of the dictionary tree under it."""
118 def do_object (object, names
):
119 if inspect
.ismodule (object):
120 do_module (object, names
)
121 elif inspect
.isclass (object):
122 do_class (object, names
)
123 # Might have an object without its class in scope.
124 elif hasattr (object, '__class__'):
125 names
.add ('__class__')
126 do_class (object.__class
__, names
)
127 # Probably not a good idea to try to enumerate arbitrary
131 def do_module (module
, names
):
132 if hasattr (module
, '__all__'): # limited export list
133 names
.update(module
.__all
__)
134 for i
in module
.__all
__:
135 do_object (getattr (module
, i
), names
)
136 else: # use all names
137 names
.update(dir (module
))
138 for i
in dir (module
):
139 do_object (getattr (module
, i
), names
)
142 def do_class (object, names
):
145 if hasattr (object, '__bases__'): # superclasses
146 for i
in object.__bases
__: do_object (i
, names
)
149 return do_object (object, set([]))
151 def complete (name
, imports
):
152 """Complete TEXT in NAMESPACE and print a Lisp list of completions.
153 Exec IMPORTS first."""
154 import __main__
, keyword
156 def class_members(object):
158 if hasattr (object, '__bases__'):
159 for super in object.__bases
__:
160 names
= class_members (super)
166 dict = __main__
.__dict
__.copy()
167 if imports
: exec imports
in dict
170 for src
in [dir (__builtins__
), keyword
.kwlist
, dict.keys()]:
172 if elt
[:l
] == name
: names
.add(elt
)
174 base
= name
[:name
.rfind ('.')]
175 name
= name
[name
.rfind('.')+1:]
177 object = eval (base
, dict)
178 names
= set(dir (object))
179 if hasattr (object, '__class__'):
180 names
.add('__class__')
181 names
.update(class_members (object))
182 except: names
= all_names (dict)
188 print '_emacs_out (',
191 if base
: print '"%s.%s"' % (base
, n
),
192 else: print '"%s"' % n
,
195 def ehelp (name
, imports
):
196 """Get help on string NAME.
197 First try to eval name for, e.g. user definitions where we need
198 the object. Otherwise try the string form."""
201 try: exec imports
in locls
203 try: help (eval (name
, globals(), locls
))
206 def eimport (mod
, dir):
207 """Import module MOD with directory DIR at the head of the search path.
208 NB doesn't load from DIR if MOD shadows a system module."""
209 from __main__
import __dict__
215 if __dict__
.has_key(mod
) and inspect
.ismodule (__dict__
[mod
]):
216 reload (__dict__
[mod
])
218 __dict__
[mod
] = __import__ (mod
)
220 (type, value
, tb
) = sys
.exc_info ()
221 print "Traceback (most recent call last):"
222 traceback
.print_exception (type, value
, tb
.tb_next
)
226 def modpath (module
):
227 """Return the source file for the given MODULE (or None).
228 Assumes that MODULE.py and MODULE.pyc are in the same directory."""
230 path
= __import__ (module
).__file
__
231 if path
[-4:] == '.pyc' and os
.path
.exists (path
[0:-1]):
233 print "_emacs_out", path
235 print "_emacs_out ()"
237 # print '_emacs_ok' # ready for input and can call continuation
239 # arch-tag: d90408f3-90e2-4de4-99c2-6eb9c7b9ca46