rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
content = open(filename).read()
content = open(filename,'rb').read()
def upload_file(self, command, pyversion, filename): # Sign if requested if self.sign: spawn(("gpg", "--detach-sign", "-a", filename), dry_run=self.dry_run)
The QUESTION strign ca be at most 255 characters.
The QUESTION string can be at most 255 characters.
def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262): """Display a QUESTION string which can be answered with Yes or No. Return 1 when the user clicks the Yes button. Return 0 when the user clicks the No button. Return -1 when the user clicks the Cancel button. When the user presses Return, the DEFAULT value is returned. If omitted, this is 0 (No). The QUESTION strign ca be at most 255 characters. """ d = GetNewDialog(id, -1) if not d: print "Can't get DLOG resource with id =", id return # Button assignments: # 1 = default (invisible) # 2 = Yes # 3 = No # 4 = Cancel # The question string is item 5 h = d.GetDialogItemAsControl(5) SetDialogItemText(h, lf2cr(question)) if yes != None: if yes == '': d.HideDialogItem(2) else: h = d.GetDialogItemAsControl(2) h.SetControlTitle(yes) if no != None: if no == '': d.HideDialogItem(3) else: h = d.GetDialogItemAsControl(3) h.SetControlTitle(no) if cancel != None: if cancel == '': d.HideDialogItem(4) else: h = d.GetDialogItemAsControl(4) h.SetControlTitle(cancel) d.SetDialogCancelItem(4) if default == 1: d.SetDialogDefaultItem(2) elif default == 0: d.SetDialogDefaultItem(3) elif default == -1: d.SetDialogDefaultItem(4) d.AutoSizeDialog() d.GetDialogWindow().ShowWindow() while 1: n = ModalDialog(None) if n == 1: return default if n == 2: return 1 if n == 3: return 0 if n == 4: return -1
if os.name == "posix" and os.path.basename(sys.path[-1]) == "Modules":
if (os.name == "posix" and sys.path and os.path.basename(sys.path[-1]) == "Modules"):
def makepath(*paths): dir = os.path.abspath(os.path.join(*paths)) return dir, os.path.normcase(dir)
return "lib%s%s" %( libname, self._static_lib_ext )
return "%s%s" %( libname, self._static_lib_ext )
def library_filename (self, libname): """Return the static library filename corresponding to the specified library name.""" return "lib%s%s" %( libname, self._static_lib_ext )
return "lib%s%s" %( libname, self._shared_lib_ext )
return "%s%s" %( libname, self._shared_lib_ext )
def shared_library_filename (self, libname): """Return the shared library filename corresponding to the specified library name.""" return "lib%s%s" %( libname, self._shared_lib_ext )
check_syntax("def f(): global time; import ")
check_syntax("def f(): global time; import ")
time.tzname = ("PDT", "PDT")
time.tzname = (tz_name, tz_name)
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = ("PDT", "PDT") time.daylight = 1 tz_value = _strptime.strptime("PDT", "%Z")[8] self.failUnlessEqual(tz_value, -1) finally: time.tzname = original_tzname time.daylight = original_daylight
tz_value = _strptime.strptime("PDT", "%Z")[8]
tz_value = _strptime.strptime(tz_name, "%Z")[8]
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = ("PDT", "PDT") time.daylight = 1 tz_value = _strptime.strptime("PDT", "%Z")[8] self.failUnlessEqual(tz_value, -1) finally: time.tzname = original_tzname time.daylight = original_daylight
if os.environ.get('TERM') in ('dumb', 'emacs'): return plainpager
def getpager(): """Decide what method to use for paging through text.""" if type(sys.stdout) is not types.FileType: return plainpager if not sys.stdin.isatty() or not sys.stdout.isatty(): return plainpager if os.environ.get('TERM') in ('dumb', 'emacs'): return plainpager if 'PAGER' in os.environ: if sys.platform == 'win32': # pipes completely broken in Windows return lambda text: tempfilepager(plain(text), os.environ['PAGER']) elif os.environ.get('TERM') in ('dumb', 'emacs'): return lambda text: pipepager(plain(text), os.environ['PAGER']) else: return lambda text: pipepager(text, os.environ['PAGER']) if sys.platform == 'win32' or sys.platform.startswith('os2'): return lambda text: tempfilepager(plain(text), 'more <') if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return lambda text: pipepager(text, 'less') import tempfile (fd, filename) = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more %s' % filename) == 0: return lambda text: pipepager(text, 'more') else: return ttypager finally: os.unlink(filename)
def __init__(self, completekey='tab'):
def __init__(self, completekey='tab', stdin=None, stdout=None):
def __init__(self, completekey='tab'): """Instantiate a line-oriented interpreter framework.
The optional argument is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. """
The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used. """ import sys if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout
def __init__(self, completekey='tab'): """Instantiate a line-oriented interpreter framework.
print self.intro
self.stdout.write(str(self.intro)+"\n")
def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
sys.stdout.write(self.prompt) sys.stdout.flush() line = sys.stdin.readline()
self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline()
def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
print '*** Unknown syntax:', line
self.stdout.write('*** Unknown syntax: %s\n'%line)
def default(self, line): """Called on an input line when the command prefix is not recognized.
print doc
self.stdout.write("%s\n"%str(doc))
def do_help(self, arg): if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: print doc return except AttributeError: pass print self.nohelp % (arg,) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) print self.doc_leader self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, help.keys(),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80)
print self.nohelp % (arg,)
self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
def do_help(self, arg): if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: print doc return except AttributeError: pass print self.nohelp % (arg,) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) print self.doc_leader self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, help.keys(),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80)
print self.doc_leader
self.stdout.write("%s\n"%str(self.doc_leader))
def do_help(self, arg): if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: print doc return except AttributeError: pass print self.nohelp % (arg,) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) print self.doc_leader self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, help.keys(),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80)
print header
self.stdout.write("%s\n"%str(header))
def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: print header if self.ruler: print self.ruler * len(header) self.columnize(cmds, maxcol-1) print
print self.ruler * len(header)
self.stdout.write("%s\n"%str(self.ruler * len(header)))
def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: print header if self.ruler: print self.ruler * len(header) self.columnize(cmds, maxcol-1) print
print
self.stdout.write("\n")
def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: print header if self.ruler: print self.ruler * len(header) self.columnize(cmds, maxcol-1) print
print "<empty>"
self.stdout.write("<empty>\n")
def columnize(self, list, displaywidth=80): """Display a list of strings as a compact set of columns.
print list[0]
self.stdout.write('%s\n'%str(list[0]))
def columnize(self, list, displaywidth=80): """Display a list of strings as a compact set of columns.
print " ".join(texts)
self.stdout.write("%s\n"%str(" ".join(texts)))
def columnize(self, list, displaywidth=80): """Display a list of strings as a compact set of columns.
_cache[alias] = entry
if not aliases.aliases.has_key(alias): aliases.aliases[alias] = modname
def search_function(encoding): # Cache lookup entry = _cache.get(encoding,_unknown) if entry is not _unknown: return entry # Import the module modname = encoding.replace('-', '_') modname = aliases.aliases.get(modname,modname) try: mod = __import__(modname,globals(),locals(),'*') except ImportError,why: _cache[encoding] = None return None # Now ask the module for the registry entry try: entry = tuple(mod.getregentry()) except AttributeError: entry = () if len(entry) != 4: raise SystemError,\ 'module "%s.%s" failed to register' % \ (__name__,modname) for obj in entry: if not callable(obj): raise SystemError,\ 'incompatible codecs in module "%s.%s"' % \ (__name__,modname) # Cache the encoding and its aliases _cache[encoding] = entry try: codecaliases = mod.getaliases() except AttributeError: pass else: for alias in codecaliases: _cache[alias] = entry return entry
self.addheaders = [('User-agent', server_version)]
self.addheaders = [('User-Agent', server_version)]
def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)] # manage the individual handlers self.handlers = [] self.handle_open = {} self.handle_error = {}
h.putheader(*args)
if name not in req.headers: h.putheader(*args)
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
self.__buf = self.__buf + \ (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) if _USE_MACHINE_REP: def pack_uint(self, x): if type(x) == LongType: x = int((x + 0x80000000L) % 0x100000000L - 0x80000000L) self.__buf = self.__buf + struct.pack('l', x)
self.__buf = self.__buf + struct.pack('>L', x)
def pack_uint(self, x):
raise ConversionError('Not supported')
try: self.__buf = self.__buf + struct.pack('>f', x) except struct.error, msg: raise ConversionError(msg)
def pack_float(self, x):
raise ConversionError('Not supported') if _xdr: def pack_float(self, x): try: self.__buf = self.__buf + _xdr.pack_float(x) except _xdr.error, msg: raise ConversionError(msg) def pack_double(self, x): try: self.__buf = self.__buf + _xdr.pack_double(x) except _xdr.error, msg: raise ConversionError(msg)
try: self.__buf = self.__buf + struct.pack('>d', x) except struct.error, msg: raise ConversionError(msg)
def pack_double(self, x):
x = long(ord(data[0]))<<24 | ord(data[1])<<16 | \ ord(data[2])<<8 | ord(data[3]) if x < 0x80000000L: x = int(x) return x if _USE_MACHINE_REP: def unpack_uint(self): i = self.__pos self.__pos = j = i+4 data = self.__buf[i:j] if len(data) < 4: raise EOFError return struct.unpack('l', data)[0]
x = struct.unpack('>L', data)[0] try: return int(x) except OverflowError: return x
def unpack_uint(self):
x = self.unpack_uint() if x >= 0x80000000L: x = x - 0x100000000L return int(x)
i = self.__pos self.__pos = j = i+4 data = self.__buf[i:j] if len(data) < 4: raise EOFError return struct.unpack('>l', data)[0]
def unpack_int(self):
raise ConversionError('Not supported')
i = self.__pos self.__pos = j = i+4 data = self.__buf[i:j] if len(data) < 4: raise EOFError return struct.unpack('>f', data)[0]
def unpack_float(self):
raise ConversionError('Not supported') if _xdr: def unpack_float(self): i = self.__pos self.__pos = j = i+4 data = self.__buf[i:j] if len(data) < 4: raise EOFError try: return _xdr.unpack_float(data) except _xdr.error, msg: raise ConversionError(msg) def unpack_double(self): i = self.__pos self.__pos = j = i+8 data = self.__buf[i:j] if len(data) < 8: raise EOFError try: return _xdr.unpack_double(data) except _xdr.error, msg: raise ConversionError(msg)
i = self.__pos self.__pos = j = i+8 data = self.__buf[i:j] if len(data) < 8: raise EOFError return struct.unpack('>d', data)[0]
def unpack_double(self):
n[i] = n[i].split(os.sep) if os.altsep and len(n[i]) == 1: n[i] = n[i].split(os.altsep)
n[i] = n[i].split("/")
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' n = m[:] for i in range(len(n)): n[i] = n[i].split(os.sep) # if os.sep didn't have any effect, try os.altsep if os.altsep and len(n[i]) == 1: n[i] = n[i].split(os.altsep) prefix = n[0] for item in n: for i in range(len(prefix)): if prefix[:i+1] <> item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return os.sep.join(prefix)
return os.sep.join(prefix)
return "/".join(prefix)
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' n = m[:] for i in range(len(n)): n[i] = n[i].split(os.sep) # if os.sep didn't have any effect, try os.altsep if os.altsep and len(n[i]) == 1: n[i] = n[i].split(os.altsep) prefix = n[0] for item in n: for i in range(len(prefix)): if prefix[:i+1] <> item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return os.sep.join(prefix)
elif usage.startswith("usage: "):
elif usage.lower().startswith("usage: "):
def set_usage (self, usage): if usage is None: self.usage = "%prog [options]" elif usage is SUPPRESS_USAGE: self.usage = None elif usage.startswith("usage: "): # for backwards compatibility with Optik 1.3 and earlier self.usage = usage[7:] else: self.usage = usage
data = convert_path(f[1])
data = convert_path(data)
def run (self): self.mkpath(self.install_dir) for f in self.data_files: if type(f) == StringType: # it's a simple file, so copy it f = convert_path(f) if self.warn_dir: self.warn("setup script did not provide a directory for " "'%s' -- installing right in '%s'" % (f, self.install_dir)) (out, _) = self.copy_file(f, self.install_dir) self.outfiles.append(out) else: # it's a tuple with path to install to and a list of files dir = convert_path(f[0]) if not os.path.isabs(dir): dir = os.path.join(self.install_dir, dir) elif self.root: dir = change_root(self.root, dir) self.mkpath(dir) for data in f[1]: data = convert_path(f[1]) (out, _) = self.copy_file(data, dir) self.outfiles.append(out)
filename = words[-1] infostuff = words[-5:-1]
filename = string.join(words[8:]) infostuff = words[5:]
def mirrorsubdir(f, localdir): pwd = f.pwd() if localdir and not os.path.isdir(localdir): if verbose: print 'Creating local directory', localdir try: makedir(localdir) except os.error, msg: print "Failed to establish local directory", localdir return infofilename = os.path.join(localdir, '.mirrorinfo') try: text = open(infofilename, 'r').read() except IOError, msg: text = '{}' try: info = eval(text) except (SyntaxError, NameError): print 'Bad mirror info in %s' % infofilename info = {} subdirs = [] listing = [] if verbose: print 'Listing remote directory %s...' % pwd f.retrlines('LIST', listing.append) filesfound = [] for line in listing: if verbose > 1: print '-->', `line` if mac: # Mac listing has just filenames; # trailing / means subdirectory filename = string.strip(line) mode = '-' if filename[-1:] == '/': filename = filename[:-1] mode = 'd' infostuff = '' else: # Parse, assuming a UNIX listing words = string.split(line) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue if words[-2] == '->': if verbose > 1: print 'Skipping symbolic link %s -> %s' % \ (words[-3], words[-1]) continue filename = words[-1] infostuff = words[-5:-1] mode = words[0] skip = 0 for pat in skippats: if fnmatch(filename, pat): if verbose > 1: print 'Skip pattern', pat, print 'matches', filename skip = 1 break if skip: continue if mode[0] == 'd': if verbose > 1: print 'Remembering subdirectory', filename subdirs.append(filename) continue filesfound.append(filename) if info.has_key(filename) and info[filename] == infostuff: if verbose > 1: print 'Already have this version of', filename continue fullname = os.path.join(localdir, filename) tempname = os.path.join(localdir, '@'+filename) if interactive: doit = askabout('file', filename, pwd) if not doit: if not info.has_key(filename): info[filename] = 'Not retrieved' continue try: os.unlink(tempname) except os.error: pass try: fp = open(tempname, 'wb') except IOError, msg: print "Can't create %s: %s" % (tempname, str(msg)) continue if verbose: print 'Retrieving %s from %s as %s...' % \ (filename, pwd, fullname) if verbose: fp1 = LoggingFile(fp, 1024, sys.stdout) else: fp1 = fp t0 = time.time() try: f.retrbinary('RETR ' + filename, fp1.write, 8*1024) except ftplib.error_perm, msg: print msg t1 = time.time() bytes = fp.tell() fp.close() if fp1 != fp: fp1.close() try: os.unlink(fullname) except os.error: pass # Ignore the error try: os.rename(tempname, fullname) except os.error, msg: print "Can't rename %s to %s: %s" % (tempname, fullname, str(msg)) continue info[filename] = infostuff writedict(info, infofilename) if verbose: dt = t1 - t0 kbytes = bytes / 1024.0 print int(round(kbytes)), print 'Kbytes in', print int(round(dt)), print 'seconds', if t1 > t0: print '(~%d Kbytes/sec)' % \ int(round(kbytes/dt),) print # # Remove files from info that are no longer remote deletions = 0 for filename in info.keys(): if filename not in filesfound: if verbose: print "Removing obsolete info entry for", print filename, "in", localdir or "." del info[filename] deletions = deletions + 1 if deletions: writedict(info, infofilename) # # Remove local files that are no longer in the remote directory try: if not localdir: names = os.listdir(os.curdir) else: names = os.listdir(localdir) except os.error: names = [] for name in names: if name[0] == '.' or info.has_key(name) or name in subdirs: continue skip = 0 for pat in skippats: if fnmatch(name, pat): if verbose > 1: print 'Skip pattern', pat, print 'matches', name skip = 1 break if skip: continue fullname = os.path.join(localdir, name) if not rmok: if verbose: print 'Local file', fullname, print 'is no longer pertinent' continue if verbose: print 'Removing local file/dir', fullname remove(fullname) # # Recursively mirror subdirectories for subdir in subdirs: if interactive: doit = askabout('subdirectory', subdir, pwd) if not doit: continue if verbose: print 'Processing subdirectory', subdir localsubdir = os.path.join(localdir, subdir) pwd = f.pwd() if verbose > 1: print 'Remote directory now:', pwd print 'Remote cwd', subdir try: f.cwd(subdir) except ftplib.error_perm, msg: print "Can't chdir to", subdir, ":", msg else: if verbose: print 'Mirroring as', localsubdir mirrorsubdir(f, localsubdir) if verbose > 1: print 'Remote cwd ..' f.cwd('..') newpwd = f.pwd() if newpwd != pwd: print 'Ended up in wrong directory after cd + cd ..' print 'Giving up now.' break else: if verbose > 1: print 'OK.'
del _active[_get_ident()]
if _sys.modules.has_key('dummy_threading'): try: del _active[_get_ident()] except KeyError: pass else: del _active[_get_ident()]
def __delete(self): _active_limbo_lock.acquire() del _active[_get_ident()] _active_limbo_lock.release()
self.packages = self.pimpdb.list()
packages = self.pimpdb.list() if show_hidden: self.packages = packages else: self.packages = [] for pkg in packages: name = pkg.fullname() if name[0] == '(' and name[-1] == ')' and not show_hidden: continue self.packages.append(pkg)
def getbrowserdata(self, show_hidden=1): self.packages = self.pimpdb.list() rv = [] for pkg in self.packages: name = pkg.fullname() if name[0] == '(' and name[-1] == ')' and not show_hidden: continue status, _ = pkg.installed() description = pkg.description() rv.append((status, name, description)) return rv
if name[0] == '(' and name[-1] == ')' and not show_hidden: continue
def getbrowserdata(self, show_hidden=1): self.packages = self.pimpdb.list() rv = [] for pkg in self.packages: name = pkg.fullname() if name[0] == '(' and name[-1] == ')' and not show_hidden: continue status, _ = pkg.installed() description = pkg.description() rv.append((status, name, description)) return rv
result = f % val fields = string.split(result, ".")
result = f % abs(val) fields = result.split(".")
def format(f,val,grouping=0): """Formats a value in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.""" result = f % val fields = string.split(result, ".") if grouping: fields[0]=_group(fields[0]) if len(fields)==2: return fields[0]+localeconv()['decimal_point']+fields[1] elif len(fields)==1: return fields[0] else: raise Error, "Too many decimal points in result string"
return fields[0]+localeconv()['decimal_point']+fields[1]
res = fields[0]+localeconv()['decimal_point']+fields[1]
def format(f,val,grouping=0): """Formats a value in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.""" result = f % val fields = string.split(result, ".") if grouping: fields[0]=_group(fields[0]) if len(fields)==2: return fields[0]+localeconv()['decimal_point']+fields[1] elif len(fields)==1: return fields[0] else: raise Error, "Too many decimal points in result string"
return fields[0]
res = fields[0]
def format(f,val,grouping=0): """Formats a value in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.""" result = f % val fields = string.split(result, ".") if grouping: fields[0]=_group(fields[0]) if len(fields)==2: return fields[0]+localeconv()['decimal_point']+fields[1] elif len(fields)==1: return fields[0] else: raise Error, "Too many decimal points in result string"
_nmtoken_rx = re.compile("[a-z][-._a-z0-9]*", re.IGNORECASE)
_nmtoken_rx = re.compile("[a-z][-._a-z0-9]*$", re.IGNORECASE)
def format_attrs(attrs, xml=0): attrs = attrs.items() attrs.sort() s = '' for name, value in attrs: if xml: s = '%s %s="%s"' % (s, name, escape(value)) else: # this is a little bogus, but should do for now if name == value and isnmtoken(value): s = "%s %s" % (s, value) elif istoken(value): s = "%s %s=%s" % (s, name, value) else: s = '%s %s="%s"' % (s, name, escape(value)) return s
_token_rx = re.compile("[a-z0-9][-._a-z0-9]*", re.IGNORECASE)
_token_rx = re.compile("[a-z0-9][-._a-z0-9]*$", re.IGNORECASE)
def isnmtoken(s): return _nmtoken_rx.match(s) is not None
output_dir=None):
output_dir=None, debug=0):
def link_static_lib (self, objects, output_libname, output_dir=None):
['response', ['mesg_num octets', ...]].
['response', ['mesg_num octets', ...], octets].
def list(self, which=None): """Request listing, return result.
frozendllmain_c, extensions_c] + files
frozendllmain_c, os.path.basename(extensions_c)] + files
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] exclude = [] # settable with -x option addn_link = [] # settable with -l, but only honored under Windows. path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # default the exclude list for each platform if win: exclude = exclude + [ 'dos', 'dospath', 'mac', 'macpath', 'macfs', 'MACFS', 'posix', 'os2'] # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line by first replacing any "-i" options with the file contents. pos = 1 while pos < len(sys.argv)-1: # last option can not be "-i", so this ensures "pos+1" is in range! if sys.argv[pos] == '-i': try: options = string.split(open(sys.argv[pos+1]).read()) except IOError, why: usage("File name '%s' specified with the -i option can not be read - %s" % (sys.argv[pos+1], why) ) # Replace the '-i' and the filename with the read params. sys.argv[pos:pos+2] = options pos = pos + len(options) - 1 # Skip the name and the included args. pos = pos + 1 # Now parse the command line with the extras inserted. try: opts, args = getopt.getopt(sys.argv[1:], 'a:de:hmo:p:P:qs:wx:l:') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a if o == '-x': exclude.append(a) if o == '-l': addn_link.append(a) if o == '-a': apply(modulefinder.AddPackagePath, tuple(string.split(a,"=", 2))) # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c')) # locations derived from options version = sys.version[:3] if win: extensions_c = 'frozen_extensions.c' if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_h_dir = exec_prefix config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') if win: frozendllmain_c = os.path.join(exec_prefix, 'Pc\\frozen_dllmain.c') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_h_dir = os.path.join(exec_prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') frozendllmain_c = os.path.join(binlib, 'frozen_dllmain.c') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + config_h_dir] # sanity check of directories and files check_dirs = [prefix, exec_prefix, binlib, incldir] if not win: check_dirs = check_dirs + extensions # These are not directories on Windows. for dir in check_dirs: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources + extensions # extensions are files on Windows. else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that file arguments exist for arg in args: if arg == '-m': break # if user specified -m on the command line before _any_ # file names, then nothing should be checked (as the # very first file should be a module name) if modargs: break if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' if odir: base = os.path.join(odir, '') frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) if win: extensions_c = os.path.join(odir, extensions_c) # Handle special entry point requirements # (on Windows, some frozen programs do not use __main__, but # import the module directly. Eg, DLLs, Services, etc custom_entry_point = None # Currently only used on Windows python_entry_is_main = 1 # Is the entry point called __main__? # handle -s option on Windows if win: import winmakemakefile try: custom_entry_point, python_entry_is_main = \ winmakemakefile.get_custom_entry_point(subsystem) except ValueError, why: usage(why) # Actual work starts here... # collect all modules of the program dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug, exclude) if win and subsystem=='service': # If a Windows service, then add the "built-in" module. mod = mf.add_module("servicemanager") mod.__file__="dummy.pyd" # really built-in to the resulting EXE for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) # Add the main script as either __main__, or the actual module name. if python_entry_is_main: mf.run_script(scriptfile) else: if modargs: mf.import_hook(scriptfile) else: mf.load_file(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules files = makefreeze.makefreeze(base, dict, debug, custom_entry_point) # look for unfrozen modules (builtin and of unknown origin) builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) # search for unknown modules in extensions directories (not on Windows) addfiles = [] frozen_extensions = [] # Windows list of modules. if unknown or (not win and builtins): if not win: addfiles, addmods = \ checkextensions.checkextensions(unknown+builtins, extensions) for mod in addmods: if mod in unknown: unknown.remove(mod) builtins.append(mod) else: # Do the windows thang... import checkextensions_win32 # Get a list of CExtension instances, each describing a module # (including its source files) frozen_extensions = checkextensions_win32.checkextensions( unknown, extensions) for mod in frozen_extensions: unknown.remove(mod.name) # report unknown modules if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile, checkextensions_win32 checkextensions_win32.write_extension_table(extensions_c, frozen_extensions) # Create a module definition for the bootstrap C code. xtras = [frozenmain_c, os.path.basename(frozen_c), frozendllmain_c, extensions_c] + files maindefn = checkextensions_win32.CExtension( '__main__', xtras ) frozen_extensions.append( maindefn ) outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), frozen_extensions, os.path.basename(target)) finally: outfp.close() return # generate config.c and Makefile builtins.sort() infp = open(config_c_in) outfp = bkfile.open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ files + supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] outfp = bkfile.open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
if s[0] in ('-', '+'):
if s[:1] in ('-', '+'):
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if type(x) == type(''): s = x else: s = `x` n = len(s) if n >= width: return s sign = '' if s[0] in ('-', '+'): sign, s = s[0], s[1:] return sign + '0'*(width-n) + s
elif sys.platform.startswith("netbsd"):
elif sys.platform.startswith("netbsd") or sys.platform.startswith("openbsd"):
def test_load(self): if os.name == "nt": name = "msvcrt" elif os.name == "ce": name = "coredll" elif sys.platform == "darwin": name = "libc.dylib" elif sys.platform.startswith("freebsd"): name = "libc.so" elif sys.platform == "sunos5": name = "libc.so" elif sys.platform.startswith("netbsd"): name = "libc.so" else: name = "libc.so.6"
If the population has repeated elements, then each occurence is
If the population has repeated elements, then each occurrence is
def sample(self, population, k, random=None, int=int): """Chooses k unique random elements from a population sequence.
if os.name == 'mac': def getproxies():
if sys.platform == 'darwin': def getproxies_internetconfig():
def getproxies_environment(): """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor. """ proxies = {} for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies
def translate(self, table, deletechars=""): return self.__class__(self.data.translate(table, deletechars))
def translate(self, *args): return self.__class__(self.data.translate(*args))
def translate(self, table, deletechars=""): return self.__class__(self.data.translate(table, deletechars))
if re.match(e[1], result): continue
if re.match(escapestr(e[1], ampm), result): continue
def strftest(now): if verbose: print "strftime test for", time.ctime(now) nowsecs = str(long(now))[:-1] gmt = time.gmtime(now) now = time.localtime(now) if now[3] < 12: ampm='(AM|am)' else: ampm='(PM|pm)' jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0))) try: if now[8]: tz = time.tzname[1] else: tz = time.tzname[0] except AttributeError: tz = '' if now[3] > 12: clock12 = now[3] - 12 elif now[3] > 0: clock12 = now[3] else: clock12 = 12 expectations = ( ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), ('%A', calendar.day_name[now[6]], 'full weekday name'), ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%B', calendar.month_name[now[1]], 'full month name'), # %c see below ('%d', '%02d' % now[2], 'day of month as number (00-31)'), ('%H', '%02d' % now[3], 'hour (00-23)'), ('%I', '%02d' % clock12, 'hour (01-12)'), ('%j', '%03d' % now[7], 'julian day (001-366)'), ('%m', '%02d' % now[1], 'month as number (01-12)'), ('%M', '%02d' % now[4], 'minute, (00-59)'), ('%p', ampm, 'AM or PM as appropriate'), ('%S', '%02d' % now[5], 'seconds of current time (00-60)'), ('%U', '%02d' % ((now[7] + jan1[6])//7), 'week number of the year (Sun 1st)'), ('%w', '0?%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), ('%W', '%02d' % ((now[7] + (jan1[6] - 1)%7)//7), 'week number of the year (Mon 1st)'), # %x see below ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%y', '%02d' % (now[0]%100), 'year without century'), ('%Y', '%d' % now[0], 'year with century'), # %Z see below ('%%', '%', 'single percent sign'), ) nonstandard_expectations = ( # These are standard but don't have predictable output ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), '%m/%d/%y %H:%M:%S'), ('%Z', '%s' % tz, 'time zone name'), # These are some platform specific extensions ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), ('%n', '\n', 'newline character'), ('%r', '%02d:%02d:%02d %s' % (clock12, now[4], now[5], ampm), '%I:%M:%S %p'), ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), ('%s', nowsecs, 'seconds since the Epoch in UCT'), ('%t', '\t', 'tab character'), ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%3y', '%03d' % (now[0]%100), 'year without century rendered using fieldwidth'), ) if verbose: print "Strftime test, platform: %s, Python version: %s" % \ (sys.platform, sys.version.split()[0]) for e in expectations: try: result = time.strftime(e[0], now) except ValueError, error: print "Standard '%s' format gave error:" % e[0], error continue if re.match(e[1], result): continue if not result or result[0] == '%': print "Does not support standard '%s' format (%s)" % (e[0], e[2]) else: print "Conflict for %s (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError, result: if verbose: print "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(result)) continue if re.match(e[1], result): if verbose: print "Supports nonstandard '%s' format (%s)" % (e[0], e[2]) elif not result or result[0] == '%': if verbose: print "Does not appear to support '%s' format (%s)" % (e[0], e[2]) else: if verbose: print "Conflict for nonstandard '%s' format (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result)
if re.match(e[1], result):
if re.match(escapestr(e[1], ampm), result):
def strftest(now): if verbose: print "strftime test for", time.ctime(now) nowsecs = str(long(now))[:-1] gmt = time.gmtime(now) now = time.localtime(now) if now[3] < 12: ampm='(AM|am)' else: ampm='(PM|pm)' jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0))) try: if now[8]: tz = time.tzname[1] else: tz = time.tzname[0] except AttributeError: tz = '' if now[3] > 12: clock12 = now[3] - 12 elif now[3] > 0: clock12 = now[3] else: clock12 = 12 expectations = ( ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), ('%A', calendar.day_name[now[6]], 'full weekday name'), ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%B', calendar.month_name[now[1]], 'full month name'), # %c see below ('%d', '%02d' % now[2], 'day of month as number (00-31)'), ('%H', '%02d' % now[3], 'hour (00-23)'), ('%I', '%02d' % clock12, 'hour (01-12)'), ('%j', '%03d' % now[7], 'julian day (001-366)'), ('%m', '%02d' % now[1], 'month as number (01-12)'), ('%M', '%02d' % now[4], 'minute, (00-59)'), ('%p', ampm, 'AM or PM as appropriate'), ('%S', '%02d' % now[5], 'seconds of current time (00-60)'), ('%U', '%02d' % ((now[7] + jan1[6])//7), 'week number of the year (Sun 1st)'), ('%w', '0?%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), ('%W', '%02d' % ((now[7] + (jan1[6] - 1)%7)//7), 'week number of the year (Mon 1st)'), # %x see below ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%y', '%02d' % (now[0]%100), 'year without century'), ('%Y', '%d' % now[0], 'year with century'), # %Z see below ('%%', '%', 'single percent sign'), ) nonstandard_expectations = ( # These are standard but don't have predictable output ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), '%m/%d/%y %H:%M:%S'), ('%Z', '%s' % tz, 'time zone name'), # These are some platform specific extensions ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), ('%n', '\n', 'newline character'), ('%r', '%02d:%02d:%02d %s' % (clock12, now[4], now[5], ampm), '%I:%M:%S %p'), ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), ('%s', nowsecs, 'seconds since the Epoch in UCT'), ('%t', '\t', 'tab character'), ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%3y', '%03d' % (now[0]%100), 'year without century rendered using fieldwidth'), ) if verbose: print "Strftime test, platform: %s, Python version: %s" % \ (sys.platform, sys.version.split()[0]) for e in expectations: try: result = time.strftime(e[0], now) except ValueError, error: print "Standard '%s' format gave error:" % e[0], error continue if re.match(e[1], result): continue if not result or result[0] == '%': print "Does not support standard '%s' format (%s)" % (e[0], e[2]) else: print "Conflict for %s (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError, result: if verbose: print "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(result)) continue if re.match(e[1], result): if verbose: print "Supports nonstandard '%s' format (%s)" % (e[0], e[2]) elif not result or result[0] == '%': if verbose: print "Does not appear to support '%s' format (%s)" % (e[0], e[2]) else: if verbose: print "Conflict for nonstandard '%s' format (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result)
directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout."""
directory already exists (or if 'name' is the empty string, which means the current directory, which of course exists), then do nothing. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout. Return the list of directories actually created."""
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) created_dirs = [] if os.path.isdir (name) or name == '': return created_dirs if PATH_CREATED.get (name): return created_dirs (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) created_dirs.append(head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1 return created_dirs
except os.error, (errno, errstr):
except OSError, exc:
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) created_dirs = [] if os.path.isdir (name) or name == '': return created_dirs if PATH_CREATED.get (name): return created_dirs (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) created_dirs.append(head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1 return created_dirs
"could not create '%s': %s" % (head, errstr)
"could not create '%s': %s" % (head, exc[-1])
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) created_dirs = [] if os.path.isdir (name) or name == '': return created_dirs if PATH_CREATED.get (name): return created_dirs (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) created_dirs.append(head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1 return created_dirs
archive_basename = "%s.win32" % self.distribution.get_fullname()
fullname = self.distribution.get_fullname() archive_basename = os.path.join(self.bdist_dir, "%s.win32" % fullname)
def run (self):
self.create_exe (arcname)
self.create_exe (arcname, fullname)
def run (self):
def create_exe (self, arcname):
def create_exe (self, arcname, fullname):
def create_exe (self, arcname): import struct, zlib
installer_name = "%s.win32.exe" % self.distribution.get_fullname()
installer_name = os.path.join(self.dist_dir, "%s.win32.exe" % fullname)
def create_exe (self, arcname): import struct, zlib
dir = os.path.join(self.root, dir[1:])
dir = change_root(self.root, dir)
def run (self): self.mkpath(self.install_dir) for f in self.data_files: if type(f) == StringType: # its a simple file, so copy it self.copy_file(f, self.install_dir) else: # its a tuple with path to install to and a list of files dir = f[0] if not os.path.isabs(dir): dir = os.path.join(self.install_dir, dir) elif self.root: dir = os.path.join(self.root, dir[1:]) self.mkpath(dir) for data in f[1]: self.copy_file(data, dir)
print "install_lib: compile=%s, optimize=%s" % \ (`self.compile`, `self.optimize`)
def finalize_options (self):
linelen = 0
def write(s, output=output, lineEnd='\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) else: output.write(s + lineEnd)
if linelen + len(c) >= MAXLINESIZE: if prevline is not None: write(prevline) prevline = EMPTYSTRING.join(outline) linelen = 0 outline = []
def write(s, output=output, lineEnd='\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) else: output.write(s + lineEnd)
linelen += len(c)
def write(s, output=output, lineEnd='\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) else: output.write(s + lineEnd)
prevline = EMPTYSTRING.join(outline) linelen = 0 outline = []
thisline = EMPTYSTRING.join(outline) while len(thisline) > MAXLINESIZE: write(thisline[:MAXLINESIZE-1], lineEnd='=\n') thisline = thisline[MAXLINESIZE-1:] prevline = thisline
def write(s, output=output, lineEnd='\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) else: output.write(s + lineEnd)
header.append(mapping[2*i]+256*mapping[2*i+1])
if sys.byteorder == 'big': header.append(256*mapping[2*i]+mapping[2*i+1]) else: header.append(mapping[2*i]+256*mapping[2*i+1])
def _optimize_unicode(charset, fixup): charmap = [0]*65536 negate = 0 for op, av in charset: if op is NEGATE: negate = 1 elif op is LITERAL: charmap[fixup(av)] = 1 elif op is RANGE: for i in range(fixup(av[0]), fixup(av[1])+1): charmap[i] = 1 elif op is CATEGORY: # XXX: could expand category return charset # cannot compress if negate: for i in range(65536): charmap[i] = not charmap[i] comps = {} mapping = [0]*256 block = 0 data = [] for i in range(256): chunk = tuple(charmap[i*256:(i+1)*256]) new = comps.setdefault(chunk, block) mapping[i] = new if new == block: block += 1 data += _mk_bitmap(chunk) header = [block] assert MAXCODE == 65535 for i in range(128): header.append(mapping[2*i]+256*mapping[2*i+1]) data[0:0] = header return [(BIGCHARSET, data)]
def create_inifile (self):
def get_inidata (self): lines = []
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
ini_name = "%s.ini" % metadata.get_fullname() self.announce ("creating %s" % ini_name) inifile = open (ini_name, "w")
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
inifile.write ("[metadata]\n")
lines.append ("[metadata]")
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
inifile.write ("%s=%s\n" % (name, repr (data)[1:-1]))
lines.append ("%s=%s" % (name, repr (data)[1:-1]))
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
inifile.write ("\n[Setup]\n") inifile.write ("info=%s\n" % repr (info)[1:-1]) inifile.write ("pthname=%s.%s\n" % (metadata.name, metadata.version))
lines.append ("\n[Setup]") lines.append ("info=%s" % repr (info)[1:-1]) lines.append ("pthname=%s.%s" % (metadata.name, metadata.version))
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
inifile.write ("target_version=%s\n" % self.target_version)
lines.append ("target_version=%s" % self.target_version)
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
inifile.write ("title=%s\n" % repr (title)[1:-1]) inifile.close() return ini_name
lines.append ("title=%s" % repr (title)[1:-1]) return string.join (lines, "\n")
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
import struct cfgdata = open (self.create_inifile()).read()
import struct self.mkpath(self.dist_dir) cfgdata = self.get_inidata()
def create_exe (self, arcname, fullname): import struct#, zlib
def __init__(self, bufsize=2**16 ): self._bufsize=bufsize XMLReader.__init__( self ) def parse(self, source): self.prepareParser(source) inf=open( source ) buffer = inf.read(self._bufsize)
def __init__(self, bufsize=2**16): self._bufsize = bufsize XMLReader.__init__(self) def _parseOpenFile(self, source): buffer = source.read(self._bufsize)
def __init__(self, bufsize=2**16 ): self._bufsize=bufsize XMLReader.__init__( self )
buffer = inf.read(self._bufsize)
buffer = source.read(self._bufsize)
def parse(self, source): self.prepareParser(source) #FIXME: do some type checking: could be already stream, URL or # filename inf=open( source ) buffer = inf.read(self._bufsize) while buffer != "": self.feed(buffer) buffer = inf.read(self._bufsize) self.close() self.reset()
host = urlparse.urlparse(req.get_full_url())[1]
host = req.get_host()
def do_open(self, http_class, req): host = urlparse.urlparse(req.get_full_url())[1] if not host: raise URLError('no host given')
if not __debug__: expected = [ev for ev in expected if ev[0] != LINE]
def check_events(self, expected): events = self.get_events_wotime() if not __debug__: # Running under -O, so we don't get LINE events expected = [ev for ev in expected if ev[0] != LINE] if events != expected: self.fail( "events did not match expectation; got:\n%s\nexpected:\n%s" % (pprint.pformat(events), pprint.pformat(expected)))
def start_doctype_decl(self, name, pubid, sysid, has_internal_subset):
def start_doctype_decl(self, name, sysid, pubid, has_internal_subset):
def start_doctype_decl(self, name, pubid, sysid, has_internal_subset): self._lex_handler_prop.startDTD(name, pubid, sysid)
writer.write("\n PUBLIC '%s'\n '%s'" % (self.publicId, self.systemId))
writer.write("%s PUBLIC '%s'%s '%s'" % (newl, self.publicId, newl, self.systemId))
def writexml(self, writer, indent="", addindent="", newl=""): writer.write("<!DOCTYPE ") writer.write(self.name) if self.publicId: writer.write("\n PUBLIC '%s'\n '%s'" % (self.publicId, self.systemId)) elif self.systemId: writer.write("\n SYSTEM '%s'" % self.systemId) if self.internalSubset is not None: writer.write(" [") writer.write(self.internalSubset) writer.write("]") writer.write(">\n")
writer.write("\n SYSTEM '%s'" % self.systemId)
writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
def writexml(self, writer, indent="", addindent="", newl=""): writer.write("<!DOCTYPE ") writer.write(self.name) if self.publicId: writer.write("\n PUBLIC '%s'\n '%s'" % (self.publicId, self.systemId)) elif self.systemId: writer.write("\n SYSTEM '%s'" % self.systemId) if self.internalSubset is not None: writer.write(" [") writer.write(self.internalSubset) writer.write("]") writer.write(">\n")
writer.write(">\n")
writer.write(">"+newl)
def writexml(self, writer, indent="", addindent="", newl=""): writer.write("<!DOCTYPE ") writer.write(self.name) if self.publicId: writer.write("\n PUBLIC '%s'\n '%s'" % (self.publicId, self.systemId)) elif self.systemId: writer.write("\n SYSTEM '%s'" % self.systemId) if self.internalSubset is not None: writer.write(" [") writer.write(self.internalSubset) writer.write("]") writer.write(">\n")
writer.write('<?xml version="1.0" ?>\n') else: writer.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
writer.write('<?xml version="1.0" ?>'+newl) else: writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
def writexml(self, writer, indent="", addindent="", newl="", encoding = None): if encoding is None: writer.write('<?xml version="1.0" ?>\n') else: writer.write('<?xml version="1.0" encoding="%s"?>\n' % encoding) for node in self.childNodes: node.writexml(writer, indent, addindent, newl)
print 'shlex: reading from %s, line %d' % (self.instream,self.lineno)
print 'shlex: reading from %s, line %d' \ % (self.instream, self.lineno)
def __init__(self, instream=None, infile=None): if instream: self.instream = instream self.infile = infile else: self.instream = sys.stdin self.infile = None self.commenters = '#' self.wordchars = 'abcdfeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' self.whitespace = ' \t\r\n' self.quotes = '\'"' self.state = ' ' self.pushback = []; self.lineno = 1 self.debug = 0 self.token = ''
self.filestack = [(self.infile,self.instream,self.lineno)] + self.filestack
self.filestack.insert(0, (self.infile, self.instream, self.lineno))
def get_token(self): "Get a token from the input stream (or from stack if it's nonempty)" if self.pushback: tok = self.pushback[0] self.pushback = self.pushback[1:] if self.debug >= 1: print "shlex: popping token " + `tok` return tok
print 'shlex: popping to %s, line %d' % (self.instream, self.lineno)
print 'shlex: popping to %s, line %d' \ % (self.instream, self.lineno)
def get_token(self): "Get a token from the input stream (or from stack if it's nonempty)" if self.pushback: tok = self.pushback[0] self.pushback = self.pushback[1:] if self.debug >= 1: print "shlex: popping token " + `tok` return tok
print "shlex: in state " + repr(self.state) + " I see character: " + repr(nextchar)
print "shlex: in state", repr(self.state), \ "I see character:", repr(nextchar)
def read_token(self): "Read a token from the input stream (no pushback or inclusions)" tok = '' while 1: nextchar = self.instream.read(1); if nextchar == '\n': self.lineno = self.lineno + 1 if self.debug >= 3: print "shlex: in state " + repr(self.state) + " I see character: " + repr(nextchar) if self.state == None: self.token = ''; # past end of file break elif self.state == ' ': if not nextchar: self.state = None; # end of file break elif nextchar in self.whitespace: if self.debug >= 2: print "shlex: I see whitespace in whitespace state" if self.token: break # emit current token else: continue elif nextchar in self.commenters: self.instream.readline() self.lineno = self.lineno + 1 elif nextchar in self.wordchars: self.token = nextchar self.state = 'a' elif nextchar in self.quotes: self.token = nextchar self.state = nextchar else: self.token = nextchar if self.token: break # emit current token else: continue elif self.state in self.quotes: self.token = self.token + nextchar if nextchar == self.state: self.state = ' ' break elif self.state == 'a': if not nextchar: self.state = None; # end of file break elif nextchar in self.whitespace: if self.debug >= 2: print "shlex: I see whitespace in word state" self.state = ' ' if self.token: break # emit current token else: continue elif nextchar in self.commenters: self.instream.readline() self.lineno = self.lineno + 1 elif nextchar in self.wordchars or nextchar in self.quotes: self.token = self.token + nextchar else: self.pushback = [nextchar] + self.pushback if self.debug >= 2: print "shlex: I see punctuation in word state" self.state = ' ' if self.token: break # emit current token else: continue result = self.token self.token = '' if self.debug > 1: if result: print "shlex: raw token=" + `result` else: print "shlex: raw token=EOF" return result
lexer = shlex()
if len(sys.argv) == 1: lexer = shlex() else: file = sys.argv[1] lexer = shlex(open(file), file)
def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if not infile: infile = self.infile if not lineno: lineno = self.lineno return "\"%s\", line %d: " % (infile, lineno)
print "Token: " + repr(tt) if not tt:
if tt: print "Token: " + repr(tt) else:
def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if not infile: infile = self.infile if not lineno: lineno = self.lineno return "\"%s\", line %d: " % (infile, lineno)
if not size:
readsize = 1024 if not size:
def read(self,size=None):
self._read()
self._read(readsize) readsize = readsize * 2
def read(self,size=None):
def _read(self): buf = self.fileobj.read(1024)
def _unread(self, buf): self.extrabuf = buf + self.extrabuf self.extrasize = len(buf) + self.extrasize def _read(self, size=1024): try: buf = self.fileobj.read(size) except AttributeError: raise EOFError, "Reached EOF"
def _read(self):
line=""
bufs = [] readsize = 100
def readline(self):
c = self.read(1) line = line + c if c=='\n' or c=="": break return line
c = self.read(readsize) i = string.find(c, '\n') if i >= 0 or c == '': bufs.append(c[:i]) self._unread(c[i+1:]) return string.join(bufs, '') bufs.append(c) readsize = readsize * 2
def readline(self):
L=[] line = self.readline() while line!="": L.append(line) line = self.readline() return L
buf = self.read() return string.split(buf, '\n')
def readlines(self):
if islink(component): resolved = os.readlink(component) (dir, file) = split(component) resolved = normpath(join(dir, resolved)) newpath = join(*([resolved] + bits[i:])) return realpath(newpath)
if islink(component): resolved = _resolve_link(component) if resolved is None: return join(*([component] + bits[i:])) else: newpath = join(*([resolved] + bits[i:])) return realpath(newpath)
def realpath(filename): """Return the canonical path of the specified filename, eliminating any