rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
and where to install packages""" | and where to install packages.""" | def http_error_default(self, url, fp, errcode, errmsg, headers): urllib.URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) |
"responsible" for the contents""" | "responsible" for the contents.""" | def compareFlavors(self, left, right): """Compare two flavor strings. This is part of your preferences because whether the user prefers installing from source or binary is.""" if left in self.flavorOrder: if right in self.flavorOrder: return cmp(self.flavorOrder.index(left), self.flavorOrder.index(right)) return -1 if right in self.flavorOrder: return 1 return cmp(left, right) |
lastmod = apply(imp.load_module, info) | lastmod = _imp.load_module(*info) | def _rec_find_module(module): "Improvement over imp.find_module which finds submodules." path="" for mod in string.split(module,"."): if path == "": info = (mod,) + _imp.find_module(mod) else: info = (mod,) + _imp.find_module(mod, [path]) lastmod = apply(imp.load_module, info) try: path = lastmod.__path__[0] except AttributeError, e: pass return info |
drv_module = apply(imp.load_module, info) | drv_module = _imp.load_module(*info) | def _create_parser(parser_name): info = _rec_find_module(parser_name) drv_module = apply(imp.load_module, info) return drv_module.create_parser() |
pth_file.cleanup() | pth_file.cleanup(prep=True) | def test_addpackage(self): # Make sure addpackage() imports if the line starts with 'import', # adds directories to sys.path for any line in the file that is not a # comment or import that is a valid directory name for where the .pth # file resides; invalid directories are not added pth_file = PthFile() pth_file.cleanup() # to make sure that nothing is pre-existing that # shouldn't be try: pth_file.create() site.addpackage(pth_file.base_dir, pth_file.filename, set()) unittest.FunctionTestCase(pth_file.test) finally: pth_file.cleanup() |
unittest.FunctionTestCase(pth_file.test) | self.pth_file_tests(pth_file) | def test_addpackage(self): # Make sure addpackage() imports if the line starts with 'import', # adds directories to sys.path for any line in the file that is not a # comment or import that is a valid directory name for where the .pth # file resides; invalid directories are not added pth_file = PthFile() pth_file.cleanup() # to make sure that nothing is pre-existing that # shouldn't be try: pth_file.create() site.addpackage(pth_file.base_dir, pth_file.filename, set()) unittest.FunctionTestCase(pth_file.test) finally: pth_file.cleanup() |
pth_file.cleanup() | pth_file.cleanup(prep=True) | def test_addsitedir(self): # Same tests for test_addpackage since addsitedir() essentially just # calls addpackage() for every .pth file in the directory pth_file = PthFile() pth_file.cleanup() # Make sure that nothing is pre-existing that is # tested for try: site.addsitedir(pth_file.base_dir, set()) unittest.FunctionTestCase(pth_file.test) finally: pth_file.cleanup() |
unittest.FunctionTestCase(pth_file.test) | self.pth_file_tests(pth_file) | def test_addsitedir(self): # Same tests for test_addpackage since addsitedir() essentially just # calls addpackage() for every .pth file in the directory pth_file = PthFile() pth_file.cleanup() # Make sure that nothing is pre-existing that is # tested for try: site.addsitedir(pth_file.base_dir, set()) unittest.FunctionTestCase(pth_file.test) finally: pth_file.cleanup() |
self.imported = "time" | self.imported = imported | def __init__(self, filename_base=TESTFN, imported="time", good_dirname="__testdir__", bad_dirname="__bad"): """Initialize instance variables""" self.filename = filename_base + ".pth" self.base_dir = os.path.abspath('') self.file_path = os.path.join(self.base_dir, self.filename) self.imported = "time" self.good_dirname = good_dirname self.bad_dirname = bad_dirname self.good_dir_path = os.path.join(self.base_dir, self.good_dirname) self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname) |
def cleanup(self): | def cleanup(self, prep=False): | def cleanup(self): """Make sure that the .pth file is deleted, self.imported is not in sys.modules, and that both self.good_dirname and self.bad_dirname are not existing directories.""" try: os.remove(self.file_path) except OSError: pass try: del sys.modules[self.imported] except KeyError: pass try: os.rmdir(self.good_dir_path) except OSError: pass try: os.rmdir(self.bad_dir_path) except OSError: pass |
try: | if os.path.exists(self.file_path): | def cleanup(self): """Make sure that the .pth file is deleted, self.imported is not in sys.modules, and that both self.good_dirname and self.bad_dirname are not existing directories.""" try: os.remove(self.file_path) except OSError: pass try: del sys.modules[self.imported] except KeyError: pass try: os.rmdir(self.good_dir_path) except OSError: pass try: os.rmdir(self.bad_dir_path) except OSError: pass |
except OSError: pass try: del sys.modules[self.imported] except KeyError: pass try: | if prep: self.imported_module = sys.modules.get(self.imported) if self.imported_module: del sys.modules[self.imported] else: if self.imported_module: sys.modules[self.imported] = self.imported_module if os.path.exists(self.good_dir_path): | def cleanup(self): """Make sure that the .pth file is deleted, self.imported is not in sys.modules, and that both self.good_dirname and self.bad_dirname are not existing directories.""" try: os.remove(self.file_path) except OSError: pass try: del sys.modules[self.imported] except KeyError: pass try: os.rmdir(self.good_dir_path) except OSError: pass try: os.rmdir(self.bad_dir_path) except OSError: pass |
except OSError: pass try: | if os.path.exists(self.bad_dir_path): | def cleanup(self): """Make sure that the .pth file is deleted, self.imported is not in sys.modules, and that both self.good_dirname and self.bad_dirname are not existing directories.""" try: os.remove(self.file_path) except OSError: pass try: del sys.modules[self.imported] except KeyError: pass try: os.rmdir(self.good_dir_path) except OSError: pass try: os.rmdir(self.bad_dir_path) except OSError: pass |
except OSError: pass def test(self): """Test to make sure that was and was not supposed to be created by using the .pth file occurred""" assert site.makepath(self.good_dir_path)[0] in sys.path assert self.imported in sys.modules assert not os.path.exists(self.bad_dir_path) | def cleanup(self): """Make sure that the .pth file is deleted, self.imported is not in sys.modules, and that both self.good_dirname and self.bad_dirname are not existing directories.""" try: os.remove(self.file_path) except OSError: pass try: del sys.modules[self.imported] except KeyError: pass try: os.rmdir(self.good_dir_path) except OSError: pass try: os.rmdir(self.bad_dir_path) except OSError: pass |
|
if verbose: print 'Connecting to %s...' % host | if verbose: print 'Connecting to %s...' % `host` | def main(): global verbose, interactive, mac, rmok, nologin try: opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v') except getopt.error, msg: usage(msg) login = '' passwd = '' account = '' for o, a in opts: if o == '-l': login = a if o == '-p': passwd = a if o == '-a': account = a if o == '-v': verbose = verbose + 1 if o == '-q': verbose = 0 if o == '-i': interactive = 1 if o == '-m': mac = 1; nologin = 1; skippats.append('*.o') if o == '-n': nologin = 1 if o == '-r': rmok = 1 if o == '-s': skippats.append(a) if not args: usage('hostname missing') host = args[0] remotedir = '' localdir = '' if args[1:]: remotedir = args[1] if args[2:]: localdir = args[2] if args[3:]: usage('too many arguments') # f = ftplib.FTP() if verbose: print 'Connecting to %s...' % host f.connect(host) if not nologin: if verbose: print 'Logging in as %s...' % (login or 'anonymous') f.login(login, passwd, account) if verbose: print 'OK.' pwd = f.pwd() if verbose > 1: print 'PWD =', `pwd` if remotedir: if verbose > 1: print 'cwd(%s)' % `remotedir` f.cwd(remotedir) if verbose > 1: print 'OK.' pwd = f.pwd() if verbose > 1: print 'PWD =', `pwd` # mirrorsubdir(f, localdir) |
print 'Logging in as %s...' % (login or 'anonymous') | print 'Logging in as %s...' % `login or 'anonymous'` | def main(): global verbose, interactive, mac, rmok, nologin try: opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v') except getopt.error, msg: usage(msg) login = '' passwd = '' account = '' for o, a in opts: if o == '-l': login = a if o == '-p': passwd = a if o == '-a': account = a if o == '-v': verbose = verbose + 1 if o == '-q': verbose = 0 if o == '-i': interactive = 1 if o == '-m': mac = 1; nologin = 1; skippats.append('*.o') if o == '-n': nologin = 1 if o == '-r': rmok = 1 if o == '-s': skippats.append(a) if not args: usage('hostname missing') host = args[0] remotedir = '' localdir = '' if args[1:]: remotedir = args[1] if args[2:]: localdir = args[2] if args[3:]: usage('too many arguments') # f = ftplib.FTP() if verbose: print 'Connecting to %s...' % host f.connect(host) if not nologin: if verbose: print 'Logging in as %s...' % (login or 'anonymous') f.login(login, passwd, account) if verbose: print 'OK.' pwd = f.pwd() if verbose > 1: print 'PWD =', `pwd` if remotedir: if verbose > 1: print 'cwd(%s)' % `remotedir` f.cwd(remotedir) if verbose > 1: print 'OK.' pwd = f.pwd() if verbose > 1: print 'PWD =', `pwd` # mirrorsubdir(f, localdir) |
if verbose: print 'Creating local directory', localdir | if verbose: print 'Creating local directory', `localdir` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print "Failed to establish local directory", localdir | print "Failed to establish local directory", `localdir` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Bad mirror info in %s' % infofilename | print 'Bad mirror info in %s' % `infofilename` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
if verbose: print 'Listing remote directory %s...' % pwd | if verbose: print 'Listing remote directory %s...' % `pwd` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
filename = words[-1] if string.find(filename, " -> ") >= 0: | filename = string.lstrip(words[-1]) i = string.find(filename, " -> ") if i >= 0: | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Skipping symbolic link %s' % \ filename continue | print 'Found symbolic link %s' % `filename` linkto = filename[i+4:] filename = filename[:i] | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Skip pattern', pat, print 'matches', filename | print 'Skip pattern', `pat`, print 'matches', `filename` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Remembering subdirectory', filename | print 'Remembering subdirectory', `filename` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Already have this version of', filename | print 'Already have this version of',`filename` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
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) | if mode[0] == 'l': if verbose: print "Creating symlink %s -> %s" % ( `filename`, `linkto`) try: os.symlink(linkto, tempname) except IOError, msg: print "Can't create %s: %s" % ( `tempname`, str(msg)) continue | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
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: 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() | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print "Can't rename %s to %s: %s" % (tempname, fullname, | print "Can't rename %s to %s: %s" % (`tempname`, `fullname`, | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
if verbose: | if verbose and mode[0] != 'l': | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print filename, "in", localdir or "." | print `filename`, "in", `localdir or "."` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Skip pattern', pat, print 'matches', name | print 'Skip pattern', `pat`, print 'matches', `name` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Local file', fullname, | print 'Local file', `fullname`, | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
if verbose: print 'Removing local file/dir', fullname | if verbose: print 'Removing local file/dir', `fullname` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
if verbose: print 'Processing subdirectory', subdir | if verbose: print 'Processing subdirectory', `subdir` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print 'Remote directory now:', pwd print 'Remote cwd', subdir | print 'Remote directory now:', `pwd` print 'Remote cwd', `subdir` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
print "Can't chdir to", subdir, ":", msg | print "Can't chdir to", `subdir`, ":", `msg` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
if verbose: print 'Mirroring as', localsubdir | if verbose: print 'Mirroring as', `localsubdir` | 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, None, 8) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue filename = words[-1] if string.find(filename, " -> ") >= 0: if verbose > 1: print 'Skipping symbolic link %s' % \ filename continue 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.' |
(fullname, str(msg)) | (`fullname`, str(msg)) | def remove(fullname): if os.path.isdir(fullname) and not os.path.islink(fullname): try: names = os.listdir(fullname) except os.error: names = [] ok = 1 for name in names: if not remove(os.path.join(fullname, name)): ok = 0 if not ok: return 0 try: os.rmdir(fullname) except os.error, msg: print "Can't remove local directory %s: %s" % \ (fullname, str(msg)) return 0 else: try: os.unlink(fullname) except os.error, msg: print "Can't remove local file %s: %s" % \ (fullname, str(msg)) return 0 return 1 |
for key in ('LDFLAGS', 'BASECFLAGS'): | for key in ('LDFLAGS', 'BASECFLAGS', 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): | def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. Generally this includes everything needed to build extensions and install both pure modules and extensions. On Unix, this means every variable defined in Python's installed Makefile; on Windows and Mac OS it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ global _config_vars if _config_vars is None: func = globals().get("_init_" + os.name) if func: func() else: _config_vars = {} # Normalized versions of prefix and exec_prefix are handy to have; # in fact, these are the standard versions used most places in the # Distutils. _config_vars['prefix'] = PREFIX _config_vars['exec_prefix'] = EXEC_PREFIX if sys.platform == 'darwin': kernel_version = os.uname()[2] # Kernel version (8.4.3) major_version = int(kernel_version.split('.')[0]) if major_version < 8: # On Mac OS X before 10.4, check if -arch and -isysroot # are in CFLAGS or LDFLAGS and remove them if they are. # This is needed when building extensions on a 10.3 system # using a universal build of python. for key in ('LDFLAGS', 'BASECFLAGS'): flags = _config_vars[key] flags = re.sub('-arch\s+\w+\s', ' ', flags) flags = re.sub('-isysroot [^ \t]*', ' ', flags) _config_vars[key] = flags if args: vals = [] for name in args: vals.append(_config_vars.get(name)) return vals else: return _config_vars |
explicitely. DEFAULT can be the relative path to a .ico file | explicitly. DEFAULT can be the relative path to a .ico file | def wm_iconbitmap(self, bitmap=None, default=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. |
a method of the same name to preform each SMTP comand, and there is a method called 'sendmail' that will do an entiere mail | a method of the same name to perform each SMTP command, and there is a method called 'sendmail' that will do an entire mail | def quotedata(data): """Quote data for email. Double leading '.', and change Unix newline '\n', or Mac '\r' into Internet CRLF end-of-line.""" return re.sub(r'(?m)^\.', '..', re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) |
def vrfy(self, address): return self.verify(address) | def vrfy(self, address): return self.verify(address) |
|
""" This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to (a string will be treated as a list with 1 address) - msg : the message to send. - mail_options : list of ESMTP options (such as 8bitmime) for the mail command - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. This method will return normally if the mail is accepted for at least one recipient. Otherwise it will throw an exception (either SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError) That is, if this method does not throw an exception, then someone should get your mail. If this method does not throw an exception, it returns a dictionary, with one entry for each recipient that was refused. | """This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - msg : The message to send. - mail_options : List of ESMTP options (such as 8bitmime) for the mail command. - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. This method will return normally if the mail is accepted for at least one recipient. Otherwise it will throw an exception (either SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError) That is, if this method does not throw an exception, then someone should get your mail. If this method does not throw an exception, it returns a dictionary, with one entry for each recipient that was refused. | def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to (a string will be treated as a list with 1 address) - msg : the message to send. - mail_options : list of ESMTP options (such as 8bitmime) for the mail command - rcpt_options : List of ESMTP options (such as DSN commands) for all the rcpt commands If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed. |
self.get_installer_filename())) | self.get_installer_filename(fullname))) | def run (self): if (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform") |
assert u"%c" % (u"abc",) == u'a' assert u"%c" % ("abc",) == u'a' | assert u"%c" % (u"a",) == u'a' assert u"%c" % ("a",) == u'a' | test('capwords', u'abc\t def \nghi', u'Abc Def Ghi') |
(objects, output_dir) = \ self._fix_link_args (objects, output_dir, takes_libs=0) | (objects, output_dir) = self._fix_object_args (objects, output_dir) | def create_static_lib (self, objects, output_libname, output_dir=None, debug=0, extra_preargs=None, extra_postargs=None): |
(objects, output_dir, libraries, library_dirs) = \ self._fix_link_args (objects, output_dir, takes_libs=1, libraries=libraries, library_dirs=library_dirs) | (objects, output_dir) = self._fix_object_args (objects, output_dir) (libraries, library_dirs, runtime_library_dirs) = \ self._fix_lib_args (libraries, library_dirs, runtime_library_dirs) if self.runtime_library_dirs: self.warn ("I don't know what to do with 'runtime_library_dirs': " + str (runtime_library_dirs)) | def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None): |
self.num_regs=len(regs)/2 | self.num_regs=len(regs) | def match(self, string, pos=0): |
h = self.outer.copy() h.update(self.inner.digest()) | h = self._current() | def digest(self): """Return the hash value of this hashing object. |
return "".join([hex(ord(x))[2:].zfill(2) for x in tuple(self.digest())]) | h = self._current() return h.hexdigest() | def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ return "".join([hex(ord(x))[2:].zfill(2) for x in tuple(self.digest())]) |
index.append(keys[j], offset + len(buf)) | index.append( (keys[j], offset + len(buf)) ) | def addname(self, name): # Domain name packing (section 4.1.4) # Add a domain name to the buffer, possibly using pointers. # The case of the first occurrence of a name is preserved. # Redundant dots are ignored. list = [] for label in string.splitfields(name, '.'): if label: if len(label) > 63: raise PackError, 'label too long' list.append(label) keys = [] for i in range(len(list)): key = string.upper(string.joinfields(list[i:], '.')) keys.append(key) if self.index.has_key(key): pointer = self.index[key] break else: i = len(list) pointer = None # Do it into temporaries first so exceptions don't # mess up self.index and self.buf buf = '' offset = len(self.buf) index = [] for j in range(i): label = list[j] n = len(label) if offset + len(buf) < 0x3FFF: index.append(keys[j], offset + len(buf)) else: print 'dnslib.Packer.addname:', print 'warning: pointer too big' buf = buf + (chr(n) + label) if pointer: buf = buf + pack16bit(pointer | 0xC000) else: buf = buf + '\0' self.buf = self.buf + buf for key, value in index: self.index[key] = value |
def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') header = input.read(AS_HEADER_LENGTH) try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: | class AppleSingle(object): datafork = None resourcefork = None def __init__(self, fileobj, verbose=False): header = fileobj.read(AS_HEADER_LENGTH) | def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: try: id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s"%arg if verbose: print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' else: data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) fp.close() elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found' |
id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) | magic, version, ig, nentry = struct.unpack(AS_HEADER_FORMAT, header) | def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: try: id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s"%arg if verbose: print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' else: data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) fp.close() elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found' |
raise Error, "Unpack entry error: %s"%arg | raise Error, "Unpack header error: %s" % (arg,) | def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: try: id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s"%arg if verbose: print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' else: data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) fp.close() elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found' |
print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' | print 'Magic: 0x%8.8x' % (magic,) print 'Version: 0x%8.8x' % (version,) print 'Entries: %d' % (nentry,) if magic != AS_MAGIC: raise Error, "Unknown AppleSingle magic number 0x%8.8x" % (magic,) if version != AS_VERSION: raise Error, "Unknown AppleSingle version number 0x%8.8x" % (version,) if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [fileobj.read(AS_ENTRY_LENGTH) for i in xrange(nentry)] self.forks = [] for hdr in headers: try: restype, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s" % (arg,) if verbose: print "Fork %d, offset %d, length %d" % (restype, offset, length) fileobj.seek(offset) data = fileobj.read(length) if len(data) != length: raise Error, "Short read: expected %d bytes got %d" % (length, len(data)) self.forks.append((restype, data)) if restype == AS_DATAFORK: self.datafork = data elif restype == AS_RESOURCEFORK: self.resourcefork = data def tofile(self, path, resonly=False): outfile = open(path, 'wb') data = False if resonly: if self.resourcefork is None: raise Error, "No resource fork found" fp = open(path, 'wb') fp.write(self.resourcefork) fp.close() elif (self.resourcefork is None and self.datafork is None): raise Error, "No useful forks found" | def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: try: id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s"%arg if verbose: print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' else: data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) fp.close() elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found' |
data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) | if self.datafork is not None: fp = open(path, 'wb') fp.write(self.datafork) | def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: try: id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s"%arg if verbose: print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' else: data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) fp.close() elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found' |
elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found' | if self.resourcefork is not None: fp = MacOS.openrf(path, '*wb') fp.write(self.resourcefork) fp.close() def decode(infile, outpath, resonly=False, verbose=False): """decode(infile, outpath [, resonly=False, verbose=False]) | def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: try: id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s"%arg if verbose: print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' else: data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) fp.close() elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found' |
resonly = 1 | resonly = True | def _test(): if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4: print 'Usage: applesingle.py [-r] applesinglefile decodedfile' sys.exit(1) if sys.argv[1] == '-r': resonly = 1 del sys.argv[1] else: resonly = 0 decode(sys.argv[1], sys.argv[2], resonly=resonly) |
resonly = 0 | resonly = False | def _test(): if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4: print 'Usage: applesingle.py [-r] applesinglefile decodedfile' sys.exit(1) if sys.argv[1] == '-r': resonly = 1 del sys.argv[1] else: resonly = 0 decode(sys.argv[1], sys.argv[2], resonly=resonly) |
addinfourl.__init__(self, fp, hdrs, url) | self.__super_init(fp, hdrs, url) | def __init__(self, url, code, msg, hdrs, fp): addinfourl.__init__(self, fp, hdrs, url) self.code = code self.msg = msg self.hdrs = hdrs self.fp = fp # XXX self.filename = url |
self.fp.close() | if self.fp: self.fp.close() | def __del__(self): # XXX is this safe? what if user catches exception, then # extracts fp and discards exception? self.fp.close() |
result = apply(func, args) | result = func(*args) | def _call_chain(self, chain, kind, meth_name, *args): # XXX raise an exception if no one else should try to handle # this url. return None if you can't but someone else could. handlers = chain.get(kind, ()) for handler in handlers: func = getattr(handler, meth_name) result = apply(func, args) if result is not None: return result |
result = apply(self._call_chain, args) | result = self._call_chain(*args) | def error(self, proto, *args): if proto == 'http': # XXX http protocol is special cased dict = self.handle_error[proto] proto = args[2] # YUCK! meth_name = 'http_error_%d' % proto http_err = 1 orig_args = args else: dict = self.handle_error meth_name = proto + '_error' http_err = 0 args = (dict, proto, meth_name) + args result = apply(self._call_chain, args) if result: return result |
return apply(self._call_chain, args) | return self._call_chain(*args) | def error(self, proto, *args): if proto == 'http': # XXX http protocol is special cased dict = self.handle_error[proto] proto = args[2] # YUCK! meth_name = 'http_error_%d' % proto http_err = 1 orig_args = args else: dict = self.handle_error meth_name = proto + '_error' http_err = 0 args = (dict, proto, meth_name) + args result = apply(self._call_chain, args) if result: return result |
h = httplib.HTTP(host) if req.has_data(): data = req.get_data() h.putrequest('POST', req.get_selector()) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', req.get_selector()) | try: h = httplib.HTTP(host) if req.has_data(): data = req.get_data() h.putrequest('POST', req.get_selector()) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', req.get_selector()) except socket.error, err: raise URLError(err) | def http_open(self, req): # XXX devise a new mechanism to specify user/password host = req.get_host() if not host: raise URLError('no host given') |
apply(h.putheader, args) | h.putheader(*args) | def http_open(self, req): # XXX devise a new mechanism to specify user/password host = req.get_host() if not host: raise URLError('no host given') |
if h.sock: h.sock.close() h.sock = None | def http_open(self, req): # XXX devise a new mechanism to specify user/password host = req.get_host() if not host: raise URLError('no host given') |
|
host = socket.gethostbyname(host) | try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) | def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password host = socket.gethostbyname(host) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splitattr(req.get_selector()) path = unquote(path) dirs = string.splitfields(path, '/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] user = passwd = '' # XXX try: fw = self.connect_ftp(user, passwd, host, port, dirs) type = file and 'I' or 'D' for attr in attrs: attr, value = splitattr(attr) if string.lower(attr) == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = string.upper(value) fp, retrlen = fw.retrfile(file, type) if retrlen is not None and retrlen >= 0: sf = StringIO('Content-Length: %d\n' % retrlen) headers = mimetools.Message(sf) else: headers = noheaders() return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors, msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] |
elif socket.gethostname() == 'walden': | elif socket.gethostname() == 'bitdiddle.concentric.net': | def build_opener(self): opener = OpenerDirectory() for ph in self.proxy_handlers: if type(ph) == types.ClassType: ph = ph() opener.add_handler(ph) |
if getattr(self.fp, 'unread'): | if hasattr(self.fp, 'unread'): | def readheaders(self): """Read header lines. Read header lines up to the entirely blank line that terminates them. The (normally blank) line that ends the headers is skipped, but not included in the returned list. If a non-header line ends the headers, (which is an error), an attempt is made to backspace over it; it is never included in the returned list. The variable self.status is set to the empty string if all went well, otherwise it is an error message. The variable self.headers is a completely uninterpreted list of lines contained in the header (so printing them will reproduce the header exactly as it appears in the file). """ self.dict = {} self.unixfrom = '' self.headers = list = [] self.status = '' headerseen = "" firstline = 1 while 1: line = self.fp.readline() if not line: self.status = 'EOF in headers' break # Skip unix From name time lines if firstline and line[:5] == 'From ': self.unixfrom = self.unixfrom + line continue firstline = 0 if headerseen and line[0] in ' \t': # It's a continuation line. list.append(line) x = (self.dict[headerseen] + "\n " + string.strip(line)) self.dict[headerseen] = string.strip(x) continue elif self.iscomment(line): # It's a comment. Ignore it. continue elif self.islast(line): # Note! No pushback here! The delimiter line gets eaten. break headerseen = self.isheader(line) if headerseen: # It's a legal header line, save it. list.append(line) self.dict[headerseen] = string.strip(line[len(headerseen)+2:]) continue else: # It's not a header line; throw it back and stop here. if not self.dict: self.status = 'No headers' else: self.status = 'Non-header line where header expected' # Try to undo the read. if getattr(self.fp, 'unread'): self.fp.unread(line) elif self.seekable: self.fp.seek(-len(line), 1) else: self.status = self.status + '; bad seek' break |
def __init__(self, out=None): | def __init__(self, out=None, encoding="iso-8859-1"): | def __init__(self, out=None): if out is None: import sys out = sys.stdout handler.ContentHandler.__init__(self) self._out = out |
self._out.write('<?xml version="1.0" encoding="iso-8859-1"?>\n') | self._out.write('<?xml version="1.0" encoding="%s"?>\n' % self._encoding) | def startDocument(self): self._out.write('<?xml version="1.0" encoding="iso-8859-1"?>\n') |
pass | self._ns_contexts.append(self._current_context.copy()) self._current_context[uri] = prefix | def startPrefixMapping(self, prefix, uri): pass |
pass | del self._current_context[-1] | def endPrefixMapping(self, prefix): pass |
if type(name) is type(()): uri, localname, prefix = name name = "%s:%s"%(prefix,localname) | def startElement(self, name, attrs): if type(name) is type(()): uri, localname, prefix = name name = "%s:%s"%(prefix,localname) self._out.write('<' + name) for (name, value) in attrs.items(): self._out.write(' %s="%s"' % (name, escape(value))) self._out.write('>') |
|
def endElement(self, name, qname): self._cont_handler.endElement(name, qname) | def endElement(self, name): self._cont_handler.endElement(name) def startElementNS(self, name, qname, attrs): self._cont_handler.startElement(name, attrs) def endElementNS(self, name, qname): self._cont_handler.endElementNS(name, qname) | def endElement(self, name, qname): self._cont_handler.endElement(name, qname) |
last.data = string.rstrip(last.data) + "\n " | last.data = last.data.rstrip() + "\n " | def rewrite_descriptor(doc, descriptor): # # Do these things: # 1. Add an "index='no'" attribute to the element if the tagName # ends in 'ni', removing the 'ni' from the name. # 2. Create a <signature> from the name attribute # 2a.Create an <args> if it appears to be available. # 3. Create additional <signature>s from <*line{,ni}> elements, # if found. # 4. If a <versionadded> is found, move it to an attribute on the # descriptor. # 5. Move remaining child nodes to a <description> element. # 6. Put it back together. # # 1. descname = descriptor.tagName index = descriptor.getAttribute("name") != "no" desctype = descname[:-4] # remove 'desc' linename = desctype + "line" if not index: linename = linename + "ni" # 2. signature = doc.createElement("signature") name = doc.createElement("name") signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(name) name.appendChild(doc.createTextNode(descriptor.getAttribute("name"))) descriptor.removeAttribute("name") # 2a. if descriptor.hasAttribute("var"): if descname != "opcodedesc": raise RuntimeError, \ "got 'var' attribute on descriptor other than opcodedesc" variable = descriptor.getAttribute("var") if variable: args = doc.createElement("args") args.appendChild(doc.createTextNode(variable)) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) descriptor.removeAttribute("var") newchildren = [signature] children = descriptor.childNodes pos = skip_leading_nodes(children) if pos < len(children): child = children[pos] if child.nodeName == "args": # move <args> to <signature>, or remove if empty: child.parentNode.removeChild(child) if len(child.childNodes): signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(child) signature.appendChild(doc.createTextNode("\n ")) # 3, 4. pos = skip_leading_nodes(children, pos) while pos < len(children) \ and children[pos].nodeName in (linename, "versionadded"): if children[pos].tagName == linename: # this is really a supplemental signature, create <signature> oldchild = children[pos].cloneNode(1) try: sig = methodline_to_signature(doc, children[pos]) except KeyError: print oldchild.toxml() raise newchildren.append(sig) else: # <versionadded added=...> descriptor.setAttribute( "added", children[pos].getAttribute("version")) pos = skip_leading_nodes(children, pos + 1) # 5. description = doc.createElement("description") description.appendChild(doc.createTextNode("\n")) newchildren.append(description) move_children(descriptor, description, pos) last = description.childNodes[-1] if last.nodeType == TEXT: last.data = string.rstrip(last.data) + "\n " # 6. # should have nothing but whitespace and signature lines in <descriptor>; # discard them while descriptor.childNodes: descriptor.removeChild(descriptor.childNodes[0]) for node in newchildren: descriptor.appendChild(doc.createTextNode("\n ")) descriptor.appendChild(node) descriptor.appendChild(doc.createTextNode("\n")) |
and not string.strip(nodes[0].data): | and not nodes[0].data.strip(): | def handle_appendix(doc, fragment): # must be called after simplfy() if document is multi-rooted to begin with docelem = get_documentElement(fragment) toplevel = docelem.tagName == "manual" and "chapter" or "section" appendices = 0 nodes = [] for node in docelem.childNodes: if appendices: nodes.append(node) elif node.nodeType == ELEMENT: appnodes = node.getElementsByTagName("appendix") if appnodes: appendices = 1 parent = appnodes[0].parentNode parent.removeChild(appnodes[0]) parent.normalize() if nodes: map(docelem.removeChild, nodes) docelem.appendChild(doc.createTextNode("\n\n\n")) back = doc.createElement("back-matter") docelem.appendChild(back) back.appendChild(doc.createTextNode("\n")) while nodes and nodes[0].nodeType == TEXT \ and not string.strip(nodes[0].data): del nodes[0] map(back.appendChild, nodes) docelem.appendChild(doc.createTextNode("\n")) |
children[-1].data = string.rstrip(children[-1].data) def fixup_trailing_whitespace(doc, wsmap): queue = [doc] | children[-1].data = children[-1].data.rstrip() def fixup_trailing_whitespace(doc, fragment, wsmap): queue = [fragment] fixups = [] | def handle_labels(doc, fragment): for label in find_all_elements(fragment, "label"): id = label.getAttribute("id") if not id: continue parent = label.parentNode parentTagName = parent.tagName if parentTagName == "title": parent.parentNode.setAttribute("id", id) else: parent.setAttribute("id", id) # now, remove <label id="..."/> from parent: parent.removeChild(label) if parentTagName == "title": parent.normalize() children = parent.childNodes if children[-1].nodeType == TEXT: children[-1].data = string.rstrip(children[-1].data) |
ws = wsmap[node.tagName] children = node.childNodes children.reverse() if children[0].nodeType == TEXT: data = string.rstrip(children[0].data) + ws children[0].data = data children.reverse() if node.tagName == "title" \ and node.parentNode.firstChild.nodeType == ELEMENT: node.parentNode.insertBefore(doc.createText("\n "), node.parentNode.firstChild) | fixups.append(node) | def fixup_trailing_whitespace(doc, wsmap): queue = [doc] while queue: node = queue[0] del queue[0] if wsmap.has_key(node.nodeName): ws = wsmap[node.tagName] children = node.childNodes children.reverse() if children[0].nodeType == TEXT: data = string.rstrip(children[0].data) + ws children[0].data = data children.reverse() # hack to get the title in place: if node.tagName == "title" \ and node.parentNode.firstChild.nodeType == ELEMENT: node.parentNode.insertBefore(doc.createText("\n "), node.parentNode.firstChild) for child in node.childNodes: if child.nodeType == ELEMENT: queue.append(child) |
first_data.data = string.lstrip(first_data.data[4:]) | first_data.data = first_data.data[4:].lstrip() | def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return set_tagName(node, "synopsis") lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: set_tagName(modauthor, "author") modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) set_tagName(title, "short-synopsis") if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: ewrite("module name in title doesn't match" " <declaremodule/>; no <short-synopsis/>\n") else: ewrite("Unexpected condition: <section/> without <title/>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated *ML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data) |
if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data) | s = data.lstrip() if len(s) < (len(data) - 4): nextnode.data = "\n\n\n" + s | def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return set_tagName(node, "synopsis") lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: set_tagName(modauthor, "author") modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) set_tagName(title, "short-synopsis") if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: ewrite("module name in title doesn't match" " <declaremodule/>; no <short-synopsis/>\n") else: ewrite("Unexpected condition: <section/> without <title/>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated *ML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data) |
if string.strip(child.data): | if child.data.strip(): | def fixup_table(doc, table): # create the table head thead = doc.createElement("thead") row = doc.createElement("row") move_elements_by_name(doc, table, row, "entry") thead.appendChild(doc.createTextNode("\n ")) thead.appendChild(row) thead.appendChild(doc.createTextNode("\n ")) # create the table body tbody = doc.createElement("tbody") prev_row = None last_was_hline = 0 children = table.childNodes for child in children: if child.nodeType == ELEMENT: tagName = child.tagName if tagName == "hline" and prev_row is not None: prev_row.setAttribute("rowsep", "1") elif tagName == "row": prev_row = child # save the rows: tbody.appendChild(doc.createTextNode("\n ")) move_elements_by_name(doc, table, tbody, "row", sep="\n ") # and toss the rest: while children: child = children[0] nodeType = child.nodeType if nodeType == TEXT: if string.strip(child.data): raise ConversionError("unexpected free data in <%s>: %r" % (table.tagName, child.data)) table.removeChild(child) continue if nodeType == ELEMENT: if child.tagName != "hline": raise ConversionError( "unexpected <%s> in table" % child.tagName) table.removeChild(child) continue raise ConversionError( "unexpected %s node in table" % child.__class__.__name__) # nothing left in the <table>; add the <thead> and <tbody> tgroup = doc.createElement("tgroup") tgroup.appendChild(doc.createTextNode("\n ")) tgroup.appendChild(thead) tgroup.appendChild(doc.createTextNode("\n ")) tgroup.appendChild(tbody) tgroup.appendChild(doc.createTextNode("\n ")) table.appendChild(tgroup) # now make the <entry>s look nice: for row in table.getElementsByTagName("row"): fixup_row(doc, row) |
pos = string.find(child.data, "\n\n") | pos = child.data.find("\n\n") | def build_para(doc, parent, start, i): children = parent.childNodes after = start + 1 have_last = 0 BREAK_ELEMENTS = PARA_LEVEL_ELEMENTS + RECURSE_INTO_PARA_CONTAINERS # Collect all children until \n\n+ is found in a text node or a # member of BREAK_ELEMENTS is found. for j in range(start, i): after = j + 1 child = children[j] nodeType = child.nodeType if nodeType == ELEMENT: if child.tagName in BREAK_ELEMENTS: after = j break elif nodeType == TEXT: pos = string.find(child.data, "\n\n") if pos == 0: after = j break if pos >= 1: child.splitText(pos) break else: have_last = 1 if (start + 1) > after: raise ConversionError( "build_para() could not identify content to turn into a paragraph") if children[after - 1].nodeType == TEXT: # we may need to split off trailing white space: child = children[after - 1] data = child.data if string.rstrip(data) != data: have_last = 0 child.splitText(len(string.rstrip(data))) para = doc.createElement(PARA_ELEMENT) prev = None indexes = range(start, after) indexes.reverse() for j in indexes: node = parent.childNodes[j] parent.removeChild(node) para.insertBefore(node, prev) prev = node if have_last: parent.appendChild(para) parent.appendChild(doc.createTextNode("\n\n")) return len(parent.childNodes) else: nextnode = parent.childNodes[start] if nextnode.nodeType == TEXT: if nextnode.data and nextnode.data[0] != "\n": nextnode.data = "\n" + nextnode.data else: newnode = doc.createTextNode("\n") parent.insertBefore(newnode, nextnode) nextnode = newnode start = start + 1 parent.insertBefore(para, nextnode) return start + 1 |
if string.rstrip(data) != data: | if data.rstrip() != data: | def build_para(doc, parent, start, i): children = parent.childNodes after = start + 1 have_last = 0 BREAK_ELEMENTS = PARA_LEVEL_ELEMENTS + RECURSE_INTO_PARA_CONTAINERS # Collect all children until \n\n+ is found in a text node or a # member of BREAK_ELEMENTS is found. for j in range(start, i): after = j + 1 child = children[j] nodeType = child.nodeType if nodeType == ELEMENT: if child.tagName in BREAK_ELEMENTS: after = j break elif nodeType == TEXT: pos = string.find(child.data, "\n\n") if pos == 0: after = j break if pos >= 1: child.splitText(pos) break else: have_last = 1 if (start + 1) > after: raise ConversionError( "build_para() could not identify content to turn into a paragraph") if children[after - 1].nodeType == TEXT: # we may need to split off trailing white space: child = children[after - 1] data = child.data if string.rstrip(data) != data: have_last = 0 child.splitText(len(string.rstrip(data))) para = doc.createElement(PARA_ELEMENT) prev = None indexes = range(start, after) indexes.reverse() for j in indexes: node = parent.childNodes[j] parent.removeChild(node) para.insertBefore(node, prev) prev = node if have_last: parent.appendChild(para) parent.appendChild(doc.createTextNode("\n\n")) return len(parent.childNodes) else: nextnode = parent.childNodes[start] if nextnode.nodeType == TEXT: if nextnode.data and nextnode.data[0] != "\n": nextnode.data = "\n" + nextnode.data else: newnode = doc.createTextNode("\n") parent.insertBefore(newnode, nextnode) nextnode = newnode start = start + 1 parent.insertBefore(para, nextnode) return start + 1 |
child.splitText(len(string.rstrip(data))) | child.splitText(len(data.rstrip())) | def build_para(doc, parent, start, i): children = parent.childNodes after = start + 1 have_last = 0 BREAK_ELEMENTS = PARA_LEVEL_ELEMENTS + RECURSE_INTO_PARA_CONTAINERS # Collect all children until \n\n+ is found in a text node or a # member of BREAK_ELEMENTS is found. for j in range(start, i): after = j + 1 child = children[j] nodeType = child.nodeType if nodeType == ELEMENT: if child.tagName in BREAK_ELEMENTS: after = j break elif nodeType == TEXT: pos = string.find(child.data, "\n\n") if pos == 0: after = j break if pos >= 1: child.splitText(pos) break else: have_last = 1 if (start + 1) > after: raise ConversionError( "build_para() could not identify content to turn into a paragraph") if children[after - 1].nodeType == TEXT: # we may need to split off trailing white space: child = children[after - 1] data = child.data if string.rstrip(data) != data: have_last = 0 child.splitText(len(string.rstrip(data))) para = doc.createElement(PARA_ELEMENT) prev = None indexes = range(start, after) indexes.reverse() for j in indexes: node = parent.childNodes[j] parent.removeChild(node) para.insertBefore(node, prev) prev = node if have_last: parent.appendChild(para) parent.appendChild(doc.createTextNode("\n\n")) return len(parent.childNodes) else: nextnode = parent.childNodes[start] if nextnode.nodeType == TEXT: if nextnode.data and nextnode.data[0] != "\n": nextnode.data = "\n" + nextnode.data else: newnode = doc.createTextNode("\n") parent.insertBefore(newnode, nextnode) nextnode = newnode start = start + 1 parent.insertBefore(para, nextnode) return start + 1 |
shortened = string.lstrip(data) | shortened = data.lstrip() | def skip_leading_nodes(children, start=0): """Return index into children of a node at which paragraph building should begin or a recursive call to fixup_paras_helper() should be made (for subsections, etc.). When the return value >= len(children), we've built all the paras we can from this list of children. """ i = len(children) while i > start: # skip over leading comments and whitespace: child = children[start] nodeType = child.nodeType if nodeType == TEXT: data = child.data shortened = string.lstrip(data) if shortened: if data != shortened: # break into two nodes: whitespace and non-whitespace child.splitText(len(data) - len(shortened)) return start + 1 return start # all whitespace, just skip elif nodeType == ELEMENT: tagName = child.tagName if tagName in RECURSE_INTO_PARA_CONTAINERS: return start if tagName not in PARA_LEVEL_ELEMENTS + PARA_LEVEL_PRECEEDERS: return start start = start + 1 return start |
and string.lstrip(child.data)[:3] == ">>>": | and child.data.lstrip().startswith(">>>"): | def fixup_verbatims(doc): for verbatim in find_all_elements(doc, "verbatim"): child = verbatim.childNodes[0] if child.nodeType == TEXT \ and string.lstrip(child.data)[:3] == ">>>": set_tagName(verbatim, "interactive-session") |
fixup_trailing_whitespace(doc, { "abstract": "\n", "title": "", "chapter": "\n\n", "section": "\n\n", "subsection": "\n\n", "subsubsection": "\n\n", "paragraph": "\n\n", "subparagraph": "\n\n", | fixup_trailing_whitespace(doc, fragment, { "abstract": ("\n", "\n"), "title": ("", "\n"), "chapter": ("\n", "\n\n\n"), "section": ("\n", "\n\n\n"), "subsection": ("\n", "\n\n"), "subsubsection": ("\n", "\n\n"), "paragraph": ("\n", "\n\n"), "subparagraph": ("\n", "\n\n"), "enumeration": ("\n", "\n\n"), | def convert(ifp, ofp): events = esistools.parse(ifp) toktype, doc = events.getEvent() fragment = doc.createDocumentFragment() events.expandNode(fragment) normalize(fragment) simplify(doc, fragment) handle_labels(doc, fragment) handle_appendix(doc, fragment) fixup_trailing_whitespace(doc, { "abstract": "\n", "title": "", "chapter": "\n\n", "section": "\n\n", "subsection": "\n\n", "subsubsection": "\n\n", "paragraph": "\n\n", "subparagraph": "\n\n", }) cleanup_root_text(doc) cleanup_trailing_parens(fragment, ["function", "method", "cfunction"]) cleanup_synopses(doc, fragment) fixup_descriptors(doc, fragment) fixup_verbatims(fragment) normalize(fragment) fixup_paras(doc, fragment) fixup_sectionauthors(doc, fragment) fixup_table_structures(doc, fragment) fixup_rfc_references(doc, fragment) fixup_signatures(doc, fragment) fixup_ulink(doc, fragment) add_node_ids(fragment) fixup_refmodindexes(fragment) fixup_bifuncindexes(fragment) # Take care of ugly hacks in the LaTeX markup to avoid LaTeX and # LaTeX2HTML screwing with GNU-style long options (the '--' problem). join_adjacent_elements(fragment, "option") # d = {} for gi in events.parser.get_empties(): d[gi] = gi if d.has_key("author"): del d["author"] if d.has_key("rfc"): del d["rfc"] knownempty = d.has_key # try: write_esis(fragment, ofp, knownempty) except IOError, (err, msg): # Ignore EPIPE; it just means that whoever we're writing to stopped # reading. The rest of the output would be ignored. All other errors # should still be reported, if err != errno.EPIPE: raise |
self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqdn, repr(all_host_names))) | self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) | def testHostnameRes(self): # Testing hostname resolution mechanisms hostname = socket.gethostname() try: ip = socket.gethostbyname(hostname) except socket.error: # Probably name lookup wasn't set up right; skip this test return self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") try: hname, aliases, ipaddrs = socket.gethostbyaddr(ip) except socket.error: # Probably a similar problem as above; skip this test return all_host_names = [hostname, hname] + aliases fqhn = socket.getfqdn() if not fqhn in all_host_names: self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqdn, repr(all_host_names))) |
macostools.mkalias(os.path.join(sys.exec_prefix, src), dst) | do_copy = 0 if macfs.FSSpec(sys.exec_prefix).as_tuple()[0] != -1: try: import Dlg rv = Dlg.CautionAlert(ALERT_NONBOOT, None) if rv == ALERT_NONBOOT_COPY: do_copy = 1 except ImportError: pass if do_copy: macostools.copy(os.path.join(sys.exec_prefix, src), dst) else: macostools.mkalias(os.path.join(sys.exec_prefix, src), dst) | def mkcorealias(src, altsrc): import string import macostools version = string.split(sys.version)[0] dst = getextensiondirfile(src+ ' ' + version) if not os.path.exists(os.path.join(sys.exec_prefix, src)): if not os.path.exists(os.path.join(sys.exec_prefix, altsrc)): if verbose: print '*', src, 'not found' return 0 src = altsrc try: os.unlink(dst) except os.error: pass macostools.mkalias(os.path.join(sys.exec_prefix, src), dst) if verbose: print ' ', dst, '->', src return 1 |
print items[i]; i+=1 | b = items[i]; i+=1 | def tightloop_example(): items = range(0, 3) try: i = 0 while 1: print items[i]; i+=1 except IndexError: pass |
'Expected:\n%s\nbut got:\n%s' % ( self.show(result), self.show(expect))) | 'expected:\n%s\nbut got:\n%s' % ( self.show(expect), self.show(result))) | def check(self, result, expect): self.assertEquals(result, expect, 'Expected:\n%s\nbut got:\n%s' % ( self.show(result), self.show(expect))) |
f.write('z') f.seek(0) f.seek(size) f.write('a') f.flush() if test_support.verbose: print 'check file size with os.fstat' expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1) f.close() | try: f.write('z') f.seek(0) f.seek(size) f.write('a') f.flush() if test_support.verbose: print 'check file size with os.fstat' expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1) finally: f.close() | def expect(got_this, expect_this): if test_support.verbose: print '%r =?= %r ...' % (got_this, expect_this), if got_this != expect_this: if test_support.verbose: print 'no' raise test_support.TestFailed, 'got %r, but expected %r' %\ (got_this, expect_this) else: if test_support.verbose: print 'yes' |
expect(f.tell(), 0) expect(f.read(1), 'z') expect(f.tell(), 1) f.seek(0) expect(f.tell(), 0) f.seek(0, 0) expect(f.tell(), 0) f.seek(42) expect(f.tell(), 42) f.seek(42, 0) expect(f.tell(), 42) f.seek(42, 1) expect(f.tell(), 84) f.seek(0, 1) expect(f.tell(), 84) f.seek(0, 2) expect(f.tell(), size + 1 + 0) f.seek(-10, 2) expect(f.tell(), size + 1 - 10) f.seek(-size-1, 2) expect(f.tell(), 0) f.seek(size) expect(f.tell(), size) expect(f.read(1), 'a') f.seek(-size-1, 1) expect(f.read(1), 'z') expect(f.tell(), 1) f.close() | try: expect(f.tell(), 0) expect(f.read(1), 'z') expect(f.tell(), 1) f.seek(0) expect(f.tell(), 0) f.seek(0, 0) expect(f.tell(), 0) f.seek(42) expect(f.tell(), 42) f.seek(42, 0) expect(f.tell(), 42) f.seek(42, 1) expect(f.tell(), 84) f.seek(0, 1) expect(f.tell(), 84) f.seek(0, 2) expect(f.tell(), size + 1 + 0) f.seek(-10, 2) expect(f.tell(), size + 1 - 10) f.seek(-size-1, 2) expect(f.tell(), 0) f.seek(size) expect(f.tell(), size) expect(f.read(1), 'a') f.seek(-size-1, 1) expect(f.read(1), 'z') expect(f.tell(), 1) finally: f.close() | def expect(got_this, expect_this): if test_support.verbose: print '%r =?= %r ...' % (got_this, expect_this), if got_this != expect_this: if test_support.verbose: print 'no' raise test_support.TestFailed, 'got %r, but expected %r' %\ (got_this, expect_this) else: if test_support.verbose: print 'yes' |
expect(os.lseek(f.fileno(), 0, 0), 0) expect(os.lseek(f.fileno(), 42, 0), 42) expect(os.lseek(f.fileno(), 42, 1), 84) expect(os.lseek(f.fileno(), 0, 1), 84) expect(os.lseek(f.fileno(), 0, 2), size+1+0) expect(os.lseek(f.fileno(), -10, 2), size+1-10) expect(os.lseek(f.fileno(), -size-1, 2), 0) expect(os.lseek(f.fileno(), size, 0), size) expect(f.read(1), 'a') f.close() | try: expect(os.lseek(f.fileno(), 0, 0), 0) expect(os.lseek(f.fileno(), 42, 0), 42) expect(os.lseek(f.fileno(), 42, 1), 84) expect(os.lseek(f.fileno(), 0, 1), 84) expect(os.lseek(f.fileno(), 0, 2), size+1+0) expect(os.lseek(f.fileno(), -10, 2), size+1-10) expect(os.lseek(f.fileno(), -size-1, 2), 0) expect(os.lseek(f.fileno(), size, 0), size) expect(f.read(1), 'a') finally: f.close() | def expect(got_this, expect_this): if test_support.verbose: print '%r =?= %r ...' % (got_this, expect_this), if got_this != expect_this: if test_support.verbose: print 'no' raise test_support.TestFailed, 'got %r, but expected %r' %\ (got_this, expect_this) else: if test_support.verbose: print 'yes' |
f.seek(0, 2) expect(f.tell(), size+1) newsize = size - 10 f.seek(newsize) f.truncate() expect(f.tell(), newsize) f.seek(0, 2) expect(f.tell(), newsize) newsize -= 1 f.seek(42) f.truncate(newsize) expect(f.tell(), 42) f.seek(0, 2) expect(f.tell(), newsize) | try: f.seek(0, 2) expect(f.tell(), size+1) newsize = size - 10 f.seek(newsize) f.truncate() expect(f.tell(), newsize) f.seek(0, 2) expect(f.tell(), newsize) newsize -= 1 f.seek(42) f.truncate(newsize) expect(f.tell(), 42) f.seek(0, 2) expect(f.tell(), newsize) | def expect(got_this, expect_this): if test_support.verbose: print '%r =?= %r ...' % (got_this, expect_this), if got_this != expect_this: if test_support.verbose: print 'no' raise test_support.TestFailed, 'got %r, but expected %r' %\ (got_this, expect_this) else: if test_support.verbose: print 'yes' |
f.close() | finally: f.close() | def expect(got_this, expect_this): if test_support.verbose: print '%r =?= %r ...' % (got_this, expect_this), if got_this != expect_this: if test_support.verbose: print 'no' raise test_support.TestFailed, 'got %r, but expected %r' %\ (got_this, expect_this) else: if test_support.verbose: print 'yes' |
self.assertEqual(binascii.a2b_qp("= "), "") | self.assertEqual(binascii.a2b_qp("= "), "= ") | def test_qp(self): # A test for SF bug 534347 (segfaults without the proper fix) try: binascii.a2b_qp("", **{1:1}) except TypeError: pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") self.assertEqual(binascii.a2b_qp("= "), "") self.assertEqual(binascii.a2b_qp("=="), "=") self.assertEqual(binascii.a2b_qp("=AX"), "=AX") self.assertRaises(TypeError, binascii.b2a_qp, foo="bar") self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00") self.assertEqual( binascii.b2a_qp("\xff\r\n\xff\n\xff"), "=FF\r\n=FF\r\n=FF" ) self.assertEqual( binascii.b2a_qp("0"*75+"\xff\r\n\xff\r\n\xff"), "0"*75+"=\r\n=FF\r\n=FF\r\n=FF" ) |
l.grid(row=self.row, col=0, sticky="nw") | l.grid(row=self.row, column=0, sticky="nw") | def make_entry(self, label, var): l = Label(self.top, text=label) l.grid(row=self.row, col=0, sticky="nw") e = Entry(self.top, textvariable=var, exportselection=0) e.grid(row=self.row, col=1, sticky="nwe") self.row = self.row + 1 return e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.