def __init__(self, items, start=0):
if type(items) == types.StringType:
items = items.split(',')
self._stringTable = {}
# make sure we don't overwrite an existing element of the class
assert self._checkExistingMembers(items)
assert uniqueElements(items)
i = start
for item in items:
# remove leading/trailing whitespace
item = string.strip(item)
# is there anything left?
if len(item) == 0:
continue
# make sure there are no invalid characters
assert Enum._checkValidIdentifier(item)
self.__dict__[item] = i
self._stringTable[i] = item
i += 1
python类__dict__()的实例源码
def _run(self):
try:
try:
console = InteractiveConsole(self.locals)
# __builtins__ may either be the __builtin__ module or
# __builtin__.__dict__ in the latter case typing
# locals() at the backdoor prompt spews out lots of
# useless stuff
import __builtin__
console.locals["__builtins__"] = __builtin__
console.interact(banner=self.banner)
except SystemExit: # raised by quit()
sys.exc_clear()
finally:
self.switch_out()
self.finalize()
def _run(self):
try:
try:
console = InteractiveConsole(self.locals)
# __builtins__ may either be the __builtin__ module or
# __builtin__.__dict__ in the latter case typing
# locals() at the backdoor prompt spews out lots of
# useless stuff
import __builtin__
console.locals["__builtins__"] = __builtin__
console.interact(banner=self.banner)
except SystemExit: # raised by quit()
sys.exc_clear()
finally:
self.switch_out()
self.finalize()
def _create_interactive_locals(self):
# Create and return a *new* locals dictionary based on self.locals,
# and set any new entries in it. (InteractiveConsole does not
# copy its locals value)
_locals = self.locals.copy()
# __builtins__ may either be the __builtin__ module or
# __builtin__.__dict__; in the latter case typing
# locals() at the backdoor prompt spews out lots of
# useless stuff
try:
import __builtin__
_locals["__builtins__"] = __builtin__
except ImportError:
import builtins
_locals["builtins"] = builtins
_locals['__builtins__'] = builtins
return _locals
def _find_function_module(func):
"""
@return: The module that defines the given function.
@rtype: C{module}
@param func: The function whose module should be found.
@type func: C{function}
"""
if hasattr(func, '__module__'):
return func.__module__
try:
module = inspect.getmodule(func)
if module: return module.__name__
except KeyboardInterrupt: raise
except: pass
# This fallback shouldn't usually be needed. But it is needed in
# a couple special cases (including using epydoc to document
# itself). In particular, if a module gets loaded twice, using
# two different names for the same file, then this helps.
for module in sys.modules.values():
if (hasattr(module, '__dict__') and
hasattr(func, 'func_globals') and
func.func_globals is module.__dict__):
return module.__name__
return None
#////////////////////////////////////////////////////////////
# Introspection Dispatch Table
#////////////////////////////////////////////////////////////
def get_value_from_name(name, globs=None):
"""
Given a name, return the corresponding value.
@param globs: A namespace to check for the value, if there is no
module containing the named value. Defaults to __builtin__.
"""
name = DottedName(name)
# Import the topmost module/package. If we fail, then check if
# the requested name refers to a builtin.
try:
module = _import(name[0])
except ImportError, e:
if globs is None: globs = __builtin__.__dict__
if name[0] in globs:
try: return _lookup(globs[name[0]], name[1:])
except: raise e
else:
raise
# Find the requested value in the module/package or its submodules.
for i in range(1, len(name)):
try: return _lookup(module, name[i:])
except ImportError: pass
module = _import('.'.join(name[:i+1]))
module = _lookup(module, name[1:i+1])
return module
def install(self, unicode=False, names=None):
import __builtin__
__builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
if hasattr(names, "__contains__"):
if "gettext" in names:
__builtin__.__dict__['gettext'] = __builtin__.__dict__['_']
if "ngettext" in names:
__builtin__.__dict__['ngettext'] = (unicode and self.ungettext
or self.ngettext)
if "lgettext" in names:
__builtin__.__dict__['lgettext'] = self.lgettext
if "lngettext" in names:
__builtin__.__dict__['lngettext'] = self.lngettext
def __init__(self, namespace = None):
"""Create a new completer for the command line.
Completer([namespace]) -> completer instance.
If unspecified, the default namespace where completions are performed
is __main__ (technically, __main__.__dict__). Namespaces should be
given as dictionaries.
Completer instances should be used as the completion mechanism of
readline via the set_completer() call:
readline.set_completer(Completer(my_namespace).complete)
"""
if namespace and not isinstance(namespace, dict):
raise TypeError,'namespace must be a dictionary'
# Don't bind to namespace quite yet, but flag whether the user wants a
# specific namespace or to use __main__.__dict__. This will allow us
# to bind to __main__.__dict__ at completion time, not now.
if namespace is None:
self.use_main_ns = 1
else:
self.use_main_ns = 0
self.namespace = namespace
def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match.
"""
import keyword
matches = []
n = len(text)
for word in keyword.kwlist:
if word[:n] == text:
matches.append(word)
for nspace in [__builtin__.__dict__, self.namespace]:
for word, val in nspace.items():
if word[:n] == text and word != "__builtins__":
matches.append(self._callable_postfix(val, word))
return matches
def _load(module):
try:
mod = __import__(module,globals(),locals(),".")
__builtin__.__dict__.update(mod.__dict__)
except Exception,e:
log_interactive.error(e)
def save_session(fname=None, session=None, pickleProto=-1):
if fname is None:
fname = conf.session
if not fname:
conf.session = fname = utils.get_temp_file(keep=True)
log_interactive.info("Use [%s] as session file" % fname)
if session is None:
session = __builtin__.__dict__["scapy_session"]
to_be_saved = session.copy()
if to_be_saved.has_key("__builtins__"):
del(to_be_saved["__builtins__"])
for k in to_be_saved.keys():
if type(to_be_saved[k]) in [types.TypeType, types.ClassType, types.ModuleType]:
log_interactive.error("[%s] (%s) can't be saved." % (k, type(to_be_saved[k])))
del(to_be_saved[k])
try:
os.rename(fname, fname+".bak")
except OSError:
pass
f=gzip.open(fname,"wb")
cPickle.dump(to_be_saved, f, pickleProto)
f.close()
def load_session(fname=None):
if fname is None:
fname = conf.session
try:
s = cPickle.load(gzip.open(fname,"rb"))
except IOError:
s = cPickle.load(open(fname,"rb"))
scapy_session = __builtin__.__dict__["scapy_session"]
scapy_session.clear()
scapy_session.update(s)
def update_session(fname=None):
if fname is None:
fname = conf.session
try:
s = cPickle.load(gzip.open(fname,"rb"))
except IOError:
s = cPickle.load(open(fname,"rb"))
scapy_session = __builtin__.__dict__["scapy_session"]
scapy_session.update(s)
################
##### Main #####
################
def autorun_commands(cmds,my_globals=None,verb=0):
sv = conf.verb
import __builtin__
try:
try:
if my_globals is None:
my_globals = __import__("scapy.all").all.__dict__
conf.verb = verb
interp = ScapyAutorunInterpreter(my_globals)
cmd = ""
cmds = cmds.splitlines()
cmds.append("") # ensure we finish multiline commands
cmds.reverse()
__builtin__.__dict__["_"] = None
while 1:
if cmd:
sys.stderr.write(sys.__dict__.get("ps2","... "))
else:
sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt())))
l = cmds.pop()
print l
cmd += "\n"+l
if interp.runsource(cmd):
continue
if interp.error:
return 0
cmd = ""
if len(cmds) <= 1:
break
except SystemExit:
pass
finally:
conf.verb = sv
return _
def instance(klass, d):
if isinstance(klass, types.ClassType):
return new.instance(klass, d)
elif isinstance(klass, type):
o = object.__new__(klass)
o.__dict__ = d
return o
else:
raise TypeError, "%s is not a class" % klass
def jellyToDOM(self, jellier, element):
element.setAttribute("marmalade:version", str(self.jellyDOMVersion))
method = getattr(self, "jellyToDOM_%s" % self.jellyDOMVersion, None)
if method:
method(jellier, element)
else:
element.appendChild(jellier.jellyToNode(self.__dict__))
def unjellyFromDOM(self, unjellier, element):
pDOMVersion = element.getAttribute("marmalade:version") or "0"
method = getattr(self, "unjellyFromDOM_%s" % pDOMVersion, None)
if method:
method(unjellier, element)
else:
# XXX: DOMJellyable.unjellyNode does not exist
# XXX: 'node' is undefined - did you mean 'self', 'element', or 'Node'?
state = self.unjellyNode(getValueElement(node))
if hasattr(self.__class__, "__setstate__"):
self.__setstate__(state)
else:
self.__dict__ = state
def unjellyAttribute(self, instance, attrName, valueNode):
"""Utility method for unjellying into instances of attributes.
Use this rather than unjellyNode unless you like surprising bugs!
Alternatively, you can use unjellyInto on your instance's __dict__.
"""
self.unjellyInto(instance.__dict__, attrName, valueNode)
def _load(module):
try:
mod = __import__(module,globals(),locals(),".")
__builtin__.__dict__.update(mod.__dict__)
except Exception,e:
log_interactive.error(e)
def load_session(fname=None):
if fname is None:
fname = conf.session
try:
s = cPickle.load(gzip.open(fname,"rb"))
except IOError:
s = cPickle.load(open(fname,"rb"))
scapy_session = __builtin__.__dict__["scapy_session"]
scapy_session.clear()
scapy_session.update(s)