2 Warning: This file is automatically generated from emacs2.py with the
3 2to3 script. Do not hand edit.
6 """Definitions used by commands sent to inferior Python in python.el."""
8 # Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
9 # Author: Dave Love <fx@gnu.org>
11 # This file is part of GNU Emacs.
13 # GNU Emacs is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 3, or (at your option)
18 # GNU Emacs is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with GNU Emacs; see the file COPYING. If not, write to the
25 # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 # Boston, MA 02110-1301, USA.
28 import os
, sys
, traceback
, inspect
, __main__
33 from sets
import Set
as set
35 __all__
= ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"]
37 def format_exception (filename
, should_remove_self
):
38 type, value
, tb
= sys
.exc_info ()
40 sys
.last_value
= value
41 sys
.last_traceback
= tb
42 if type is SyntaxError:
43 try: # parse the error message
44 msg
, (dummy_filename
, lineno
, offset
, line
) = value
46 pass # Not the format we expect; leave it alone
48 # Stuff in the right filename
49 value
= SyntaxError(msg
, (filename
, lineno
, offset
, line
))
50 sys
.last_value
= value
51 res
= traceback
.format_exception_only (type, value
)
52 # There are some compilation errors which do not provide traceback so we
53 # should not massage it.
54 if should_remove_self
:
55 tblist
= traceback
.extract_tb (tb
)
57 res
= traceback
.format_list (tblist
)
59 res
.insert(0, "Traceback (most recent call last):\n")
60 res
[len(res
):] = traceback
.format_exception_only (type, value
)
61 # traceback.print_exception(type, value, tb)
62 for line
in res
: print(line
, end
=' ')
65 """Execute FILE and then remove it.
66 Execute the file within the __main__ namespace.
67 If we get an exception, print a traceback with the top frame
68 (ourselves) excluded."""
69 # We cannot use real execfile since it has a bug where the file stays
70 # locked forever (under w32) if SyntaxError occurs.
71 # --- code based on code.py and PyShell.py.
74 source
= open (file, "r").read()
75 code
= compile (source
, file, "exec")
76 # Other exceptions (shouldn't be any...) will (correctly) fall
78 except (OverflowError, SyntaxError, ValueError):
79 # FIXME: When can compile() raise anything else than
81 format_exception (file, False)
84 exec(code
, __main__
.__dict
__)
86 format_exception (file, True)
90 def eargs (name
, imports
):
91 "Get arglist of NAME for Eldoc &c."
93 if imports
: exec(imports
)
94 parts
= name
.split ('.')
96 exec('import ' + parts
[0]) # might fail
98 if inspect
.isbuiltin (func
) or type(func
) is type:
100 if doc
.find (' ->') != -1:
101 print('_emacs_out', doc
.split (' ->')[0])
103 print('_emacs_out', doc
.split ('\n')[0])
105 if inspect
.ismethod (func
):
107 if not inspect
.isfunction (func
):
110 (args
, varargs
, varkw
, defaults
) = inspect
.getargspec (func
)
111 # No space between name and arglist for consistency with builtins.
112 print('_emacs_out', \
113 func
.__name
__ + inspect
.formatargspec (args
, varargs
, varkw
,
118 def all_names (object):
119 """Return (an approximation to) a list of all possible attribute
120 names reachable via the attributes of OBJECT, i.e. roughly the
121 leaves of the dictionary tree under it."""
123 def do_object (object, names
):
124 if inspect
.ismodule (object):
125 do_module (object, names
)
126 elif inspect
.isclass (object):
127 do_class (object, names
)
128 # Might have an object without its class in scope.
129 elif hasattr (object, '__class__'):
130 names
.add ('__class__')
131 do_class (object.__class
__, names
)
132 # Probably not a good idea to try to enumerate arbitrary
136 def do_module (module
, names
):
137 if hasattr (module
, '__all__'): # limited export list
138 names
.update(module
.__all
__)
139 for i
in module
.__all
__:
140 do_object (getattr (module
, i
), names
)
141 else: # use all names
142 names
.update(dir (module
))
143 for i
in dir (module
):
144 do_object (getattr (module
, i
), names
)
147 def do_class (object, names
):
150 if hasattr (object, '__bases__'): # superclasses
151 for i
in object.__bases
__: do_object (i
, names
)
154 return do_object (object, set([]))
156 def complete (name
, imports
):
157 """Complete TEXT in NAMESPACE and print a Lisp list of completions.
158 Exec IMPORTS first."""
159 import __main__
, keyword
161 def class_members(object):
163 if hasattr (object, '__bases__'):
164 for super in object.__bases
__:
165 names
= class_members (super)
171 dict = __main__
.__dict
__.copy()
172 if imports
: exec(imports
, dict)
175 for src
in [dir (__builtins__
), keyword
.kwlist
, list(dict.keys())]:
177 if elt
[:l
] == name
: names
.add(elt
)
179 base
= name
[:name
.rfind ('.')]
180 name
= name
[name
.rfind('.')+1:]
182 object = eval (base
, dict)
183 names
= set(dir (object))
184 if hasattr (object, '__class__'):
185 names
.add('__class__')
186 names
.update(class_members (object))
187 except: names
= all_names (dict)
189 print(sys
.exc_info())
193 print('_emacs_out (', end
=' ')
196 if base
: print('"%s.%s"' % (base
, n
), end
=' ')
197 else: print('"%s"' % n
, end
=' ')
200 def ehelp (name
, imports
):
201 """Get help on string NAME.
202 First try to eval name for, e.g. user definitions where we need
203 the object. Otherwise try the string form."""
206 try: exec(imports
, locls
)
208 try: help (eval (name
, globals(), locls
))
211 def eimport (mod
, dir):
212 """Import module MOD with directory DIR at the head of the search path.
213 NB doesn't load from DIR if MOD shadows a system module."""
214 from __main__
import __dict__
220 if mod
in __dict__
and inspect
.ismodule (__dict__
[mod
]):
221 reload (__dict__
[mod
])
223 __dict__
[mod
] = __import__ (mod
)
225 (type, value
, tb
) = sys
.exc_info ()
226 print("Traceback (most recent call last):")
227 traceback
.print_exception (type, value
, tb
.tb_next
)
231 def modpath (module
):
232 """Return the source file for the given MODULE (or None).
233 Assumes that MODULE.py and MODULE.pyc are in the same directory."""
235 path
= __import__ (module
).__file
__
236 if path
[-4:] == '.pyc' and os
.path
.exists (path
[0:-1]):
238 print("_emacs_out", path
)
240 print("_emacs_out ()")
242 # print '_emacs_ok' # ready for input and can call continuation
244 # arch-tag: 37bfed38-5f4a-4027-a2bf-d5f41819dd89