rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
ckmsg(s, "'continue' not supported inside 'finally' clause")
if sys.platform.startswith('java'): print "'continue' not supported inside 'finally' clause" print "ok" else: ckmsg(s, "'continue' not supported inside 'finally' clause")
def ckmsg(src, msg): try: compile(src, '<fragment>', 'exec') except SyntaxError, e: print e.msg if e.msg == msg: print "ok" else: print "expected:", msg else: print "failed to get expected SyntaxError"
test_capi1()
def test_capi1(): try: _testcapi.raise_exception(BadException, 1) except TypeError, err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code assert co.co_name == "test_capi1" assert co.co_filename.endswith('test_exceptions.py') else: print "Expected exception"
test_capi2()
if not sys.platform.startswith('java'): test_capi1() test_capi2()
def test_capi2(): try: _testcapi.raise_exception(BadException, 0) except RuntimeError, err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code assert co.co_name == "__init__" assert co.co_filename.endswith('test_exceptions.py') co2 = tb.tb_frame.f_back.f_code assert co2.co_name == "test_capi2" else: print "Expected exception"
self.addr = sock.getpeername()
try: self.addr = sock.getpeername() except socket.error: pass
def __init__ (self, sock=None, map=None): if sock: self.set_socket (sock, map) # I think it should inherit this anyway self.socket.setblocking (0) self.connected = 1 self.addr = sock.getpeername() else: self.socket = None
verify(L == ['Commented Bar', 'Foo Bar', 'Internationalized Stuff', 'Spacey Bar'],
verify(L == [r'Commented Bar', r'Foo Bar', r'Internationalized Stuff', r'Section\with$weird%characters[' '\t', r'Spacey Bar', ],
def basic(src): print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() verify(L == ['Commented Bar', 'Foo Bar', 'Internationalized Stuff', 'Spacey Bar'], "unexpected list of section names") # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 verify(cf.get('Foo Bar', 'foo', raw=1) == 'bar') verify(cf.get('Spacey Bar', 'foo', raw=1) == 'bar') verify(cf.get('Commented Bar', 'foo', raw=1) == 'bar') verify('__name__' not in cf.options("Foo Bar"), '__name__ "option" should not be exposed by the API!') # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: verify(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report existance of option") verify(not cf.has_option('Foo Bar', 'foo'), "remove_option() failed to remove option") verify(not cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
for i in range(0, 256):
for i in [0, 8, 16, 32, 64, 127, 128, 255]:
def test(expression, result, exception=None): try: r = eval(expression) except: if exception: if not isinstance(sys.exc_value, exception): print expression, "FAILED" # display name, not actual value if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got", sys.exc_type.__name__, str(sys.exc_value) else: print expression, "FAILED" traceback.print_exc(file=sys.stdout) else: if exception: print expression, "FAILED" if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got result", repr(r) else: if r != result: print expression, "FAILED" print "expected", repr(result) print "got result", repr(r)
assert gc.collect() == 1
if gc.collect() != 1: raise TestFailed
def test_list(): l = [] l.append(l) gc.collect() del l assert gc.collect() == 1
assert gc.collect() == 1
if gc.collect() != 1: raise TestFailed
def test_dict(): d = {} d[1] = d gc.collect() del d assert gc.collect() == 1
assert gc.collect() == 2
if gc.collect() != 2: raise TestFailed
def test_tuple(): # since tuples are immutable we close the loop with a list l = [] t = (l,) l.append(t) gc.collect() del t del l assert gc.collect() == 2
assert gc.collect() > 0
if gc.collect() == 0: raise TestFailed
def test_class(): class A: pass A.a = A gc.collect() del A assert gc.collect() > 0
assert gc.collect() > 0
if gc.collect() == 0: raise TestFailed
def test_instance(): class A: pass a = A() a.a = a gc.collect() del a assert gc.collect() > 0
assert gc.collect() > 0
if gc.collect() == 0: raise TestFailed
def __init__(self): self.init = self.__init__
gc.garbage[:] = []
def __del__(self): pass
assert gc.collect() > 0 assert id(gc.garbage[0]) == id_a
if gc.collect() == 0: raise TestFailed for obj in gc.garbage: if id(obj) == id_a: del obj.a break else: raise TestFailed gc.garbage.remove(obj)
def __del__(self): pass
assert gc.collect() == 2
if gc.collect() != 2: raise TestFailed def test_saveall(): debug = gc.get_debug() gc.set_debug(debug | gc.DEBUG_SAVEALL) l = [] l.append(l) id_l = id(l) del l gc.collect() try: for obj in gc.garbage: if id(obj) == id_l: del obj[:] break else: raise TestFailed gc.garbage.remove(obj) finally: gc.set_debug(debug)
exec("def f(): pass\n") in d
"paragraph", "subparagraph")
"paragraph", "subparagraph", "description", "opcodedesc", "classdesc", "funcdesc", "methoddesc", "excdesc", "datadesc", "funcdescni", "methoddescni", "excdescni", "datadescni", )
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == xml.dom.core.ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
"moduleinfo", "title", "opcodedesc", "verbatim", "funcdesc", "methoddesc", "excdesc", "datadesc",
"moduleinfo", "title", "verbatim", "opcodedesc", "classdesc", "funcdesc", "methoddesc", "excdesc", "datadesc",
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == xml.dom.core.ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
i = 0
i = len(children)
def fixup_paras_helper(doc, container): # document is already normalized children = container.childNodes start = 0 start_fixed = 0 i = 0 SKIP_ELEMENTS = PARA_LEVEL_ELEMENTS + PARA_LEVEL_PRECEEDERS for child in children: if child.nodeType == xml.dom.core.ELEMENT: if child.tagName in FIXUP_PARA_ELEMENTS: fixup_paras_helper(doc, child) break elif child.tagName in SKIP_ELEMENTS: if not start_fixed: start = i + 1 elif not start_fixed: start_fixed = 1 i = i + 1 else: if child.nodeType == xml.dom.core.TEXT \ and string.strip(child.data) and not start_fixed: start_fixed = 1 i = i + 1 if DEBUG_PARA_FIXER: sys.stderr.write("fixup_paras_helper() called on <%s>; %d, %d\n" % (container.tagName, start, i)) if i > start: # the first [start:i] children shoudl be rewritten as <para> elements # start by breaking text nodes that contain \n\n+ into multiple nodes nstart, i = skip_leading_nodes(container.childNodes, start, i) if i > nstart: build_para(doc, container, nstart, i) fixup_paras_helper(doc, container)
for child in children: if child.nodeType == xml.dom.core.ELEMENT: if child.tagName in FIXUP_PARA_ELEMENTS: fixup_paras_helper(doc, child) break elif child.tagName in SKIP_ELEMENTS: if not start_fixed: start = i + 1 elif not start_fixed: start_fixed = 1 i = i + 1 else: if child.nodeType == xml.dom.core.TEXT \ and string.strip(child.data) and not start_fixed: start_fixed = 1 i = i + 1
def fixup_paras_helper(doc, container): # document is already normalized children = container.childNodes start = 0 start_fixed = 0 i = 0 SKIP_ELEMENTS = PARA_LEVEL_ELEMENTS + PARA_LEVEL_PRECEEDERS for child in children: if child.nodeType == xml.dom.core.ELEMENT: if child.tagName in FIXUP_PARA_ELEMENTS: fixup_paras_helper(doc, child) break elif child.tagName in SKIP_ELEMENTS: if not start_fixed: start = i + 1 elif not start_fixed: start_fixed = 1 i = i + 1 else: if child.nodeType == xml.dom.core.TEXT \ and string.strip(child.data) and not start_fixed: start_fixed = 1 i = i + 1 if DEBUG_PARA_FIXER: sys.stderr.write("fixup_paras_helper() called on <%s>; %d, %d\n" % (container.tagName, start, i)) if i > start: # the first [start:i] children shoudl be rewritten as <para> elements # start by breaking text nodes that contain \n\n+ into multiple nodes nstart, i = skip_leading_nodes(container.childNodes, start, i) if i > nstart: build_para(doc, container, nstart, i) fixup_paras_helper(doc, container)
print >> self.stream, "Welcome to the profile statistics browser."
def postcmd(self, stop, line): if stop: return stop return None
ProfileBrowser(initprofile).cmdloop() print >> self.stream, "Goodbye."
browser = ProfileBrowser(initprofile) print >> browser.stream, "Welcome to the profile statistics browser." browser.cmdloop() print >> browser.stream, "Goodbye."
def postcmd(self, stop, line): if stop: return stop return None
self.interaction(frame, None)
if self.bp_commands(frame): self.interaction(frame, None) def bp_commands(self,frame): """ Call every command that was set for the current active breakpoint (if there is one) Returns True if the normal interaction function must be called, False otherwise """ if getattr(self,"currentbp",False) and self.currentbp in self.commands: currentbp = self.currentbp self.currentbp = 0 lastcmd_back = self.lastcmd self.setup(frame, None) for line in self.commands[currentbp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[currentbp]: self.print_stack_entry(self.stack[self.curindex]) if self.commands_doprompt[currentbp]: self.cmdloop() self.forget() return return 1
def user_line(self, frame): """This function is called when we stop or break at this line.""" if self._wait_for_mainpyfile: if (self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno<= 0): return self._wait_for_mainpyfile = 0 self.interaction(frame, None)
submsgobj = self.parsestr(part) msgobj.attach(submsgobj)
def _parsebody(self, container, fp): # Parse the body, but first split the payload on the content-type # boundary if present. boundary = container.get_boundary() isdigest = (container.get_content_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately. Otherwise, just parse the rest of # the body as a single message. Note: any exceptions raised in the # recursive parse need to have their line numbers coerced. if boundary: preamble = epilogue = None # Split into subparts. The first boundary we're looking for won't # always have a leading newline since we're at the start of the # body text, and there's not always a preamble before the first # boundary. separator = '--' + boundary payload = fp.read() # We use an RE here because boundaries can have trailing # whitespace. mo = re.search( r'(?P<sep>' + re.escape(separator) + r')(?P<ws>[ \t]*)', payload) if not mo: if self._strict: raise Errors.BoundaryError( "Couldn't find starting boundary: %s" % boundary) container.set_payload(payload) return start = mo.start() if start > 0: # there's some pre-MIME boundary preamble preamble = payload[0:start] # Find out what kind of line endings we're using start += len(mo.group('sep')) + len(mo.group('ws')) mo = nlcre.search(payload, start) if mo: start += len(mo.group(0)) # We create a compiled regexp first because we need to be able to # specify the start position, and the module function doesn't # support this signature. :( cre = re.compile('(?P<sep>\r\n|\r|\n)' + re.escape(separator) + '--') mo = cre.search(payload, start) if mo: terminator = mo.start() linesep = mo.group('sep') if mo.end() < len(payload): # There's some post-MIME boundary epilogue epilogue = payload[mo.end():] elif self._strict: raise Errors.BoundaryError( "Couldn't find terminating boundary: %s" % boundary) else: # Handle the case of no trailing boundary. Check that it ends # in a blank line. Some cases (spamspamspam) don't even have # that! mo = re.search('(?P<sep>\r\n|\r|\n){2}$', payload) if not mo: mo = re.search('(?P<sep>\r\n|\r|\n)$', payload) if not mo: raise Errors.BoundaryError( 'No terminating boundary and no trailing empty line') linesep = mo.group('sep') terminator = len(payload) # We split the textual payload on the boundary separator, which # includes the trailing newline. If the container is a # multipart/digest then the subparts are by default message/rfc822 # instead of text/plain. In that case, they'll have a optional # block of MIME headers, then an empty line followed by the # message headers. parts = re.split( linesep + re.escape(separator) + r'[ \t]*' + linesep, payload[start:terminator]) for part in parts: if isdigest: if part.startswith(linesep): # There's no header block so create an empty message # object as the container, and lop off the newline so # we can parse the sub-subobject msgobj = self._class() part = part[len(linesep):] else: parthdrs, part = part.split(linesep+linesep, 1) # msgobj in this case is the "message/rfc822" container msgobj = self.parsestr(parthdrs, headersonly=1) # while submsgobj is the message itself submsgobj = self.parsestr(part) msgobj.attach(submsgobj) msgobj.set_default_type('message/rfc822') else: msgobj = self.parsestr(part) container.preamble = preamble container.epilogue = epilogue container.attach(msgobj) elif container.get_main_type() == 'multipart': # Very bad. A message is a multipart with no boundary! raise Errors.BoundaryError( 'multipart message with no defined boundary') elif container.get_type() == 'message/delivery-status': # This special kind of type contains blocks of headers separated # by a blank line. We'll represent each header block as a # separate Message object blocks = [] while True: blockmsg = self._class() self._parseheaders(blockmsg, fp) if not len(blockmsg): # No more header blocks left break blocks.append(blockmsg) container.set_payload(blocks) elif container.get_main_type() == 'message': # Create a container for the payload, but watch out for there not # being any headers left try: msg = self.parse(fp) except Errors.HeaderParseError: msg = self._class() self._parsebody(msg, fp) container.attach(msg) else: container.set_payload(fp.read())
on connect to the Net for testing.
on connecting to the Net for testing.
def hexescape(char): """Escape char as RFC 2396 specifies""" hex_repr = hex(ord(char))[2:].upper() if len(hex_repr) == 1: hex_repr = "0%s" % hex_repr return "%" + hex_repr
from os.path import normpath, join, dirname for (name, value) in done.items(): if value[0:2] == "./": done[name] = normpath(join(dirname(fp.name), value))
def parse_makefile(fp, g=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if g is None: g = {} variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} # while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # "Fix" all pathnames in the Makefile that are explicitly relative, # ie. that start with "./". This is a kludge to fix the "./ld_so_aix" # problem, the nature of which is that Python's installed Makefile # refers to "./ld_so_aix", but when we are building extensions we are # far from the directory where Python's Makefile (and ld_so_aix, for # that matter) is installed. Unfortunately, there are several other # relative pathnames in the Makefile, and this fix doesn't fix them, # because the layout of Python's source tree -- which is what the # Makefile refers to -- is not fully preserved in the Python # installation. Grumble. from os.path import normpath, join, dirname for (name, value) in done.items(): if value[0:2] == "./": done[name] = normpath(join(dirname(fp.name), value)) # save the results in the global dictionary g.update(done) return g
testtar = path("testtar" + os.extsep + "tar") tempdir = path("testtar" + os.extsep + "dir") tempname = path("testtar" + os.extsep + "tmp")
testtar = path("testtar.tar") tempdir = os.path.join(tempfile.gettempdir(), "testtar" + os.extsep + "dir") tempname = test_support.TESTFN
def path(path): return test_support.findfile(path)
if os.path.exists(tempdir): shutil.rmtree(tempdir) if os.path.exists(tempname): os.remove(tempname)
if os.path.exists(dirname()): shutil.rmtree(dirname()) if os.path.exists(tmpname()): os.remove(tmpname())
def test_main(): if gzip: # create testtar.tar.gz gzip.open(tarname("gz"), "wb").write(file(tarname(), "rb").read()) if bz2: # create testtar.tar.bz2 bz2.BZ2File(tarname("bz2"), "wb").write(file(tarname(), "rb").read()) tests = [ ReadTest, ReadStreamTest, WriteTest, WriteStreamTest ] if gzip: tests.extend([ ReadTestGzip, ReadStreamTestGzip, WriteTestGzip, WriteStreamTestGzip ]) if bz2: tests.extend([ ReadTestBzip2, ReadStreamTestBzip2, WriteTestBzip2, WriteStreamTestBzip2 ]) try: test_support.run_unittest(*tests) finally: if gzip: os.remove(tarname("gz")) if bz2: os.remove(tarname("bz2")) if os.path.exists(tempdir): shutil.rmtree(tempdir) if os.path.exists(tempname): os.remove(tempname)
return whatever**2
return arg**2
def m1(self, arg): return whatever**2
sys.stderr.write('MH error: %\n' % (msg % args))
sys.stderr.write('MH error: %s\n' % (msg % args))
def error(self, msg, *args): sys.stderr.write('MH error: %\n' % (msg % args))
mode = eval('0' + protect)
mode = string.atoi(protect, 8)
def makefolder(self, name): protect = pickline(self.profile, 'Folder-Protect') if protect and isnumeric(protect): mode = eval('0' + protect) else: mode = FOLDER_PROTECT os.mkdir(os.path.join(self.getpath(), name), mode)
if isnumeric(name): messages.append(eval(name))
if name[0] != "," and \ numericprog.match(name) == len(name): messages.append(string.atoi(name))
def listmessages(self): messages = [] for name in os.listdir(self.getfullname()): if isnumeric(name): messages.append(eval(name)) messages.sort() if messages: self.last = max(messages) else: self.last = 0 return messages
path = self.getmessagefilename(n)
def openmessage(self, n): path = self.getmessagefilename(n) return Message(self, n)
newline = '%s: %s' % (key, value)
newline = '%s: %s\n' % (key, value)
def updateline(file, key, value, casefold = 1): try: f = open(file, 'r') lines = f.readlines() f.close() except IOError: lines = [] pat = key + ':\(.*\)\n' if casefold: prog = regex.compile(pat, regex.casefold) else: prog = regex.compile(pat) if value is None: newline = None else: newline = '%s: %s' % (key, value) for i in range(len(lines)): line = lines[i] if prog.match(line) == len(line): if newline is None: del lines[i] else: lines[i] = newline break else: if newline is not None: lines.append(newline) f = open(tempfile, 'w') for line in lines: f.write(line) f.close()
common = filter(big._data.has_key, little._data)
common = ifilter(big._data.has_key, little)
def __and__(self, other): """Return the intersection of two sets as a new set.
for elt in selfdata: if elt not in otherdata: data[elt] = value for elt in otherdata: if elt not in selfdata: data[elt] = value
for elt in ifilter(otherdata.has_key, selfdata, True): data[elt] = value for elt in ifilter(selfdata.has_key, otherdata, True): data[elt] = value
def __xor__(self, other): """Return the symmetric difference of two sets as a new set.
otherdata = other._data
def __sub__(self, other): """Return the difference of two sets as a new Set.
for elt in self: if elt not in otherdata: data[elt] = value
for elt in ifilter(other._data.has_key, self, True): data[elt] = value
def __sub__(self, other): """Return the difference of two sets as a new Set.
otherdata = other._data for elt in self: if elt not in otherdata: return False
for elt in ifilter(other._data.has_key, self, True): return False
def issubset(self, other): """Report whether another set contains this set.""" self._binary_sanity_check(other) if len(self) > len(other): # Fast check for obvious cases return False otherdata = other._data for elt in self: if elt not in otherdata: return False return True
selfdata = self._data for elt in other: if elt not in selfdata:
for elt in ifilter(self._data.has_key, other, True):
def issuperset(self, other): """Report whether this set contains another set.""" self._binary_sanity_check(other) if len(self) < len(other): # Fast check for obvious cases return False selfdata = self._data for elt in other: if elt not in selfdata: return False return True
self.stack = get_stack(tb) self.text = get_exception()
self.stack = self.get_stack(tb) self.text = self.get_exception() def get_stack(self, tb): if tb is None: tb = sys.last_traceback stack = [] if tb and tb.tb_frame is None: tb = tb.tb_next while tb is not None: stack.append((tb.tb_frame, tb.tb_lineno)) tb = tb.tb_next return stack def get_exception(self): type = sys.last_type value = sys.last_value if hasattr(type, "__name__"): type = type.__name__ s = str(type) if value is not None: s = s + ": " + str(value) return s
def __init__(self, flist=None, tb=None): self.flist = flist self.stack = get_stack(tb) self.text = get_exception()
def get_stack(t=None, f=None): if t is None: t = sys.last_traceback stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next return stack def get_exception(type=None, value=None): if type is None: type = sys.last_type value = sys.last_value if hasattr(type, "__name__"): type = type.__name__ s = str(type) if value is not None: s = s + ": " + str(value) return s
def get_stack(t=None, f=None): if t is None: t = sys.last_traceback stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next return stack
manifest = open (self.manifest, "w") for fn in self.files: manifest.write (fn + '\n') manifest.close ()
self.execute(write_file, (self.manifest, self.files), "writing manifest file")
def write_manifest (self): """Write the file list in 'self.files' (presumably as filled in by 'find_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'."""
("Visual Studio 2003 needs to be installed before " "building extensions for Python.")
("""Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
def load_macros(self, version): vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir") self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir") net = r"Software\Microsoft\.NETFramework" self.set_macro("FrameworkDir", net, "installroot") try: if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") except KeyError, exc: # raise DistutilsPlatformError, \ ("Visual Studio 2003 needs to be installed before " "building extensions for Python.")
expect(gc.collect(), 0, "boom")
expect(gc.collect(), 4, "boom")
def test_boom(): a = Boom() b = Boom() 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 Boom.__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")
'BuildRoot: %{_tmppath}/%{name}-buildroot',
'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version(), '%define release ' + self.release, '', 'Summary: ' + self.distribution.get_description(), ]
if isinstance(host, TupleType): host, x509 = host else: x509 = {}
host, extra_headers, x509 = self.get_host_info(host)
def make_connection(self, host): # create a HTTPS connection object from a host descriptor # host may be a string, or a (host, x509-dict) tuple import httplib if isinstance(host, TupleType): host, x509 = host else: x509 = {} try: HTTPS = httplib.HTTPS except AttributeError: raise NotImplementedError,\ "your version of httplib doesn't support HTTPS" else: return apply(HTTPS, (host, None), x509)
raise NotImplementedError,\ "your version of httplib doesn't support HTTPS"
raise NotImplementedError( "your version of httplib doesn't support HTTPS" )
def make_connection(self, host): # create a HTTPS connection object from a host descriptor # host may be a string, or a (host, x509-dict) tuple import httplib if isinstance(host, TupleType): host, x509 = host else: x509 = {} try: HTTPS = httplib.HTTPS except AttributeError: raise NotImplementedError,\ "your version of httplib doesn't support HTTPS" else: return apply(HTTPS, (host, None), x509)
return apply(HTTPS, (host, None), x509) def send_host(self, connection, host): if isinstance(host, TupleType): host, x509 = host connection.putheader("Host", host)
return apply(HTTPS, (host, None), x509 or {})
def make_connection(self, host): # create a HTTPS connection object from a host descriptor # host may be a string, or a (host, x509-dict) tuple import httplib if isinstance(host, TupleType): host, x509 = host else: x509 = {} try: HTTPS = httplib.HTTPS except AttributeError: raise NotImplementedError,\ "your version of httplib doesn't support HTTPS" else: return apply(HTTPS, (host, None), x509)
_hostprog = re.compile('^//([^/]*)(.*)$')
_hostprog = re.compile('^//([^/?]*)(.*)$')
def splithost(url): """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" global _hostprog if _hostprog is None: import re _hostprog = re.compile('^//([^/]*)(.*)$') match = _hostprog.match(url) if match: return match.group(1, 2) return None, url
"timzone value not set to -1")
"timezone value not set to -1")
def test_timezone(self): # Test timezone directives. # When gmtime() is used with %Z, entire result of strftime() is empty. # Check for equal timezone names deals with bad locale info when this # occurs; first found in FreeBSD 4.4. strp_output = _strptime.strptime("UTC", "%Z") self.failUnlessEqual(strp_output.tm_isdst, 0) strp_output = _strptime.strptime("GMT", "%Z") self.failUnlessEqual(strp_output.tm_isdst, 0) time_tuple = time.localtime() strf_output = time.strftime("%Z") #UTC does not have a timezone strp_output = _strptime.strptime(strf_output, "%Z") locale_time = _strptime.LocaleTime() if time.tzname[0] != time.tzname[1]: self.failUnless(strp_output[8] == time_tuple[8], "timezone check failed; '%s' -> %s != %s" % (strf_output, strp_output[8], time_tuple[8])) else: self.failUnless(strp_output[8] == -1, "LocaleTime().timezone has duplicate values but " "timzone value not set to -1")
n = m[:] for i in range(len(n)): n[i] = n[i].split(os.sep) if os.altsep and len(n[i]) == 1: n[i] = n[i].split(os.altsep) prefix = n[0] for item in n:
prefix = m[0] for item in m:
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) def isdir(s): """Return true if the pathname refers to an existing directory.""" try: st = os.stat(s) except os.error: return 0 return S_ISDIR(st[ST_MODE]) def getsize(filename): """Return the size of a file, reported by os.stat().""" st = os.stat(filename) return st[ST_SIZE] def getmtime(filename): """Return the last modification time of a file, reported by os.stat().""" st = os.stat(filename) return st[ST_MTIME] def getatime(filename): """Return the last access time of a file, reported by os.stat().""" st = os.stat(filename) return st[ST_ATIME] def islink(s): """Return true if the pathname refers to a symbolic link. Always false on the Mac, until we understand Aliases.)""" return 0 def isfile(s): """Return true if the pathname refers to an existing regular file.""" try: st = os.stat(s) except os.error: return 0 return S_ISREG(st[ST_MODE]) def exists(s): """Return true if the pathname refers to an existing file or directory.""" try: st = os.stat(s) except os.error: return 0 return 1
return 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)
filename = compiler.library_filename(libname, lib_type='shared') result = find_file(filename, std_dirs, paths) if result is not None: return result filename = compiler.library_filename(libname, lib_type='static') result = find_file(filename, std_dirs, paths) return result
result = compiler.find_library_file(std_dirs + paths, libname) if result is None: return None dirname = os.path.dirname(result) for p in std_dirs: if p.endswith(os.sep): p = p.strip(os.sep) if p == dirname: return [ ] for p in paths: if p.endswith(os.sep): p = p.strip(os.sep) if p == dirname: return [p] else: assert False, "Internal error: Path not found in std_dirs or paths"
def find_library_file(compiler, libname, std_dirs, paths): filename = compiler.library_filename(libname, lib_type='shared') result = find_file(filename, std_dirs, paths) if result is not None: return result filename = compiler.library_filename(libname, lib_type='static') result = find_file(filename, std_dirs, paths) return result
if self.basetype: Output("
Output("
def generate(self): # XXX This should use long strings and %(varname)s substitution!
else: Output(" self.prefix, self.typename)
def generate(self): # XXX This should use long strings and %(varname)s substitution!
try: line = raw_input(self.prompt) except EOFError: line = 'EOF'
if self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: sys.stdout.write(self.prompt) line = sys.stdin.readline() if not len(line): line = 'EOF' else: line = line[:-1]
def cmdloop(self, intro=None): self.preloop() if intro is not None: self.intro = intro if self.intro: print self.intro stop = None while not stop: if self.cmdqueue: line = self.cmdqueue[0] del self.cmdqueue[0] else: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop()
'HTTPS'))
'HTTPS', 'HTTP11'))
def test_others(self): cm = self.checkModule
fp = open(findfile('audiotest.au'), 'rb')
datadir = os.path.join(os.path.dirname(landmark), 'data', '') fp = open(findfile('audiotest.au', datadir), 'rb')
def setUp(self): # In Python, audiotest.au lives in Lib/test not Lib/test/data fp = open(findfile('audiotest.au'), 'rb') try: self._audiodata = fp.read() finally: fp.close() self._au = MIMEAudio(self._audiodata)
if not mimetypes.inited: mimetypes.init()
def guess_type(self, path): """Guess the type of a file.
verify(unicode(u).__class__ is unicode)
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__(u"".join(L)) return self._rev
s = "\\pdfoutline goto name{page.%d}" % pageno
s = "\\pdfoutline goto name{page.%dx}" % pageno
def write_toc_entry(entry, fp, layer): stype, snum, title, pageno, toc = entry s = "\\pdfoutline goto name{page.%d}" % pageno if toc: s = "%s count -%d" % (s, len(toc)) if snum: title = "%s %s" % (snum, title) s = "%s {%s}\n" % (s, title) fp.write(s) for entry in toc: write_toc_entry(entry, fp, layer + 1)
self.checkequal(('this', ' is ', 'the partition method'), 'this is the partition method', 'partition', ' is ')
self.checkequal(('this is the par', 'ti', 'tion method'), 'this is the partition method', 'partition', 'ti')
def test_partition(self):
self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50))
if self.parent is not None: self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50))
def __init__(self, parent, title = None):
override if you don't want the standard buttons
override if you do not want the standard buttons
def buttonbox(self): '''add standard button box.
self.parent.focus_set()
if self.parent is not None: self.parent.focus_set()
def cancel(self, event=None):
v = self.get(section, option) val = int(v) if val not in (0, 1):
states = {'1': 1, 'yes': 1, 'true': 1, 'on': 1, '0': 0, 'no': 0, 'false': 0, 'off': 0} v = self.get(section, option) if not states.has_key(v.lower()):
def getboolean(self, section, option): v = self.get(section, option) val = int(v) if val not in (0, 1): raise ValueError, 'Not a boolean: %s' % v return val
return val
return states[v.lower()]
def getboolean(self, section, option): v = self.get(section, option) val = int(v) if val not in (0, 1): raise ValueError, 'Not a boolean: %s' % v return val
includes = ['-I' + incldir, '-I' + binlib]
includes = ['-I' + incldir, '-I' + config_h_dir]
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 self.inc.match(fullname) == None:
if DEBUG: print 'checkpath', fullname matchvalue = self.inc.match(fullname) if matchvalue == None:
def checkdir(self, path, istop): files = os.listdir(path) rv = [] todo = [] for f in files: if self.exc.match(f): continue fullname = os.path.join(path, f) if self.inc.match(fullname) == None: if os.path.isdir(fullname): todo.append(fullname) else: rv.append(fullname) for d in todo: if len(rv) > 500: if istop: rv.append('... and more ...') return rv rv = rv + self.checkdir(d, 0) return rv
macostools.copy(fullname, os.path.join(destprefix, dest), 1)
try: macostools.copy(fullname, os.path.join(destprefix, dest), 1) except: print 'cwd', os.path.getcwd() print 'fsspec', macfs.FSSpec(fullname) sys.exit(1)
def rundir(self, path, destprefix, doit): files = os.listdir(path) todo = [] rv = 1 for f in files: if self.exc.match(f): continue fullname = os.path.join(path, f) if os.path.isdir(fullname): todo.append(fullname) else: dest = self.inc.match(fullname) if dest == None: print 'Not yet resolved:', fullname rv = 0 if dest: if doit: print 'COPY ', fullname print ' -> ', os.path.join(destprefix, dest) macostools.copy(fullname, os.path.join(destprefix, dest), 1) for d in todo: if not self.rundir(d, destprefix, doit): rv = 0 return rv
path = module.__path__
try: path = module.__path__ except AttributeError: raise ImportError, 'No source for module ' + module.__name__
def _find_module(fullname, path=None): """Version of imp.find_module() that handles hierarchical module names""" file = None for tgt in fullname.split('.'): if file is not None: file.close() # close intermediate files (file, filename, descr) = imp.find_module(tgt, path) if descr[2] == imp.PY_SOURCE: break # find but not load the source file module = imp.load_module(tgt, file, filename, descr) path = module.__path__ return file, filename, descr
name=string.strip(name) if len(name)==0: name = socket.gethostname() try: name = socket.gethostbyaddr(name)[0] except socket.error: pass self.putcmd("helo",name)
self.putcmd("helo", _get_fqdn_hostname(name))
def helo(self, name=''): """SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host. """ name=string.strip(name) if len(name)==0: name = socket.gethostname() try: name = socket.gethostbyaddr(name)[0] except socket.error: pass self.putcmd("helo",name) (code,msg)=self.getreply() self.helo_resp=msg return (code,msg)
name=string.strip(name) if len(name)==0: name = socket.gethostname() try: name = socket.gethostbyaddr(name)[0] except socket.error: pass self.putcmd("ehlo",name)
self.putcmd("ehlo", _get_fqdn_hostname(name))
def ehlo(self, name=''): """ SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ name=string.strip(name) if len(name)==0: name = socket.gethostname() try: name = socket.gethostbyaddr(name)[0] except socket.error: pass self.putcmd("ehlo",name) (code,msg)=self.getreply() # According to RFC1869 some (badly written) # MTA's will disconnect on an ehlo. Toss an exception if # that happens -ddm if code == -1 and len(msg) == 0: raise SMTPServerDisconnected("Server not connected") self.ehlo_resp=msg if code<>250: return (code,msg) self.does_esmtp=1 #parse the ehlo response -ddm resp=string.split(self.ehlo_resp,'\n') del resp[0] for each in resp: m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each) if m: feature=string.lower(m.group("feature")) params=string.strip(m.string[m.end("feature"):]) self.esmtp_features[feature]=params return (code,msg)
"Divide two Rats, returning quotient and remainder (reversed args)."""
def __rdivmod__(self, other): "Divide two Rats, returning quotient and remainder (reversed args).""" if isint(other): other = Rat(other) elif not isRat(other): return NotImplemented return divmod(other, self)
server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)]
self.addheaders = [('User-agent', self.version)]
def __init__(self, proxies=None, **x509): if proxies is None: proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies self.key_file = x509.get('key_file') self.cert_file = x509.get('cert_file') server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)] self.__tempfiles = [] self.__unlink = os.unlink # See cleanup() self.tempcache = None # Undocumented feature: if you assign {} to tempcache, # it is used to cache files retrieved with # self.retrieve(). This is not enabled by default # since it does not work for changing documents (and I # haven't got the logic to check expiration headers # yet). self.ftpcache = ftpcache # Undocumented feature: you can use a different # ftp cache by assigning to the .ftpcache member; # in case you want logically independent URL openers # XXX This is not threadsafe. Bah.
f2 = self.tar.extractfile("S-SPARSE-WITH-NULLS")
f2 = self.tar.extractfile("/S-SPARSE-WITH-NULLS")
def test_sparse(self): """Test sparse member extraction. """ if self.sep != "|": f1 = self.tar.extractfile("S-SPARSE") f2 = self.tar.extractfile("S-SPARSE-WITH-NULLS") self.assert_(f1.read() == f2.read(), "_FileObject failed on sparse file member")
filename = "0-REGTYPE-TEXT"
filename = "/0-REGTYPE-TEXT"
def test_readlines(self): """Test readlines() method of _FileObject. """ if self.sep != "|": filename = "0-REGTYPE-TEXT" self.tar.extract(filename, dirname()) lines1 = file(os.path.join(dirname(), filename), "r").readlines() lines2 = self.tar.extractfile(filename).readlines() self.assert_(lines1 == lines2, "_FileObject.readline() does not work correctly")
lines1 = file(os.path.join(dirname(), filename), "r").readlines()
lines1 = file(os.path.join(dirname(), filename), "rU").readlines()
def test_readlines(self): """Test readlines() method of _FileObject. """ if self.sep != "|": filename = "0-REGTYPE-TEXT" self.tar.extract(filename, dirname()) lines1 = file(os.path.join(dirname(), filename), "r").readlines() lines2 = self.tar.extractfile(filename).readlines() self.assert_(lines1 == lines2, "_FileObject.readline() does not work correctly")
filename = "0-REGTYPE"
filename = "/0-REGTYPE"
def test_seek(self): """Test seek() method of _FileObject, incl. random reading. """ if self.sep != "|": filename = "0-REGTYPE" self.tar.extract(filename, dirname()) data = file(os.path.join(dirname(), filename), "rb").read()
ldflags = self.ldflags_shared_debug
ld_args = self.ldflags_shared_debug[:]
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
ldflags = self.ldflags_shared
ld_args = self.ldflags_shared[:] objects = map(os.path.normpath, objects)
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
libraries.append ('mypylib')
objects.insert(0, startup_obj)
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
def_file = os.path.join (build_temp, '%s.def' % modname) f = open (def_file, 'w') f.write ('EXPORTS\n')
temp_dir = os.path.dirname(objects[0]) def_file = os.path.join (temp_dir, '%s.def' % modname) contents = ['EXPORTS']
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
f.write (' %s=_%s\n' % (sym, sym)) ld_args = ldflags + [startup_obj] + objects + \ [',%s,,' % output_filename] + \ libraries + [',' + def_file]
contents.append(' %s=_%s' % (sym, sym)) self.execute(write_file, (def_file, contents), "writing %s" % def_file) for l in library_dirs: ld_args.append("/L%s" % os.path.normpath(l)) ld_args.extend(objects) ld_args.extend([',',output_filename]) ld_args.extend([',', ',']) for lib in libraries: libfile = self.find_library_file(library_dirs, lib, debug) if libfile is None: ld_args.append(lib) else: ld_args.append(libfile) ld_args.extend([',',def_file])
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
"don't know how to set runtime library search path for MSVC++"
("don't know how to set runtime library search path " "for Borland C++")
def runtime_library_dir_option (self, dir): raise DistutilsPlatformError, \ "don't know how to set runtime library search path for MSVC++"
def find_library_file (self, dirs, lib):
def find_library_file (self, dirs, lib, debug=0):
def find_library_file (self, dirs, lib):
['extract-all', 'default-domain', 'escape', 'help',
['extract-all', 'default-domain=', 'escape', 'help',
def main(): global default_keywords try: opts, args = getopt.getopt( sys.argv[1:], 'ad:DEhk:Kno:p:S:Vvw:x:', ['extract-all', 'default-domain', 'escape', 'help', 'keyword=', 'no-default-keywords', 'add-location', 'no-location', 'output=', 'output-dir=', 'style=', 'verbose', 'version', 'width=', 'exclude-file=', 'docstrings', ]) except getopt.error, msg: usage(1, msg) # for holding option values class Options: # constants GNU = 1 SOLARIS = 2 # defaults extractall = 0 # FIXME: currently this option has no effect at all. escape = 0 keywords = [] outpath = '' outfile = 'messages.pot' writelocations = 1 locationstyle = GNU verbose = 0 width = 78 excludefilename = '' docstrings = 0 options = Options() locations = {'gnu' : options.GNU, 'solaris' : options.SOLARIS, } # parse options for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-a', '--extract-all'): options.extractall = 1 elif opt in ('-d', '--default-domain'): options.outfile = arg + '.pot' elif opt in ('-E', '--escape'): options.escape = 1 elif opt in ('-D', '--docstrings'): options.docstrings = 1 elif opt in ('-k', '--keyword'): options.keywords.append(arg) elif opt in ('-K', '--no-default-keywords'): default_keywords = [] elif opt in ('-n', '--add-location'): options.writelocations = 1 elif opt in ('--no-location',): options.writelocations = 0 elif opt in ('-S', '--style'): options.locationstyle = locations.get(arg.lower()) if options.locationstyle is None: usage(1, _('Invalid value for --style: %s') % arg) elif opt in ('-o', '--output'): options.outfile = arg elif opt in ('-p', '--output-dir'): options.outpath = arg elif opt in ('-v', '--verbose'): options.verbose = 1 elif opt in ('-V', '--version'): print _('pygettext.py (xgettext for Python) %s') % __version__ sys.exit(0) elif opt in ('-w', '--width'): try: options.width = int(arg) except ValueError: usage(1, _('--width argument must be an integer: %s') % arg) elif opt in ('-x', '--exclude-file'): options.excludefilename = arg # calculate escapes make_escapes(options.escape) # calculate all keywords options.keywords.extend(default_keywords) # initialize list of strings to exclude if options.excludefilename: try: fp = open(options.excludefilename) options.toexclude = fp.readlines() fp.close() except IOError: print >> sys.stderr, _( "Can't read --exclude-file: %s") % options.excludefilename sys.exit(1) else: options.toexclude = [] # slurp through all the files eater = TokenEater(options) for filename in args: if filename == '-': if options.verbose: print _('Reading standard input') fp = sys.stdin closep = 0 else: if options.verbose: print _('Working on %s') % filename fp = open(filename) closep = 1 try: eater.set_filename(filename) try: tokenize.tokenize(fp.readline, eater) except tokenize.TokenError, e: print >> sys.stderr, '%s: %s, line %d, column %d' % ( e[0], filename, e[1][0], e[1][1]) finally: if closep: fp.close() # write the output if options.outfile == '-': fp = sys.stdout closep = 0 else: if options.outpath: options.outfile = os.path.join(options.outpath, options.outfile) fp = open(options.outfile, 'w') closep = 1 try: eater.write(fp) finally: if closep: fp.close()
f = open(filename, 'r')
f = open(filename, 'rb')
def whathdr(filename): """Recognize sound headers""" f = open(filename, 'r') h = f.read(512) for tf in tests: res = tf(h, f) if res: return res return None
self.prefix = ""
def __init__(self, name=""): """Construct a TarInfo object. name is the optional name of the member. """
tarinfo.prefix = buf[345:500]
prefix = buf[345:500].rstrip(NUL) if prefix and not tarinfo.issparse(): tarinfo.name = prefix + "/" + tarinfo.name
def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: raise ValueError("truncated header") if buf.count(NUL) == BLOCKSIZE: raise ValueError("empty header")
buf = "" type = self.type prefix = "" if self.name.endswith("/"): type = DIRTYPE name = normpath(self.name) if type == DIRTYPE: name += "/" linkname = self.linkname if linkname: linkname = normpath(linkname) if posix: if self.size > MAXSIZE_MEMBER: raise ValueError("file is too large (>= 8 GB)") if len(self.linkname) > LENGTH_LINK: raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK)) if len(name) > LENGTH_NAME: prefix = name[:LENGTH_PREFIX + 1] while prefix and prefix[-1] != "/": prefix = prefix[:-1] name = name[len(prefix):] prefix = prefix[:-1] if not prefix or len(name) > LENGTH_NAME: raise ValueError("name is too long") else: if len(self.linkname) > LENGTH_LINK: buf += self._create_gnulong(self.linkname, GNUTYPE_LONGLINK) if len(name) > LENGTH_NAME: buf += self._create_gnulong(name, GNUTYPE_LONGNAME)
def tobuf(self, posix=False): """Return a tar header block as a 512 byte string. """ parts = [ stn(self.name, 100), itn(self.mode & 07777, 8, posix), itn(self.uid, 8, posix), itn(self.gid, 8, posix), itn(self.size, 12, posix), itn(self.mtime, 12, posix), " ", # checksum field self.type, stn(self.linkname, 100), stn(MAGIC, 6), stn(VERSION, 2), stn(self.uname, 32), stn(self.gname, 32), itn(self.devmajor, 8, posix), itn(self.devminor, 8, posix), stn(self.prefix, 155) ]
stn(self.name, 100),
stn(name, 100),
def tobuf(self, posix=False): """Return a tar header block as a 512 byte string. """ parts = [ stn(self.name, 100), itn(self.mode & 07777, 8, posix), itn(self.uid, 8, posix), itn(self.gid, 8, posix), itn(self.size, 12, posix), itn(self.mtime, 12, posix), " ", # checksum field self.type, stn(self.linkname, 100), stn(MAGIC, 6), stn(VERSION, 2), stn(self.uname, 32), stn(self.gname, 32), itn(self.devmajor, 8, posix), itn(self.devminor, 8, posix), stn(self.prefix, 155) ]
self.type,
type,
def tobuf(self, posix=False): """Return a tar header block as a 512 byte string. """ parts = [ stn(self.name, 100), itn(self.mode & 07777, 8, posix), itn(self.uid, 8, posix), itn(self.gid, 8, posix), itn(self.size, 12, posix), itn(self.mtime, 12, posix), " ", # checksum field self.type, stn(self.linkname, 100), stn(MAGIC, 6), stn(VERSION, 2), stn(self.uname, 32), stn(self.gname, 32), itn(self.devmajor, 8, posix), itn(self.devminor, 8, posix), stn(self.prefix, 155) ]
stn(self.prefix, 155)
stn(prefix, 155)
def tobuf(self, posix=False): """Return a tar header block as a 512 byte string. """ parts = [ stn(self.name, 100), itn(self.mode & 07777, 8, posix), itn(self.uid, 8, posix), itn(self.gid, 8, posix), itn(self.size, 12, posix), itn(self.mtime, 12, posix), " ", # checksum field self.type, stn(self.linkname, 100), stn(MAGIC, 6), stn(VERSION, 2), stn(self.uname, 32), stn(self.gname, 32), itn(self.devmajor, 8, posix), itn(self.devminor, 8, posix), stn(self.prefix, 155) ]
buf = struct.pack("%ds" % BLOCKSIZE, "".join(parts))
buf += struct.pack("%ds" % BLOCKSIZE, "".join(parts))
def tobuf(self, posix=False): """Return a tar header block as a 512 byte string. """ parts = [ stn(self.name, 100), itn(self.mode & 07777, 8, posix), itn(self.uid, 8, posix), itn(self.gid, 8, posix), itn(self.size, 12, posix), itn(self.mtime, 12, posix), " ", # checksum field self.type, stn(self.linkname, 100), stn(MAGIC, 6), stn(VERSION, 2), stn(self.uname, 32), stn(self.gname, 32), itn(self.devmajor, 8, posix), itn(self.devminor, 8, posix), stn(self.prefix, 155) ]
buf = buf[:148] + "%06o\0" % chksum + buf[155:]
buf = buf[:-364] + "%06o\0" % chksum + buf[-357:]
def tobuf(self, posix=False): """Return a tar header block as a 512 byte string. """ parts = [ stn(self.name, 100), itn(self.mode & 07777, 8, posix), itn(self.uid, 8, posix), itn(self.gid, 8, posix), itn(self.size, 12, posix), itn(self.mtime, 12, posix), " ", # checksum field self.type, stn(self.linkname, 100), stn(MAGIC, 6), stn(VERSION, 2), stn(self.uname, 32), stn(self.gname, 32), itn(self.devmajor, 8, posix), itn(self.devminor, 8, posix), stn(self.prefix, 155) ]
tarinfo.name = normpath(tarinfo.name) if tarinfo.isdir(): tarinfo.name += "/" if tarinfo.linkname: tarinfo.linkname = normpath(tarinfo.linkname) if tarinfo.size > MAXSIZE_MEMBER: if self.posix: raise ValueError("file is too large (>= 8 GB)") else: self._dbg(2, "tarfile: Created GNU tar largefile header") if len(tarinfo.linkname) > LENGTH_LINK: if self.posix: raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK)) else: self._create_gnulong(tarinfo.linkname, GNUTYPE_LONGLINK) tarinfo.linkname = tarinfo.linkname[:LENGTH_LINK -1] self._dbg(2, "tarfile: Created GNU tar extension LONGLINK") if len(tarinfo.name) > LENGTH_NAME: if self.posix: prefix = tarinfo.name[:LENGTH_PREFIX + 1] while prefix and prefix[-1] != "/": prefix = prefix[:-1] name = tarinfo.name[len(prefix):] prefix = prefix[:-1] if not prefix or len(name) > LENGTH_NAME: raise ValueError("name is too long (>%d)" % (LENGTH_NAME)) tarinfo.name = name tarinfo.prefix = prefix else: self._create_gnulong(tarinfo.name, GNUTYPE_LONGNAME) tarinfo.name = tarinfo.name[:LENGTH_NAME - 1] self._dbg(2, "tarfile: Created GNU tar extension LONGNAME") self.fileobj.write(tarinfo.tobuf(self.posix)) self.offset += BLOCKSIZE
tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.posix) self.fileobj.write(buf) self.offset += len(buf)
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw")
tarinfo.name = normpath(os.path.join(tarinfo.prefix.rstrip(NUL), tarinfo.name))
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
tarinfo.prefix = ""
def proc_sparse(self, tarinfo): """Process a GNU sparse header plus extra headers. """ buf = tarinfo.buf sp = _ringbuffer() pos = 386 lastpos = 0L realpos = 0L # There are 4 possible sparse structs in the # first header. for i in xrange(4): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break if offset > lastpos: sp.append(_hole(lastpos, offset - lastpos)) sp.append(_data(offset, numbytes, realpos)) realpos += numbytes lastpos = offset + numbytes pos += 24
def _create_gnulong(self, name, type): """Write a GNU longname/longlink member to the TarFile. It consists of an extended tar header, with the length of the longname as size, followed by data blocks, which contain the longname as a null terminated string. """ name += NUL tarinfo = TarInfo() tarinfo.name = "././@LongLink" tarinfo.type = type tarinfo.mode = 0 tarinfo.size = len(name) self.fileobj.write(tarinfo.tobuf()) self.offset += BLOCKSIZE self.fileobj.write(name) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE
def __iter__(self): """Provide an iterator object. """ if self._loaded: return iter(self.members) else: return TarIter(self)