1 """Definitions used by commands sent to inferior Python in python.el."""
3 # Copyright (C) 2004, 2005, 2006 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 2, 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__
26 __all__
= ["eexecfile", "eargs", "complete", "ehelp", "eimport", "modpath"]
29 """Execute FILE and then remove it.
30 Execute the file within the __main__ namespace.
31 If we get an exception, print a traceback with the top frame
32 (ourselves) excluded."""
34 try: execfile (file, __main__
.__dict
__)
36 (type, value
, tb
) = sys
.exc_info ()
37 # Lose the stack frame for this location.
39 if tb
is None: # print_exception won't do it
40 print "Traceback (most recent call last):"
41 traceback
.print_exception (type, value
, tb
)
45 def eargs (name
, imports
):
46 "Get arglist of NAME for Eldoc &c."
48 if imports
: exec imports
49 parts
= name
.split ('.')
51 exec 'import ' + parts
[0] # might fail
53 if inspect
.isbuiltin (func
):
55 if doc
.find (' ->') != -1:
56 print '_emacs_out', doc
.split (' ->')[0]
57 elif doc
.find ('\n') != -1:
58 print '_emacs_out', doc
.split ('\n')[0]
60 if inspect
.ismethod (func
):
62 if not inspect
.isfunction (func
): return
63 (args
, varargs
, varkw
, defaults
) = inspect
.getargspec (func
)
64 # No space between name and arglist for consistency with builtins.
66 func
.__name
__ + inspect
.formatargspec (args
, varargs
, varkw
,
70 def all_names (object):
71 """Return (an approximation to) a list of all possible attribute
72 names reachable via the attributes of OBJECT, i.e. roughly the
73 leaves of the dictionary tree under it."""
75 def do_object (object, names
):
76 if inspect
.ismodule (object):
77 do_module (object, names
)
78 elif inspect
.isclass (object):
79 do_class (object, names
)
80 # Might have an object without its class in scope.
81 elif hasattr (object, '__class__'):
82 names
.add ('__class__')
83 do_class (object.__class
__, names
)
84 # Probably not a good idea to try to enumerate arbitrary
88 def do_module (module
, names
):
89 if hasattr (module
, '__all__'): # limited export list
90 names
.union_update (module
.__all
__)
91 for i
in module
.__all
__:
92 do_object (getattr (module
, i
), names
)
94 names
.union_update (dir (module
))
95 for i
in dir (module
):
96 do_object (getattr (module
, i
), names
)
99 def do_class (object, names
):
101 names
.union_update (ns
)
102 if hasattr (object, '__bases__'): # superclasses
103 for i
in object.__bases
__: do_object (i
, names
)
106 return do_object (object, Set ([]))
108 def complete (name
, imports
):
109 """Complete TEXT in NAMESPACE and print a Lisp list of completions.
110 Exec IMPORTS first."""
111 import __main__
, keyword
113 def class_members(object):
115 if hasattr (object, '__bases__'):
116 for super in object.__bases
__:
117 names
= class_members (super)
123 dict = __main__
.__dict
__.copy()
124 if imports
: exec imports
in dict
127 for list in [dir (__builtins__
), keyword
.kwlist
, dict.keys()]:
129 if elt
[:l
] == name
: names
.add(elt
)
131 base
= name
[:name
.rfind ('.')]
132 name
= name
[name
.rfind('.')+1:]
134 object = eval (base
, dict)
135 names
= Set (dir (object))
136 if hasattr (object, '__class__'):
137 names
.add('__class__')
138 names
.union_update (class_members (object))
139 except: names
= all_names (dict)
142 print '_emacs_out (',
145 if base
: print '"%s.%s"' % (base
, n
),
146 else: print '"%s"' % n
,
149 def ehelp (name
, imports
):
150 """Get help on string NAME.
151 First try to eval name for, e.g. user definitions where we need
152 the object. Otherwise try the string form."""
155 try: exec imports
in locls
157 try: help (eval (name
, globals(), locls
))
160 def eimport (mod
, dir):
161 """Import module MOD with directory DIR at the head of the search path.
162 NB doesn't load from DIR if MOD shadows a system module."""
163 from __main__
import __dict__
169 if __dict__
.has_key(mod
) and inspect
.ismodule (__dict__
[mod
]):
170 reload (__dict__
[mod
])
172 __dict__
[mod
] = __import__ (mod
)
174 (type, value
, tb
) = sys
.exc_info ()
175 print "Traceback (most recent call last):"
176 traceback
.print_exception (type, value
, tb
.tb_next
)
180 def modpath (module
):
181 """Return the source file for the given MODULE (or None).
182 Assumes that MODULE.py and MODULE.pyc are in the same directory."""
184 path
= __import__ (module
).__file
__
185 if path
[-4:] == '.pyc' and os
.path
.exists (path
[0:-1]):
187 print "_emacs_out", path
189 print "_emacs_out ()"
191 # print '_emacs_ok' # ready for input and can call continuation
193 # arch-tag: d90408f3-90e2-4de4-99c2-6eb9c7b9ca46