rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
return EditorWindow.close(self)
|
self.closing = True self.text.after(2 * self.pollinterval, self.close2) def close2(self): return EditorWindow.close(self)
|
def close(self): "Extend EditorWindow.close()" if self.executing: response = tkMessageBox.askokcancel( "Kill?", "The program is still running!\n Do you want to kill it?", default="ok", parent=self.text) if response == False: return "cancel" # interrupt the subprocess self.canceled = True if use_subprocess: self.interp.interrupt_subprocess() return "cancel" else: return EditorWindow.close(self)
|
buildno = int(buildno)
|
def _sys_version(): """ Returns a parsed version of Python's sys.version as tuple (version, buildno, builddate, compiler) referring to the Python version, build number, build date/time as string and the compiler identification string. Note that unlike the Python sys.version, the returned value for the Python version will always include the patchlevel (it defaults to '.0'). """ global _sys_version_cache if _sys_version_cache is not None: return _sys_version_cache version, buildno, builddate, buildtime, compiler = \ _sys_version_parser.match(sys.version).groups() buildno = int(buildno) builddate = builddate + ' ' + buildtime l = string.split(version, '.') if len(l) == 2: l.append('0') version = string.join(l, '.') _sys_version_cache = (version, buildno, builddate, compiler) return _sys_version_cache
|
|
if self.distribution.has_ext_modules():
|
if not self.skip_build and self.distribution.has_ext_modules():
|
def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'wininst') if not self.target_version: self.target_version = "" if self.distribution.has_ext_modules(): short_version = get_python_version() if self.target_version and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be" + short_version self.target_version = short_version
|
"target version can only be" + short_version
|
"target version can only be %s, or the '--skip_build'" \ " option must be specified" % (short_version,)
|
def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'wininst') if not self.target_version: self.target_version = "" if self.distribution.has_ext_modules(): short_version = get_python_version() if self.target_version and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be" + short_version self.target_version = short_version
|
build_info = "Build %s with distutils-%s" % \
|
build_info = "Built %s with distutils-%s" % \
|
def get_inidata (self): # Return data describing the installation.
|
`fileName`+' .')
|
`fn`+' .', parent=self)
|
def ViewFile(self, viewTitle, viewFile, encoding=None): fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), viewFile) if encoding: import codecs try: textFile = codecs.open(fn, 'r') except IOError: tkMessageBox.showerror(title='File Load Error', message='Unable to load file '+ `fileName`+' .') return else: data = textFile.read() else: data = None textView.TextViewer(self, viewTitle, fn, data=data)
|
topdir = os.getcwd() + 'build/rpm'
|
def run (self):
|
|
'_topdir ' + os.getcwd() + '/build/rpm',])
|
'_topdir %s/%s' % (os.getcwd(), rpm_base),])
|
def run (self):
|
chars = self.text.get("1.0", "end-1c")
|
chars = str(self.text.get("1.0", "end-1c"))
|
def writefile(self, filename): self.fixlastline() try: f = open(filename, "w") chars = self.text.get("1.0", "end-1c") f.write(chars) f.close() ## print "saved to", `filename` return 1 except IOError, msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return 0
|
def __init__(self, get, set=None):
|
def __init__(self, get, set=None, delete=None):
|
def __init__(self, get, set=None): self.__get = get self.__set = set
|
x = computed_attribute(__get_x, __set_x)
|
def __delete_x(self): del self.__x x = computed_attribute(__get_x, __set_x, __delete_x)
|
def __set_x(self, x): self.__x = x
|
C.x.__delete__(a) verify(not hasattr(a, "x"))
|
def delx(self): del self.__x
|
|
__call__ = run
|
def __call__(self, *args, **kwds): return self.run(*args, **kwds)
|
def run(self, result=None): if result is None: result = self.defaultTestResult() result.startTest(self) testMethod = getattr(self, self.__testMethodName) try: try: self.setUp() except KeyboardInterrupt: raise except: result.addError(self, self.__exc_info()) return
|
return self(result) def __call__(self, result):
|
def run(self, result): return self(result)
|
|
print "usage:", sys.argv[0], "file ..."
|
print "usage:", sys.argv[0], "[-t tabwidth] file ..."
|
def main(): tabsize = 8 try: opts, args = getopt.getopt(sys.argv[1:], "t:") if not args: raise getopt.error, "At least one file argument required" except getopt.error, msg: print msg print "usage:", sys.argv[0], "file ..." return for file in args: process(file, tabsize)
|
vout.setpf(1, -2))
|
vout.setpf((1, -2))
|
def record(v, info, filename, audiofilename, mono, grey, greybits, \ monotreshold, fields, preallocspace): import thread format, x, y, qsize, rate = info fps = 59.64 # Fields per second # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) tpf = 1000.0 / fps # Time per field in msec if filename: vout = VFile.VoutFile().init(filename) if mono: format = 'mono' elif grey and greybits == 8: format = 'grey' elif grey: format = 'grey'+`abs(greybits)` else: format = 'rgb8' vout.setformat(format) vout.setsize(x, y) if fields: vout.setpf(1, -2)) vout.writeheader() if preallocspace: print 'Preallocating space...' vout.prealloc(preallocspace) print 'done.' MAXSIZE = 20 # XXX should be a user option import Queue queue = Queue.Queue().init(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() convertor = None if grey: if greybits == 2: convertor = imageop.grey2grey2 elif greybits == 4: convertor = imageop.grey2grey4 elif greybits == -2: convertor = imageop.dither2grey2 thread.start_new_thread(saveframes, \ (vout, queue, done, mono, monotreshold, convertor)) if audiofilename: audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone) gl.wintitle('(rec) ' + filename) lastid = 0 t0 = time.millitimer() count = 0 ids = [] v.InitContinuousCapture(info) while not gl.qtest(): try: cd, id = v.GetCaptureData() except sv.error: #time.millisleep(10) # XXX is this necessary? sgi.nap(1) # XXX Try by Jack continue ids.append(id) id = id + 2*rate
|
pdict: dictionary containing other parameters of conten-type header
|
pdict: dictionary containing other parameters of content-type header
|
def parse_multipart(fp, pdict): """Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of conten-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. """ boundary = "" if 'boundary' in pdict: boundary = pdict['boundary'] if not valid_boundary(boundary): raise ValueError, ('Invalid boundary in multipart form: %r' % (boundary,)) nextpart = "--" + boundary lastpart = "--" + boundary + "--" partdict = {} terminator = "" while terminator != lastpart: bytes = -1 data = None if terminator: # At start of next part. Read headers first. headers = mimetools.Message(fp) clength = headers.getheader('content-length') if clength: try: bytes = int(clength) except ValueError: pass if bytes > 0: if maxlen and bytes > maxlen: raise ValueError, 'Maximum content length exceeded' data = fp.read(bytes) else: data = "" # Read lines until end of part. lines = [] while 1: line = fp.readline() if not line: terminator = lastpart # End outer loop break if line[:2] == "--": terminator = line.strip() if terminator in (nextpart, lastpart): break lines.append(line) # Done with part. if data is None: continue if bytes < 0: if lines: # Strip final line terminator line = lines[-1] if line[-2:] == "\r\n": line = line[:-2] elif line[-1:] == "\n": line = line[:-1] lines[-1] = line data = "".join(lines) line = headers['content-disposition'] if not line: continue key, params = parse_header(line) if key != 'form-data': continue if 'name' in params: name = params['name'] else: continue if name in partdict: partdict[name].append(data) else: partdict[name] = [data] return partdict
|
headers = mimetools.Message(fp)
|
headers = _header_parser.parse(fp)
|
def parse_multipart(fp, pdict): """Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of conten-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. """ boundary = "" if 'boundary' in pdict: boundary = pdict['boundary'] if not valid_boundary(boundary): raise ValueError, ('Invalid boundary in multipart form: %r' % (boundary,)) nextpart = "--" + boundary lastpart = "--" + boundary + "--" partdict = {} terminator = "" while terminator != lastpart: bytes = -1 data = None if terminator: # At start of next part. Read headers first. headers = mimetools.Message(fp) clength = headers.getheader('content-length') if clength: try: bytes = int(clength) except ValueError: pass if bytes > 0: if maxlen and bytes > maxlen: raise ValueError, 'Maximum content length exceeded' data = fp.read(bytes) else: data = "" # Read lines until end of part. lines = [] while 1: line = fp.readline() if not line: terminator = lastpart # End outer loop break if line[:2] == "--": terminator = line.strip() if terminator in (nextpart, lastpart): break lines.append(line) # Done with part. if data is None: continue if bytes < 0: if lines: # Strip final line terminator line = lines[-1] if line[-2:] == "\r\n": line = line[:-2] elif line[-1:] == "\n": line = line[:-1] lines[-1] = line data = "".join(lines) line = headers['content-disposition'] if not line: continue key, params = parse_header(line) if key != 'form-data': continue if 'name' in params: name = params['name'] else: continue if name in partdict: partdict[name].append(data) else: partdict[name] = [data] return partdict
|
headers: a dictionary(-like) object (sometimes rfc822.Message or a subclass thereof) containing *all* headers
|
headers: a dictionary(-like) object (sometimes email.Message.Message or a subclass thereof) containing *all* headers
|
def __repr__(self): """Return printable representation.""" return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
|
headers = rfc822.Message(self.fp)
|
headers = _header_parser.parse(self.fp)
|
def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" ib = self.innerboundary if not valid_boundary(ib): raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,) self.list = [] klass = self.FieldStorageClass or self.__class__ part = klass(self.fp, {}, ib, environ, keep_blank_values, strict_parsing) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = klass(self.fp, headers, ib, environ, keep_blank_values, strict_parsing) self.list.append(part) self.skip_lines()
|
if type(f) == type(''):
|
if isinstance(f, basestring):
|
def __init__(self, f): self._i_opened_the_file = None if type(f) == type(''): f = __builtin__.open(f, 'rb') self._i_opened_the_file = f # else, assume it is an open file object already self.initfp(f)
|
if type(f) == type(''):
|
if isinstance(f, basestring):
|
def __init__(self, f): self._i_opened_the_file = None if type(f) == type(''): f = __builtin__.open(f, 'wb') self._i_opened_the_file = f self.initfp(f)
|
else: MacOS.HandleEvent(event)
|
return MacOS.HandleEvent(event)
|
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise KeyboardInterrupt, "Command-period" if c == 'q': self.quitting = 1 elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message(self.getabouttext()) elif item > 1: name = self.applemenu.GetMenuItemText(item) Menu.OpenDeskAcc(name) elif id == self.quitid and item == 1: self.quitting = 1 Menu.HiliteMenu(0) else: # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
|
in setRollover().
|
in doRollover().
|
def emit(self, record): """ Emit a record.
|
value = _EmptyClass() value.__class__ = klass else:
|
try: value = _EmptyClass() value.__class__ = klass except RuntimeError: pass if not instantiated:
|
def load_inst(self): k = self.marker() args = tuple(self.stack[k+1:]) del self.stack[k:] module = self.readline()[:-1] name = self.readline()[:-1] klass = self.find_class(module, name)
|
value = _EmptyClass() value.__class__ = klass else:
|
try: value = _EmptyClass() value.__class__ = klass instantiated = 1 except RuntimeError: pass if not instantiated:
|
def load_obj(self): stack = self.stack k = self.marker() klass = stack[k + 1] del stack[k + 1] args = tuple(stack[k + 1:]) del stack[k:]
|
inst.__dict__.update(value)
|
try: inst.__dict__.update(value) except RuntimeError: for k, v in value.items(): setattr(inst, k, v)
|
def load_build(self): stack = self.stack value = stack[-1] del stack[-1] inst = stack[-1] try: setstate = inst.__setstate__ except AttributeError: inst.__dict__.update(value) else: setstate(value)
|
__starttag_text = None
|
def parse_pi(self, i): rawdata = self.rawdata if rawdata[i:i+2] != '<?': self.error('unexpected call to parse_pi()') match = piclose.search(rawdata, i+2) if not match: return -1 j = match.start(0) self.handle_pi(rawdata[i+2: j]) j = match.end(0) return j-i
|
|
def __delitem__(self, key): del self.data[key.upper()]
|
try: unsetenv except NameError: def __delitem__(self, key): del self.data[key.upper()] else: def __delitem__(self, key): unsetenv(key) del self.data[key.upper()]
|
def __delitem__(self, key): del self.data[key.upper()]
|
st2 = parser.sequence2ast(t)
|
try: st2 = parser.sequence2ast(t) except parser.ParserError: print "Failing syntax tree:" pprint.pprint(t) raise
|
def roundtrip(f, s): st1 = f(s) t = st1.totuple() st2 = parser.sequence2ast(t)
|
buffering. Sublcasses should however, if possible, try to
|
buffering. Subclasses should however, if possible, try to
|
def readline(self, size=None):
|
the file.
|
file.
|
def open(filename, mode='rb', encoding=None, errors='strict', buffering=1): """ Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. Note: The wrapped version will only accept the object format defined by the codecs, i.e. Unicode objects for most builtin codecs. Output is also codec dependent and will usually by Unicode as well. Files are always opened in binary mode, even if no binary mode was specified. Thisis done to avoid data loss due to encodings using 8-bit values. The default file mode is 'rb' meaning to open the file in binary read mode. encoding specifies the encoding which is to be used for the the file. errors may be given to define the error handling. It defaults to 'strict' which causes ValueErrors to be raised in case an encoding error occurs. buffering has the same meaning as for the builtin open() API. It defaults to line buffered. The returned wrapped file object provides an extra attribute .encoding which allows querying the used encoding. This attribute is only available if an encoding was specified as parameter. """ if encoding is not None and \ 'b' not in mode: # Force opening of the file in binary mode mode = mode + 'b' file = __builtin__.open(filename, mode, buffering) if encoding is None: return file (e, d, sr, sw) = lookup(encoding) srw = StreamReaderWriter(file, sr, sw, errors) # Add attributes to simplify introspection srw.encoding = encoding return srw
|
If a target mapping in the decoding map occurrs multiple
|
If a target mapping in the decoding map occurs multiple
|
def make_encoding_map(decoding_map): """ Creates an encoding map from a decoding map. If a target mapping in the decoding map occurrs multiple times, then that target is mapped to None (undefined mapping), causing an exception when encountered by the charmap codec during translation. One example where this happens is cp875.py which decodes multiple character to \u001a. """ m = {} for k,v in decoding_map.items(): if not v in m: m[v] = k else: m[v] = None return m
|
FileHandler.names = (socket.gethostbyname('localhost'), socket.gethostbyname(socket.gethostname()))
|
try: FileHandler.names = (socket.gethostbyname('localhost'), socket.gethostbyname(socket.gethostname())) except socket.gaierror: FileHandler.names = (socket.gethostbyname('localhost'),)
|
def get_names(self): if FileHandler.names is None: FileHandler.names = (socket.gethostbyname('localhost'), socket.gethostbyname(socket.gethostname())) return FileHandler.names
|
data = s[:n]
|
def pack_fstring(self, n, s): if n < 0: raise ValueError, 'fstring size must be nonnegative' n = ((n+3)/4)*4 data = s[:n] data = data + (n - len(data)) * '\0' self.__buf.write(data)
|
|
if e.errno == errno.EAGAIN:
|
if e.errno in (errno.EAGAIN, errno.EACCES):
|
def _lock_file(f, dotlock=True): """Lock file f using lockf and dot locking.""" dotlock_done = False try: if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.errno == errno.EAGAIN: raise ExternalClashError('lockf: lock unavailable: %s' % f.name) else: raise if dotlock: try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() except IOError, e: if e.errno == errno.EACCES: return # Without write access, just skip dotlocking. else: raise try: if hasattr(os, 'link'): os.link(pre_lock.name, f.name + '.lock') dotlock_done = True os.unlink(pre_lock.name) else: os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True except OSError, e: if e.errno == errno.EEXIST: os.remove(pre_lock.name) raise ExternalClashError('dot lock unavailable: %s' % f.name) else: raise except: if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) if dotlock_done: os.remove(f.name + '.lock') raise
|
if os.name == "posix": check_environ() sys_dir = os.path.dirname(sys.modules['distutils'].__file__) sys_file = os.path.join(sys_dir, "pydistutils.cfg") if os.path.isfile(sys_file): files.append(sys_file) user_file = os.path.join(os.environ.get('HOME'), ".pydistutils.cfg")
|
check_environ() if os.name=='posix': sys_dir = os.path.dirname(sys.modules['distutils'].__file__) user_filename = ".pydistutils.cfg" else: sys_dir = sysconfig.PREFIX user_filename = "pydistutils.cfg" sys_file = os.path.join(sys_dir, "pydistutils.cfg") if os.path.isfile(sys_file): files.append(sys_file) if os.environ.has_key('HOME'): user_file = os.path.join(os.environ.get('HOME'), user_filename)
|
def find_config_files (self): """Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions).
|
else: sys_file = os.path.join (sysconfig.PREFIX, "pydistutils.cfg") if os.path.isfile(sys_file): files.append(sys_file)
|
def find_config_files (self): """Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions).
|
|
self.assertRaises(AttributeError, f, LenOnly(), 10)
|
self.assertRaises(TypeError, f, LenOnly(), 10)
|
def test_len_only(self): for f in (bisect_left, bisect_right, insort_left, insort_right): self.assertRaises(AttributeError, f, LenOnly(), 10)
|
self.assertRaises(AttributeError, f, GetOnly(), 10)
|
self.assertRaises(TypeError, f, GetOnly(), 10)
|
def test_get_only(self): for f in (bisect_left, bisect_right, insort_left, insort_right): self.assertRaises(AttributeError, f, GetOnly(), 10)
|
data = self.sslobj.read(size) while len(data) < size: data += self.sslobj.read(size-len(data)) return data
|
chunks = [] read = 0 while read < size: data = self.sslobj.read(size-read) read += len(data) chunks.append(size) return ''.join(chunks)
|
def read(self, size): """Read 'size' bytes from remote.""" # sslobj.read() sometimes returns < size bytes data = self.sslobj.read(size) while len(data) < size: data += self.sslobj.read(size-len(data))
|
line = ""
|
line = []
|
def readline(self): """Read line from remote.""" # NB: socket.ssl needs a "readline" method, or perhaps a "makefile" method. line = "" while 1: char = self.sslobj.read(1) line += char if char == "\n": return line
|
line += char if char == "\n": return line
|
line.append(char) if char == "\n": return ''.join(line)
|
def readline(self): """Read line from remote.""" # NB: socket.ssl needs a "readline" method, or perhaps a "makefile" method. line = "" while 1: char = self.sslobj.read(1) line += char if char == "\n": return line
|
if not host: return addinfo(open(file, 'r'), noheaders())
|
if not host: return addinfo(open(_fixpath(file), 'r'), noheaders())
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(file, 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(file, 'r'), noheaders()) raise IOError, ('local file error', 'not on local host')
|
return addinfo(open(file, 'r'), noheaders())
|
return addinfo(open(_fixpath(file), 'r'), noheaders())
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(file, 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(file, 'r'), noheaders()) raise IOError, ('local file error', 'not on local host')
|
self.implib_dir = self.build_temp
|
def finalize_options (self): from distutils import sysconfig
|
|
def get_ext_libname (self, ext_name): ext_path = string.split (ext_name, '.') if os.name == 'nt' and self.debug: return apply (os.path.join, ext_path) + '_d.lib' return apply (os.path.join, ext_path) + '.lib'
|
def get_ext_libname (self, ext_name): # create a filename for the (unneeded) lib-file. # extensions in debug_mode are named 'module_d.pyd' under windows ext_path = string.split (ext_name, '.') if os.name == 'nt' and self.debug: return apply (os.path.join, ext_path) + '_d.lib' return apply (os.path.join, ext_path) + '.lib'
|
|
if sys.platform == "win32": pythonlib = ("python%d%d" % (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
|
from distutils.msvccompiler import MSVCCompiler if sys.platform == "win32" and \ not isinstance(self.compiler, MSVCCompiler): template = "python%d%d" if self.debug: template = template + '_d' pythonlib = (template % (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
|
def get_libraries (self, ext): """Return the list of libraries to link against when building a shared extension. On most platforms, this is just 'ext.libraries'; on Windows, we add the Python library (eg. python20.dll). """ # The python library is always needed on Windows. For MSVC, this # is redundant, since the library is mentioned in a pragma in # config.h that MSVC groks. The other Windows compilers all seem # to need it mentioned explicitly, though, so that's what we do. if sys.platform == "win32": pythonlib = ("python%d%d" % (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff)) # don't extend ext.libraries, it may be shared with other # extensions, it is a reference to the original list return ext.libraries + [pythonlib] else: return ext.libraries
|
self.spawn (["zip", "-r", base_dir, base_dir])
|
self.spawn (["zip", "-r", base_dir + ".zip", base_dir])
|
def make_zipfile (self, base_dir):
|
filename = sys.argv[0]
|
try: filename = sys.argv[0] except AttributeError: filename = '__main__'
|
def warn(message, category=None, stacklevel=1): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning assert issubclass(category, Warning) # Get context information try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = "<string>" filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith(".pyc") or fnl.endswith(".pyo"): filename = filename[:-1] else: if module == "__main__": filename = sys.argv[0] if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry)
|
The walk is performed in breadth-first order. This method is a
|
The walk is performed in depth-first order. This method is a
|
def walk(self): """Walk over the message tree, yielding each subpart.
|
if not self.stack and not space.match(data):
|
if not self.stack and space.match(data) is None:
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: if self.__at_start: self.syntax_error('illegal data at start of file') self.__at_start = 0 data = rawdata[i:j] if not self.stack and not space.match(data): self.syntax_error('data not in content') if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k self.literal = 0 continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:i], '\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise RuntimeError, 'only XML version 1.0 supported' if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue elif rawdata[i] == '&': res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + string.count(res.group(0), '\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.entitydefs.has_key(name): self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.syntax_error('reference to unknown entity') self.unknown_entityref(name) self.lineno = self.lineno + string.count(res.group(0), '\n') continue elif rawdata[i] == ']': if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1])
|
if not res:
|
if res is None:
|
def parse_comment(self, i): rawdata = self.rawdata if rawdata[i:i+4] <> '<!--': raise RuntimeError, 'unexpected call to handle_comment' res = commentclose.search(rawdata, i+4) if not res: return -1 if doubledash.search(rawdata, i+4, res.start(0)): self.syntax_error("`--' inside comment") if rawdata[res.start(0)-1] == '-': self.syntax_error('comment cannot end in three dashes') if illegal.search(rawdata, i+4, res.start(0)): self.syntax_error('illegal character in comment') self.handle_comment(rawdata[i+4: res.start(0)]) return res.end(0)
|
if not res:
|
if res is None:
|
def parse_doctype(self, res): rawdata = self.rawdata n = len(rawdata) name = res.group('name') pubid, syslit = res.group('pubid', 'syslit') if pubid is not None: pubid = pubid[1:-1] # remove quotes pubid = string.join(string.split(pubid)) # normalize if syslit is not None: syslit = syslit[1:-1] # remove quotes j = k = res.end(0) if k >= n: return -1 if rawdata[k] == '[': level = 0 k = k+1 dq = sq = 0 while k < n: c = rawdata[k] if not sq and c == '"': dq = not dq elif not dq and c == "'": sq = not sq elif sq or dq: pass elif level <= 0 and c == ']': res = endbracket.match(rawdata, k+1) if not res: return -1 self.handle_doctype(name, pubid, syslit, rawdata[j+1:k]) return res.end(0) elif c == '<': level = level + 1 elif c == '>': level = level - 1 if level < 0: self.syntax_error("bogus `>' in DOCTYPE") k = k+1 res = endbracket.search(rawdata, k) if not res: return -1 if res.start(0) != k: self.syntax_error('garbage in DOCTYPE') self.handle_doctype(name, pubid, syslit, None) return res.end(0)
|
res = endbracket.search(rawdata, k) if not res:
|
res = endbracketfind.match(rawdata, k) if res is None:
|
def parse_doctype(self, res): rawdata = self.rawdata n = len(rawdata) name = res.group('name') pubid, syslit = res.group('pubid', 'syslit') if pubid is not None: pubid = pubid[1:-1] # remove quotes pubid = string.join(string.split(pubid)) # normalize if syslit is not None: syslit = syslit[1:-1] # remove quotes j = k = res.end(0) if k >= n: return -1 if rawdata[k] == '[': level = 0 k = k+1 dq = sq = 0 while k < n: c = rawdata[k] if not sq and c == '"': dq = not dq elif not dq and c == "'": sq = not sq elif sq or dq: pass elif level <= 0 and c == ']': res = endbracket.match(rawdata, k+1) if not res: return -1 self.handle_doctype(name, pubid, syslit, rawdata[j+1:k]) return res.end(0) elif c == '<': level = level + 1 elif c == '>': level = level - 1 if level < 0: self.syntax_error("bogus `>' in DOCTYPE") k = k+1 res = endbracket.search(rawdata, k) if not res: return -1 if res.start(0) != k: self.syntax_error('garbage in DOCTYPE') self.handle_doctype(name, pubid, syslit, None) return res.end(0)
|
if res.start(0) != k:
|
if endbracket.match(rawdata, k) is None:
|
def parse_doctype(self, res): rawdata = self.rawdata n = len(rawdata) name = res.group('name') pubid, syslit = res.group('pubid', 'syslit') if pubid is not None: pubid = pubid[1:-1] # remove quotes pubid = string.join(string.split(pubid)) # normalize if syslit is not None: syslit = syslit[1:-1] # remove quotes j = k = res.end(0) if k >= n: return -1 if rawdata[k] == '[': level = 0 k = k+1 dq = sq = 0 while k < n: c = rawdata[k] if not sq and c == '"': dq = not dq elif not dq and c == "'": sq = not sq elif sq or dq: pass elif level <= 0 and c == ']': res = endbracket.match(rawdata, k+1) if not res: return -1 self.handle_doctype(name, pubid, syslit, rawdata[j+1:k]) return res.end(0) elif c == '<': level = level + 1 elif c == '>': level = level - 1 if level < 0: self.syntax_error("bogus `>' in DOCTYPE") k = k+1 res = endbracket.search(rawdata, k) if not res: return -1 if res.start(0) != k: self.syntax_error('garbage in DOCTYPE') self.handle_doctype(name, pubid, syslit, None) return res.end(0)
|
if not res:
|
if res is None:
|
def parse_cdata(self, i): rawdata = self.rawdata if rawdata[i:i+9] <> '<![CDATA[': raise RuntimeError, 'unexpected call to parse_cdata' res = cdataclose.search(rawdata, i+9) if not res: return -1 if illegal.search(rawdata, i+9, res.start(0)): self.syntax_error('illegal character in CDATA') if not self.stack: self.syntax_error('CDATA not in content') self.handle_cdata(rawdata[i+9:res.start(0)]) return res.end(0)
|
if not end:
|
if end is None:
|
def parse_proc(self, i): rawdata = self.rawdata end = procclose.search(rawdata, i) if not end: return -1 j = end.start(0) if illegal.search(rawdata, i+2, j): self.syntax_error('illegal character in processing instruction') res = tagfind.match(rawdata, i+2) if not res: raise RuntimeError, 'unexpected call to parse_proc' k = res.end(0) name = res.group(0) if string.find(string.lower(name), 'xml') >= 0: self.syntax_error('illegal processing instruction target name') self.handle_proc(name, rawdata[k:j]) return end.end(0)
|
if not res:
|
if res is None:
|
def parse_proc(self, i): rawdata = self.rawdata end = procclose.search(rawdata, i) if not end: return -1 j = end.start(0) if illegal.search(rawdata, i+2, j): self.syntax_error('illegal character in processing instruction') res = tagfind.match(rawdata, i+2) if not res: raise RuntimeError, 'unexpected call to parse_proc' k = res.end(0) name = res.group(0) if string.find(string.lower(name), 'xml') >= 0: self.syntax_error('illegal processing instruction target name') self.handle_proc(name, rawdata[k:j]) return end.end(0)
|
def parse_attributes(self, tag, k, j, attributes = None):
|
def parse_attributes(self, tag, i, j, attributes = None):
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
while k < j: res = attrfind.match(rawdata, k) if not res: break
|
while i < j: res = attrfind.match(rawdata, i) if res is None: break
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
self.syntax_error('no attribute value specified')
|
self.syntax_error("no value specified for attribute `%s'" % attrname)
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
self.syntax_error('attribute value not quoted')
|
self.syntax_error("attribute `%s' value not quoted" % attrname) if '<' in attrvalue: self.syntax_error("`<' illegal in attribute value")
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
self.syntax_error('unknown attribute %s of element %s' %
|
self.syntax_error("unknown attribute `%s' of element `%s'" %
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
self.syntax_error('attribute specified twice')
|
self.syntax_error("attribute `%s' specified twice" % attrname)
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
k = res.end(0)
|
i = res.end(0)
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
return attrdict, k
|
return attrdict, i
|
def parse_attributes(self, tag, k, j, attributes = None): rawdata = self.rawdata # Now parse the data between k and j into a tag and attrs attrdict = {} try: # convert attributes list to dictionary d = {} for a in attributes: d[a] = None attributes = d except TypeError: pass while k < j: res = attrfind.match(rawdata, k) if not res: break attrname, attrvalue = res.group('name', 'value') if attrvalue is None: self.syntax_error('no attribute value specified') attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] else: self.syntax_error('attribute value not quoted') if attributes is not None and not attributes.has_key(attrname): self.syntax_error('unknown attribute %s of element %s' % (attrname, tag)) if attrdict.has_key(attrname): self.syntax_error('attribute specified twice') attrvalue = string.translate(attrvalue, attrtrans) attrdict[attrname] = self.translate_references(attrvalue) k = res.end(0) if attributes is not None: # fill in with default attributes for key, val in attributes.items(): if val is not None and not attrdict.has_key(key): attrdict[key] = val return attrdict, k
|
end = endbracket.search(rawdata, i+1) if not end:
|
end = endbracketfind.match(rawdata, i+1) if end is None:
|
def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracket.search(rawdata, i+1) if not end: return -1 j = end.start(0) res = tagfind.match(rawdata, i+1) if not res: raise RuntimeError, 'unexpected call to parse_starttag' k = res.end(0) tag = res.group(0) if not self.__seen_starttag and self.__seen_doctype: if tag != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') if hasattr(self, tag + '_attributes'): attributes = getattr(self, tag + '_attributes') else: attributes = None attrdict, k = self.parse_attributes(tag, k, j, attributes) res = starttagend.match(rawdata, k) if not res: self.syntax_error('garbage in start tag') self.finish_starttag(tag, attrdict) if res and res.group('slash') == '/': self.finish_endtag(tag) return end.end(0)
|
j = end.start(0) res = tagfind.match(rawdata, i+1) if not res: raise RuntimeError, 'unexpected call to parse_starttag' k = res.end(0) tag = res.group(0) if not self.__seen_starttag and self.__seen_doctype: if tag != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE')
|
tag = starttagmatch.match(rawdata, i) if tag is None or tag.end(0) != end.end(0): self.syntax_error('garbage in starttag') return end.end(0) tagname = tag.group('tagname') if not self.__seen_starttag and self.__seen_doctype and \ tagname != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE')
|
def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracket.search(rawdata, i+1) if not end: return -1 j = end.start(0) res = tagfind.match(rawdata, i+1) if not res: raise RuntimeError, 'unexpected call to parse_starttag' k = res.end(0) tag = res.group(0) if not self.__seen_starttag and self.__seen_doctype: if tag != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') if hasattr(self, tag + '_attributes'): attributes = getattr(self, tag + '_attributes') else: attributes = None attrdict, k = self.parse_attributes(tag, k, j, attributes) res = starttagend.match(rawdata, k) if not res: self.syntax_error('garbage in start tag') self.finish_starttag(tag, attrdict) if res and res.group('slash') == '/': self.finish_endtag(tag) return end.end(0)
|
if hasattr(self, tag + '_attributes'): attributes = getattr(self, tag + '_attributes')
|
if hasattr(self, tagname + '_attributes'): attributes = getattr(self, tagname + '_attributes')
|
def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracket.search(rawdata, i+1) if not end: return -1 j = end.start(0) res = tagfind.match(rawdata, i+1) if not res: raise RuntimeError, 'unexpected call to parse_starttag' k = res.end(0) tag = res.group(0) if not self.__seen_starttag and self.__seen_doctype: if tag != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') if hasattr(self, tag + '_attributes'): attributes = getattr(self, tag + '_attributes') else: attributes = None attrdict, k = self.parse_attributes(tag, k, j, attributes) res = starttagend.match(rawdata, k) if not res: self.syntax_error('garbage in start tag') self.finish_starttag(tag, attrdict) if res and res.group('slash') == '/': self.finish_endtag(tag) return end.end(0)
|
attrdict, k = self.parse_attributes(tag, k, j, attributes) res = starttagend.match(rawdata, k) if not res: self.syntax_error('garbage in start tag') self.finish_starttag(tag, attrdict) if res and res.group('slash') == '/': self.finish_endtag(tag) return end.end(0)
|
k, j = tag.span('attrs') attrdict, k = self.parse_attributes(tagname, k, j, attributes) self.finish_starttag(tagname, attrdict) if tag.group('slash') == '/': self.finish_endtag(tagname) return tag.end(0)
|
def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracket.search(rawdata, i+1) if not end: return -1 j = end.start(0) res = tagfind.match(rawdata, i+1) if not res: raise RuntimeError, 'unexpected call to parse_starttag' k = res.end(0) tag = res.group(0) if not self.__seen_starttag and self.__seen_doctype: if tag != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') if hasattr(self, tag + '_attributes'): attributes = getattr(self, tag + '_attributes') else: attributes = None attrdict, k = self.parse_attributes(tag, k, j, attributes) res = starttagend.match(rawdata, k) if not res: self.syntax_error('garbage in start tag') self.finish_starttag(tag, attrdict) if res and res.group('slash') == '/': self.finish_endtag(tag) return end.end(0)
|
end = endbracket.search(rawdata, i+1) if not end:
|
end = endbracketfind.match(rawdata, i+1) if end is None:
|
def parse_endtag(self, i): rawdata = self.rawdata end = endbracket.search(rawdata, i+1) if not end: return -1 res = tagfind.match(rawdata, i+2) if not res: self.syntax_error('no name specified in end tag') tag = '' k = i+2 else: tag = res.group(0) k = res.end(0) if k != end.start(0): self.syntax_error('garbage in end tag') self.finish_endtag(tag) return end.end(0)
|
if not res:
|
if res is None:
|
def parse_endtag(self, i): rawdata = self.rawdata end = endbracket.search(rawdata, i+1) if not end: return -1 res = tagfind.match(rawdata, i+2) if not res: self.syntax_error('no name specified in end tag') tag = '' k = i+2 else: tag = res.group(0) k = res.end(0) if k != end.start(0): self.syntax_error('garbage in end tag') self.finish_endtag(tag) return end.end(0)
|
if k != end.start(0):
|
if endbracket.match(rawdata, k) is None:
|
def parse_endtag(self, i): rawdata = self.rawdata end = endbracket.search(rawdata, i+1) if not end: return -1 res = tagfind.match(rawdata, i+2) if not res: self.syntax_error('no name specified in end tag') tag = '' k = i+2 else: tag = res.group(0) k = res.end(0) if k != end.start(0): self.syntax_error('garbage in end tag') self.finish_endtag(tag) return end.end(0)
|
class C:
|
class Boom:
|
def test_trashcan(): # "trashcan" is a hack to prevent stack overflow when deallocating # very deeply nested tuples etc. It works in part by abusing the # type pointer and refcount fields, and that can yield horrible # problems when gc tries to traverse the structures. # If this test fails (as it does in 2.0, 2.1 and 2.2), it will # most likely die via segfault. # Note: In 2.3 the possibility for compiling without cyclic gc was # removed, and that in turn allows the trashcan mechanism to work # via much simpler means (e.g., it never abuses the type pointer or # refcount fields anymore). Since it's much less likely to cause a # problem now, the various constants in this expensive (we force a lot # of full collections) test are cut back from the 2.2 version. gc.enable() N = 150 for count in range(2): t = [] for i in range(N): t = [t, Ouch()] u = [] for i in range(N): u = [u, Ouch()] v = {} for i in range(N): v = {1: v, 2: Ouch()} gc.disable()
|
a = C() b = C()
|
a = Boom() b = Boom()
|
def test_boom(): a = C() b = C() a.attr = b b.attr = a gc.collect() garbagelen = len(gc.garbage) del a, b # a<->b are in a trash cycle now. Collection will invoke C.__getattr__ # (to see whether a and b have __del__ methods), and __getattr__ deletes # the internal "attr" attributes as a side effect. That causes the # trash cycle to get reclaimed via refcounts falling to 0, thus mutating # the trash graph as a side effect of merely asking whether __del__ # exists. This used to (before 2.3b1) crash Python. expect(gc.collect(), 0, "boom") expect(len(gc.garbage), garbagelen, "boom")
|
self._read_test(['a,\\b,c'], [['a', '\\b', 'c']], escapechar='\\')
|
self._read_test(['a,\\b,c'], [['a', 'b', 'c']], escapechar='\\')
|
def test_read_escape(self): self._read_test(['a,\\b,c'], [['a', '\\b', 'c']], escapechar='\\') self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\') self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\') self._read_test(['a,"b,\\c"'], [['a', 'b,\\c']], escapechar='\\') self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\') self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\')
|
self._read_test(['a,"b,\\c"'], [['a', 'b,\\c']], escapechar='\\')
|
self._read_test(['a,"b,\\c"'], [['a', 'b,c']], escapechar='\\')
|
def test_read_escape(self): self._read_test(['a,\\b,c'], [['a', '\\b', 'c']], escapechar='\\') self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\') self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\') self._read_test(['a,"b,\\c"'], [['a', 'b,\\c']], escapechar='\\') self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\') self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\')
|
host, port = self.socket.getsockname()
|
host, port = self.socket.getsockname()[:2]
|
def server_bind(self): """Override server_bind to store the server name.""" SocketServer.TCPServer.server_bind(self) host, port = self.socket.getsockname() self.server_name = socket.getfqdn(host) self.server_port = port
|
host, port = self.client_address
|
host, port = self.client_address[:2]
|
def address_string(self): """Return the client address formatted for logging.
|
"exclude=", "include=", "package=", "strip", "iconfile=")
|
"exclude=", "include=", "package=", "strip", "iconfile=", "lib=")
|
def main(builder=None): if builder is None: builder = AppBuilder(verbosity=1) shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa" longopts = ("builddir=", "name=", "resource=", "file=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "argv", "standalone", "exclude=", "include=", "package=", "strip", "iconfile=") try: options, args = getopt.getopt(sys.argv[1:], shortopts, longopts) except getopt.error: usage() for opt, arg in options: if opt in ('-b', '--builddir'): builder.builddir = arg elif opt in ('-n', '--name'): builder.name = arg elif opt in ('-r', '--resource'): builder.resources.append(arg) elif opt in ('-f', '--file'): srcdst = arg.split(':') if len(srcdst) != 2: usage("-f or --file argument must be two paths, " "separated by a colon") builder.files.append(srcdst) elif opt in ('-e', '--executable'): builder.executable = arg elif opt in ('-m', '--mainprogram'): builder.mainprogram = arg elif opt in ('-a', '--argv'): builder.argv_emulation = 1 elif opt in ('-c', '--creator'): builder.creator = arg elif opt == '--iconfile': builder.iconfile = arg elif opt == "--nib": builder.nibname = arg elif opt in ('-p', '--plist'): builder.plist = Plist.fromFile(arg) elif opt in ('-l', '--link'): builder.symlink = 1 elif opt == '--link-exec': builder.symlink_exec = 1 elif opt in ('-h', '--help'): usage() elif opt in ('-v', '--verbose'): builder.verbosity += 1 elif opt in ('-q', '--quiet'): builder.verbosity -= 1 elif opt == '--standalone': builder.standalone = 1 elif opt in ('-x', '--exclude'): builder.excludeModules.append(arg) elif opt in ('-i', '--include'): builder.includeModules.append(arg) elif opt == '--package': builder.includePackages.append(arg) elif opt == '--strip': builder.strip = 1 if len(args) != 1: usage("Must specify one command ('build', 'report' or 'help')") command = args[0] if command == "build": builder.setup() builder.build() elif command == "report": builder.setup() builder.report() elif command == "help": usage() else: usage("Unknown command '%s'" % command)
|
def fileConfig(fname):
|
def fileConfig(fname, defaults=None):
|
def fileConfig(fname): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). In versions of ConfigParser which have the readfp method [typically shipped in 2.x versions of Python], you can pass in a file-like object rather than a filename, in which case the file-like object will be read using readfp. """ import ConfigParser cp = ConfigParser.ConfigParser() if hasattr(cp, 'readfp') and hasattr(fname, 'readline'): cp.readfp(fname) else: cp.read(fname) #first, do the formatters... flist = cp.get("formatters", "keys") if len(flist): flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None f = logging.Formatter(fs, dfs) formatters[form] = f #next, do the handlers... #critical section... logging._acquireLock() try: try: #first, lose the existing handlers... logging._handlers.clear() #now set up the new ones... hlist = cp.get("handlers", "keys") if len(hlist): hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" klass = eval(klass, vars(logging)) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) #temporary hack for FileHandler and MemoryHandler. if klass == logging.handlers.MemoryHandler: if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for fixup in fixups: h = fixup[0] t = fixup[1] h.setTarget(handlers[t]) #at last, the loggers...first the root... llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1 except: import traceback ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) del ei finally: logging._releaseLock()
|
cp = ConfigParser.ConfigParser()
|
cp = ConfigParser.ConfigParser(defaults)
|
def fileConfig(fname): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). In versions of ConfigParser which have the readfp method [typically shipped in 2.x versions of Python], you can pass in a file-like object rather than a filename, in which case the file-like object will be read using readfp. """ import ConfigParser cp = ConfigParser.ConfigParser() if hasattr(cp, 'readfp') and hasattr(fname, 'readline'): cp.readfp(fname) else: cp.read(fname) #first, do the formatters... flist = cp.get("formatters", "keys") if len(flist): flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None f = logging.Formatter(fs, dfs) formatters[form] = f #next, do the handlers... #critical section... logging._acquireLock() try: try: #first, lose the existing handlers... logging._handlers.clear() #now set up the new ones... hlist = cp.get("handlers", "keys") if len(hlist): hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" klass = eval(klass, vars(logging)) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) #temporary hack for FileHandler and MemoryHandler. if klass == logging.handlers.MemoryHandler: if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for fixup in fixups: h = fixup[0] t = fixup[1] h.setTarget(handlers[t]) #at last, the loggers...first the root... llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1 except: import traceback ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) del ei finally: logging._releaseLock()
|
Output("PyObject_HEAD_INIT(&PyType_Type)")
|
Output("PyObject_HEAD_INIT(NULL)")
|
def outputTypeObject(self): sf = self.static and "staticforward " Output() Output("%sPyTypeObject %s = {", sf, self.typename) IndentLevel() Output("PyObject_HEAD_INIT(&PyType_Type)") Output("0, /*ob_size*/") Output("\"%s\", /*tp_name*/", self.name) Output("sizeof(%s), /*tp_basicsize*/", self.objecttype) Output("0, /*tp_itemsize*/") Output("/* methods */") Output("(destructor) %s_dealloc, /*tp_dealloc*/", self.prefix) Output("0, /*tp_print*/") Output("(getattrfunc) %s_getattr, /*tp_getattr*/", self.prefix) Output("(setattrfunc) %s_setattr, /*tp_setattr*/", self.prefix) Output("(cmpfunc) %s_compare, /*tp_compare*/", self.prefix) Output("(reprfunc) %s_repr, /*tp_repr*/", self.prefix) Output("(PyNumberMethods *)0, /* tp_as_number */") Output("(PySequenceMethods *)0, /* tp_as_sequence */") Output("(PyMappingMethods *)0, /* tp_as_mapping */") Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix) DedentLevel() Output("};")
|
__slots__ = ['_hash']
|
__slots__ = ['_hashcode']
|
def _compute_hash(self): # Calculate hash code for a set by xor'ing the hash codes of # the elements. This algorithm ensures that the hash code # does not depend on the order in which elements are added to # the code. This is not called __hash__ because a BaseSet # should not be hashable; only an ImmutableSet is hashable. result = 0 for elt in self: result ^= hash(elt) return result
|
TixWidget.__init__(self, master, 'tixDirList', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['shlist'] = _dummyScrolledHList(self, 'vsb')
|
TixWidget.__init__(self, master, 'tixListNoteBook', ['options'], cnf, kw) self.subwidget_list['pane'] = _dummyPanedWindow(self, 'pane', destroy_physically=0) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['shlist'] = _dummyScrolledHList(self, 'vsb')
|
def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirList', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['shlist'] = _dummyScrolledHList(self, 'vsb')
|
'UNICODE': ('ref/unicode', 'encodings unicode TYPES STRING'),
|
'UNICODE': ('ref/strings', 'encodings unicode TYPES STRING'),
|
def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): writedocs(path, pkgpath + file + '.', done) elif os.path.isfile(path): modname = inspect.getmodulename(path) if modname: modname = pkgpath + modname if not modname in done: done[modname] = 1 writedoc(modname)
|
'BOOLEAN': ('ref/lambda', 'EXPRESSIONS TRUTHVALUE'),
|
'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'),
|
'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
|
"""Tix maintains a list of directory under which which
|
"""Tix maintains a list of directories under which
|
def tix_addbitmapdir(self, directory): """Tix maintains a list of directory under which which the tix_getimage and tix_getbitmap commands will search for image files. The standard bitmap direc tory is $TIX_LIBRARY/bitmaps. The addbitmapdir com mand adds directory into this list. By using this command, the image files of an applications can also be located using the tix_getimage or tix_getbitmap command. """ return self.tk.call('tix', 'addbitmapdir', directory)
|
"""Query or modify the configuration options of the Tix application context. If no option is specified, returns a list describing all of the available options (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may be any of the options described in the CONFIGURATION OPTIONS section.
|
"""Query or modify the configuration options of the Tix application context. If no option is specified, returns a dictionary all of the available options. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may be any of the configuration options.
|
def tix_configure(self, cnf=None, **kw): """Query or modify the configuration options of the Tix application context. If no option is specified, returns a list describing all of the available options (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may be any of the options described in the CONFIGURATION OPTIONS section. """ return apply(self.tk.call, ('tix', configure) + self._options(cnf,kw) )
|
return apply(self.tk.call, ('tix', configure) + self._options(cnf,kw) )
|
if kw: cnf = _cnfmerge((cnf, kw)) elif cnf: cnf = _cnfmerge(cnf) if cnf is None: cnf = {} for x in self.tk.split(self.tk.call('tix', 'configure')): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if isinstance(cnf, StringType): x = self.tk.split(self.tk.call('tix', 'configure', '-'+cnf)) return (x[0][1:],) + x[1:] return self.tk.call(('tix', 'configure') + self._options(cnf))
|
def tix_configure(self, cnf=None, **kw): """Query or modify the configuration options of the Tix application context. If no option is specified, returns a list describing all of the available options (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may be any of the options described in the CONFIGURATION OPTIONS section. """ return apply(self.tk.call, ('tix', configure) + self._options(cnf,kw) )
|
"""Returns the file selection dialog that may be shared among different modules of this application. This command will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix filedialog. An optional dlgclass parameter can be passed to specified what type of file selection dialog widget is desired. Possible options are 'tix' 'FileSelectDialog' or 'tixExFileSelectDialog'.
|
"""Returns the file selection dialog that may be shared among different calls from this application. This command will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix_filedialog. An optional dlgclass parameter can be passed to specified what type of file selection dialog widget is desired. Possible options are tix FileSelectDialog or tixExFileSelectDialog.
|
def tix_filedialog(self, dlgclass=None): """Returns the file selection dialog that may be shared among different modules of this application. This command will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix filedialog. An optional dlgclass parameter can be passed to specified what type of file selection dialog widget is desired. Possible options are 'tix' 'FileSelectDialog' or 'tixExFileSelectDialog'. """ if dlgclass is not None: return self.tk.call('tix', 'filedialog', dlgclass) else: return self.tk.call('tix', 'filedialog')
|
"""Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (self, see the tix_addbitmapdir command above). By using tix_getbitmap, you can advoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the complete pathname of the bitmap file, prefixed with the character '@'. The returned value can be used to configure the -bitmap option of the TK and Tix widgets.
|
"""Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (see the tix_addbitmapdir command above). By using tix_getbitmap, you can avoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the complete pathname of the bitmap file, prefixed with the character '@'. The returned value can be used to configure the -bitmap option of the TK and Tix widgets.
|
def tix_getbitmap(self, name): """Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (self, see the tix_addbitmapdir command above). By using tix_getbitmap, you can advoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the complete pathname of the bitmap file, prefixed with the character '@'. The returned value can be used to configure the -bitmap option of the TK and Tix widgets. """ return self.tk.call('tix', 'getbitmap', name)
|
"""Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directo ries (see the addbitmapdir command above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the depth of the X display: xbm images are chosen on monochrome displays and color images are chosen on color displays. By using tix getim age, you can advoid hard coding the pathnames of the image files in your application. When success ful, this command returns the name of the newly created image, which can be used to configure the -image option of the TK and Tix widgets.
|
"""Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directories (see the addbitmapdir command above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the depth of the X display: xbm images are chosen on monochrome displays and color images are chosen on color displays. By using tix_ getimage, you can advoid hard coding the pathnames of the image files in your application. When successful, this command returns the name of the newly created image, which can be used to configure the -image option of the Tk and Tix widgets.
|
def tix_getimage(self, name): """Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directo ries (see the addbitmapdir command above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the depth of the X display: xbm images are chosen on monochrome displays and color images are chosen on color displays. By using tix getim age, you can advoid hard coding the pathnames of the image files in your application. When success ful, this command returns the name of the newly created image, which can be used to configure the -image option of the TK and Tix widgets. """ return self.tk.call('tix', 'getimage', name)
|
scheme mechanism. Available options are:
|
scheme mechanism. Available options include:
|
def tix_option_get(self, name): """Gets the options manitained by the Tix scheme mechanism. Available options are:
|
"""Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetop tions command before the creation of any widgets in a Tix application. The optional parameter newScmPrio can be given to reset the priority level of the TK options set by the Tix schemes. Because of the way TK handles the X option database, after tixwish has started up, it is not possible to reset the color schemes and font sets using the tix config command. Instead, the tix resetoptions command must be used.
|
"""Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetoptions command before the creation of any widgets in a Tix application. The optional parameter newScmPrio can be given to reset the priority level of the Tk options set by the Tix schemes. Because of the way Tk handles the X option database, after Tix has been has imported and inited, it is not possible to reset the color schemes and font sets using the tix config command. Instead, the tix_resetoptions command must be used.
|
def tix_resetoptions(self, newScheme, newFontSet, newScmPrio=None): """Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetop tions command before the creation of any widgets in a Tix application.
|
elif type(option) != type(''):
|
elif not isinstance(option, StringType):
|
def config_all(self, option, value): """Set configuration options for all subwidgets (and self).""" if option == '': return elif type(option) != type(''): option = `option` if type(value) != type(''): value = `value` names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', '-' + option, value)
|
if type(value) != type(''):
|
if not isinstance(value, StringType):
|
def config_all(self, option, value): """Set configuration options for all subwidgets (and self).""" if option == '': return elif type(option) != type(''): option = `option` if type(value) != type(''): value = `value` names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', '-' + option, value)
|
"lib", "python" + sys.version[:3])
|
"lib", "python" + get_python_version())
|
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = plat_specific and EXEC_PREFIX or PREFIX if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(prefix, "Lib") else: if sys.version < "2.2": return prefix else: return os.path.join(PREFIX, "Lib", "site-packages") elif os.name == "mac": if plat_specific: if standard_lib: return os.path.join(prefix, "Lib", "lib-dynload") else: return os.path.join(prefix, "Lib", "site-packages") else: if standard_lib: return os.path.join(prefix, "Lib") else: return os.path.join(prefix, "Lib", "site-packages") elif os.name == "os2": if standard_lib: return os.path.join(PREFIX, "Lib") else: return os.path.join(PREFIX, "Lib", "site-packages") else: raise DistutilsPlatformError( "I don't know where Python installs its library " "on platform '%s'" % os.name)
|
db.DB_INIT_LOCK | db.DB_THREAD)
|
db.DB_INIT_LOCK | db.DB_THREAD | self.envFlags)
|
def setUp(self): self.filename = self.__class__.__name__ + '.db' homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass self.env = db.DBEnv() self.env.open(homeDir, db.DB_CREATE | db.DB_INIT_MPOOL | db.DB_INIT_LOCK | db.DB_THREAD)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.