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 ...
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 serv...
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_...
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_help...
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...
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_help...
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 se...
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 se...
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 =...
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([ ReadTestG...
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 ...
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.la...
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...
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")...
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 ca...
'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: ' + se...
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 ...
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 ...
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 ...
_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,...
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 ...
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 getm...
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 ...
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: as...
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) r...
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.on...
'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.p...
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.appen...
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:...
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 ...
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...
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() # A...
"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 = [('U...
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...
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...
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.fin...
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=', 'docstri...
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.lin...
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(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), ...
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(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), ...
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), ...
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), ...
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(ta...
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...
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]) exc...
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 = "././@LongLi...
def __iter__(self): """Provide an iterator object. """ if self._loaded: return iter(self.members) else: return TarIter(self)