bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
def uid(self, command, *args): """Execute "command arg ..." with messages identified by UID, rather than message number.
6,800
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
6,801
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
6,802
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
def xatom(self, name, *args): """Allow simple extension commands notified by server in CAPABILITY response.
6,803
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
6,804
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
6,805
def _command(self, name, dat1=None, dat2=None, dat3=None, literal=None):
def _command(self, name, dat1=None, dat2=None, dat3=None, literal=None):
6,806
def _get_response(self):
def _get_response(self):
6,807
def _get_response(self):
def _get_response(self):
6,808
def _get_line(self):
def _get_line(self):
6,809
def _simple_command(self, name, dat1=None, dat2=None):
def _simple_command(self, name, dat1=None, dat2=None):
6,810
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
6,811
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
6,812
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
6,813
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
6,814
def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1
def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1
6,815
def break_yolks(self): self.yolks = self.yolks - 2
def break_yolks(self): self.yolks = self.yolks - 2
6,816
def break_yolks(self): self.yolks = self.yolks - 2
def break_yolks(self): self.yolks = self.yolks - 2
6,817
def _writecrc(self): # XXXX Should this be here?? # self.crc = binascii.crc_hqx('\0\0', self.crc) self.ofp.write(struct.pack('>h', self.crc)) self.crc = 0
def _writecrc(self): # XXXX Should this be here?? # self.crc = binascii.crc_hqx('\0\0', self.crc) if self.crc < 0: fmt = '>h' else: fmt = '>H' self.ofp.write(struct.pack(fmt, self.crc)) self.crc = 0
6,818
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = '<a href="file:%s">%s</a>' % (url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc)
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = '<a href="file:%s">%s</a>' % (url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc)
6,819
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = '<a href="file:%s">%s</a>' % (url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc)
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = '<a href="file:%s">%s</a>' % (url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc)
6,820
def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop))
def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop))
6,821
def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop))
def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop))
6,822
def test_weak_keys(self): # # This exercises d.copy(), d.items(), d[] = v, d[], del d[], # len(d). # dict, objects = self.make_weak_keyed_dict() for o in objects: self.assert_(weakref.getweakrefcount(o) == 1, "wrong number of weak references to %r!" % o) self.assert_(o.arg is dict[o], "wrong object returned by weak dict!") items1 = dict.items() items2 = dict.copy().items() items1.sort() items2.sort() self.assert_(items1 == items2, "cloning of weak-keyed dictionary did not work!") del items1, items2 self.assert_(len(dict) == self.COUNT) del objects[0] self.assert_(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o self.assert_(len(dict) == 0, "deleting the keys did not clear the dictionary")
def test_weak_keys(self): # # This exercises d.copy(), d.items(), d[] = v, d[], del d[], # len(d). # dict, objects = self.make_weak_keyed_dict() for o in objects: self.assert_(weakref.getweakrefcount(o) == 1, "wrong number of weak references to %r!" % o) self.assert_(o.arg is dict[o], "wrong object returned by weak dict!") items1 = dict.items() items2 = dict.copy().items() items1.sort() items2.sort() self.assert_(items1 == items2, "cloning of weak-keyed dictionary did not work!") del items1, items2 self.assert_(len(dict) == self.COUNT) del objects[0] self.assert_(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o self.assert_(len(dict) == 0, "deleting the keys did not clear the dictionary")
6,823
def setup(self): import StringIO self.packet, self.socket = self.request self.rfile = StringIO.StringIO(self.packet) self.wfile = StringIO.StringIO(self.packet)
def setup(self): import StringIO self.packet, self.socket = self.request self.rfile = StringIO.StringIO(self.packet) self.wfile = StringIO.StringIO(self.packet)
6,824
def mkdirs(dst): """Make directories leading to 'dst' if they don't exist yet""" if dst == '' or os.path.exists(dst): return head, tail = os.path.split(dst) print 'XX', dst, '->', (head, tail) # XXXX Is this a bug in os.path.split? if not ':' in head: head = head + ':' mkdirs(head) os.mkdir(dst, 0777)
def mkdirs(dst): """Make directories leading to 'dst' if they don't exist yet""" if dst == '' or os.path.exists(dst): return head, tail = os.path.split(dst) print 'XX', dst, '->', (head, tail) # XXXX Is this a bug in os.path.split? if not ':' in head: head = head + ':' mkdirs(head) os.mkdir(dst, 0777)
6,825
def spillproperties(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push('<dl><dt><strong>%s</strong></dt>\n' % name) if value.__doc__ is not None: doc = self.markup(value.__doc__, self.preformat, funcs, classes, mdict) push('<dd><tt>%s</tt></dd>\n' % doc) for attr, tag in [('fget', '<em>get</em>'), ('fset', '<em>set</em>'), ('fdel', '<em>delete</em>')]: func = getattr(value, attr) if func is not None: base = self.document(func, tag, mod, funcs, classes, mdict, object) push('<dd>%s</dd>\n' % base) push('</dl>\n') return attrs
def spillproperties(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docproperty(name, value, mod)) return attrs
6,826
def spillproperties(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(name) need_blank_after_doc = 0 doc = getdoc(value) or '' if doc: push(self.indent(doc)) need_blank_after_doc = 1 for attr, tag in [('fget', '<get>'), ('fset', '<set>'), ('fdel', '<delete>')]: func = getattr(value, attr) if func is not None: if need_blank_after_doc: push('') need_blank_after_doc = 0 base = self.document(func, tag, mod) push(self.indent(base)) return attrs
def spillproperties(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docproperty(name, value, mod)) return attrs
6,827
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splitattr(req.get_selector()) path = unquote(path) dirs = path.split('/') 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 attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() fp, retrlen = fw.retrfile(file, type) headers = "" mtype = mimetypes.guess_type(req.get_full_url())[0] if mtype: headers += "Content-type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-length: %d\n" % retrlen sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors, msg: raise IOError, ('ftp error', msg), sys.exc_info()[2]
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splitattr(req.get_selector()) dirs = path.split('/') 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 attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() fp, retrlen = fw.retrfile(file, type) headers = "" mtype = mimetypes.guess_type(req.get_full_url())[0] if mtype: headers += "Content-type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-length: %d\n" % retrlen sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors, msg: raise IOError, ('ftp error', msg), sys.exc_info()[2]
6,828
def expect(self, list, timeout=None): """Read until one from a list of a regular expressions matches.
def expect(self, list, timeout=None): """Read until one from a list of a regular expressions matches.
6,829
def get_inidata (self): # Return data describing the installation.
def get_inidata (self): # Return data describing the installation.
6,830
def get_inidata (self): # Return data describing the installation.
def get_inidata (self): # Return data describing the installation.
6,831
def get_inidata (self): # Return data describing the installation.
def get_inidata (self): # Return data describing the installation.
6,832
def get_inidata (self): # Return data describing the installation.
def get_inidata (self): # Return data describing the installation.
6,833
def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string]
def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string]
6,834
def _init_posix(): import os import re import string import sys g = globals() version = sys.version[:3] config_dir = os.path.join( sys.exec_prefix, "lib", "python" + version, "config") # load the installed config.h: define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n") fp = open(os.path.join(config_dir, "config.h")) while 1: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = string.atoi(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 # load the installed Makefile.pre.in: variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} fp = open(os.path.join(config_dir, "Makefile")) while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # save the results in the global dictionary g.update(done)
g = globals() version = sys.version[:3] config_dir = os.path.join( sys.exec_prefix, "lib", "python" + version, "config") # load the installed config.h: define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n") fp = open(os.path.join(config_dir, "config.h")) while 1: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = string.atoi(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 # load the installed Makefile.pre.in: variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} fp = open(os.path.join(config_dir, "Makefile")) while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # save the results in the global dictionary g.update(done)
6,835
def _init_posix(): import os import re import string import sys g = globals() version = sys.version[:3] config_dir = os.path.join( sys.exec_prefix, "lib", "python" + version, "config") # load the installed config.h: define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n") fp = open(os.path.join(config_dir, "config.h")) while 1: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = string.atoi(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 # load the installed Makefile.pre.in: variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} fp = open(os.path.join(config_dir, "Makefile")) while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # save the results in the global dictionary g.update(done)
def _init_posix(): import os import re import string import sys def get_config_h_filename(): return os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3], "config", "config.h") version = sys.version[:3] config_dir = os.path.join( sys.exec_prefix, "lib", "python" + version, "config") # load the installed config.h: define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n") fp = open(os.path.join(config_dir, "config.h")) while 1: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = string.atoi(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 # load the installed Makefile.pre.in: variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} fp = open(os.path.join(config_dir, "Makefile")) while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # save the results in the global dictionary g.update(done)
6,836
def _init_posix(): import os import re import string import sys g = globals() version = sys.version[:3] config_dir = os.path.join( sys.exec_prefix, "lib", "python" + version, "config") # load the installed config.h: define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n") fp = open(os.path.join(config_dir, "config.h")) while 1: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = string.atoi(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 # load the installed Makefile.pre.in: variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} fp = open(os.path.join(config_dir, "Makefile")) while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # save the results in the global dictionary g.update(done)
def _init_posix(): import os import re import string import sys g = globals() def get_makefile_filename(): return os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3], "config", "Makefile") # load the installed config.h: define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n") fp = open(os.path.join(config_dir, "config.h")) while 1: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = string.atoi(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 # load the installed Makefile.pre.in: variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} fp = open(os.path.join(config_dir, "Makefile")) while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # save the results in the global dictionary g.update(done)
6,837
def _init_posix(): import os import re import string import sys g = globals() version = sys.version[:3] config_dir = os.path.join( sys.exec_prefix, "lib", "python" + version, "config") # load the installed config.h: define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n") fp = open(os.path.join(config_dir, "config.h")) while 1: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = string.atoi(v) except ValueError: pass g[n] = v else: m = undef_rx.match(line) if m: g[m.group(1)] = 0 # load the installed Makefile.pre.in: variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n") done = {} notdone = {} fp = open(os.path.join(config_dir, "Makefile")) while 1: line = fp.readline() if not line: break m = variable_rx.match(line) if m: n, v = m.group(1, 2) v = string.strip(v) if "$" in v: notdone[n] = v else: try: v = string.atoi(v) except ValueError: pass done[n] = v # do variable interpolation here findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") while notdone: for name in notdone.keys(): value = notdone[name] m = findvar1_rx.search(value) if not m: m = findvar2_rx.search(value) if m: n = m.group(1) if done.has_key(n): after = value[m.end():] value = value[:m.start()] + done[n] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] elif notdone.has_key(n): # get it on a subsequent round pass else: done[n] = "" after = value[m.end():] value = value[:m.start()] + after if "$" in after: notdone[name] = value else: try: value = string.atoi(value) except ValueError: pass done[name] = string.strip(value) del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # save the results in the global dictionary g.update(done)
defdef parse_config_h(fp, g=None): if g is None: g = {} _init_posix():def parse_config_h(fp, g=None): if g is None: g = {} importdef parse_config_h(fp, g=None): if g is None: g = {} osdef parse_config_h(fp, g=None): if g is None: g = {} importdef parse_config_h(fp, g=None): if g is None: g = {} redef parse_config_h(fp, g=None): if g is None: g = {} importdef parse_config_h(fp, g=None): if g is None: g = {} stringdef parse_config_h(fp, g=None): if g is None: g = {} importdef parse_config_h(fp, g=None): if g is None: g = {} sysdef parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} gdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} globals()def parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} versiondef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} sys.version[:3]def parse_config_h(fp, g=None): if g is None: g = {} config_dirdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} os.path.join(def parse_config_h(fp, g=None): if g is None: g = {} sys.exec_prefix,def parse_config_h(fp, g=None): if g is None: g = {} "lib",def parse_config_h(fp, g=None): if g is None: g = {} "python"def parse_config_h(fp, g=None): if g is None: g = {} +def parse_config_h(fp, g=None): if g is None: g = {} version,def parse_config_h(fp, g=None): if g is None: g = {} "config")def parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} #def parse_config_h(fp, g=None): if g is None: g = {} loaddef parse_config_h(fp, g=None): if g is None: g = {} thedef parse_config_h(fp, g=None): if g is None: g = {} installeddef parse_config_h(fp, g=None): if g is None: g = {} config.h:def parse_config_h(fp, g=None): if g is None: g = {} define_rxdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} re.compile("#definedef parse_config_h(fp, g=None): if g is None: g = {} ([A-Z][A-Z0-9_]+)def parse_config_h(fp, g=None): if g is None: g = {} (.*)\n")def parse_config_h(fp, g=None): if g is None: g = {} undef_rxdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} re.compile("/[*]def parse_config_h(fp, g=None): if g is None: g = {} #undefdef parse_config_h(fp, g=None): if g is None: g = {} ([A-Z][A-Z0-9_]+)def parse_config_h(fp, g=None): if g is None: g = {} [*]/\n")def parse_config_h(fp, g=None): if g is None: g = {} fpdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} open(os.path.join(config_dir,def parse_config_h(fp, g=None): if g is None: g = {} "config.h"))def parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} whiledef parse_config_h(fp, g=None): if g is None: g = {} 1:def parse_config_h(fp, g=None): if g is None: g = {} linedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} fp.readline()def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} notdef parse_config_h(fp, g=None): if g is None: g = {} line:def parse_config_h(fp, g=None): if g is None: g = {} breakdef parse_config_h(fp, g=None): if g is None: g = {} mdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} define_rx.match(line)def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} m:def parse_config_h(fp, g=None): if g is None: g = {} n,def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} m.group(1,def parse_config_h(fp, g=None): if g is None: g = {} 2)def parse_config_h(fp, g=None): if g is None: g = {} try:def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} string.atoi(v)def parse_config_h(fp, g=None): if g is None: g = {} exceptdef parse_config_h(fp, g=None): if g is None: g = {} ValueError:def parse_config_h(fp, g=None): if g is None: g = {} passdef parse_config_h(fp, g=None): if g is None: g = {} g[n]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} else:def parse_config_h(fp, g=None): if g is None: g = {} mdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} undef_rx.match(line)def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} m:def parse_config_h(fp, g=None): if g is None: g = {} g[m.group(1)]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} 0def parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} #def parse_config_h(fp, g=None): if g is None: g = {} loaddef parse_config_h(fp, g=None): if g is None: g = {} thedef parse_config_h(fp, g=None): if g is None: g = {} installeddef parse_config_h(fp, g=None): if g is None: g = {} Makefile.pre.in:def parse_config_h(fp, g=None): if g is None: g = {} variable_rxdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)\n")def parse_config_h(fp, g=None): if g is None: g = {} donedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} {}def parse_config_h(fp, g=None): if g is None: g = {} notdonedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} {}def parse_config_h(fp, g=None): if g is None: g = {} fpdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} open(os.path.join(config_dir,def parse_config_h(fp, g=None): if g is None: g = {} "Makefile"))def parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} whiledef parse_config_h(fp, g=None): if g is None: g = {} 1:def parse_config_h(fp, g=None): if g is None: g = {} linedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} fp.readline()def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} notdef parse_config_h(fp, g=None): if g is None: g = {} line:def parse_config_h(fp, g=None): if g is None: g = {} breakdef parse_config_h(fp, g=None): if g is None: g = {} mdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} variable_rx.match(line)def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} m:def parse_config_h(fp, g=None): if g is None: g = {} n,def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} m.group(1,def parse_config_h(fp, g=None): if g is None: g = {} 2)def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} string.strip(v)def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} "$"def parse_config_h(fp, g=None): if g is None: g = {} indef parse_config_h(fp, g=None): if g is None: g = {} v:def parse_config_h(fp, g=None): if g is None: g = {} notdone[n]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} else:def parse_config_h(fp, g=None): if g is None: g = {} try:def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} string.atoi(v)def parse_config_h(fp, g=None): if g is None: g = {} exceptdef parse_config_h(fp, g=None): if g is None: g = {} ValueError:def parse_config_h(fp, g=None): if g is None: g = {} passdef parse_config_h(fp, g=None): if g is None: g = {} done[n]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} vdef parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} #def parse_config_h(fp, g=None): if g is None: g = {} dodef parse_config_h(fp, g=None): if g is None: g = {} variabledef parse_config_h(fp, g=None): if g is None: g = {} interpolationdef parse_config_h(fp, g=None): if g is None: g = {} heredef parse_config_h(fp, g=None): if g is None: g = {} findvar1_rxdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")def parse_config_h(fp, g=None): if g is None: g = {} findvar2_rxdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")def parse_config_h(fp, g=None): if g is None: g = {} whiledef parse_config_h(fp, g=None): if g is None: g = {} notdone:def parse_config_h(fp, g=None): if g is None: g = {} fordef parse_config_h(fp, g=None): if g is None: g = {} namedef parse_config_h(fp, g=None): if g is None: g = {} indef parse_config_h(fp, g=None): if g is None: g = {} notdone.keys():def parse_config_h(fp, g=None): if g is None: g = {} valuedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} notdone[name]def parse_config_h(fp, g=None): if g is None: g = {} mdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} findvar1_rx.search(value)def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} notdef parse_config_h(fp, g=None): if g is None: g = {} m:def parse_config_h(fp, g=None): if g is None: g = {} mdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} findvar2_rx.search(value)def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} m:def parse_config_h(fp, g=None): if g is None: g = {} ndef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} m.group(1)def parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} done.has_key(n):def parse_config_h(fp, g=None): if g is None: g = {} afterdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} value[m.end():]def parse_config_h(fp, g=None): if g is None: g = {} valuedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} value[:m.start()]def parse_config_h(fp, g=None): if g is None: g = {} +def parse_config_h(fp, g=None): if g is None: g = {} done[n]def parse_config_h(fp, g=None): if g is None: g = {} +def parse_config_h(fp, g=None): if g is None: g = {} afterdef parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} "$"def parse_config_h(fp, g=None): if g is None: g = {} indef parse_config_h(fp, g=None): if g is None: g = {} after:def parse_config_h(fp, g=None): if g is None: g = {} notdone[name]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} valuedef parse_config_h(fp, g=None): if g is None: g = {} else:def parse_config_h(fp, g=None): if g is None: g = {} try:def parse_config_h(fp, g=None): if g is None: g = {} valuedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} string.atoi(value)def parse_config_h(fp, g=None): if g is None: g = {} exceptdef parse_config_h(fp, g=None): if g is None: g = {} ValueError:def parse_config_h(fp, g=None): if g is None: g = {} passdef parse_config_h(fp, g=None): if g is None: g = {} done[name]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} string.strip(value)def parse_config_h(fp, g=None): if g is None: g = {} deldef parse_config_h(fp, g=None): if g is None: g = {} notdone[name]def parse_config_h(fp, g=None): if g is None: g = {} elifdef parse_config_h(fp, g=None): if g is None: g = {} notdone.has_key(n):def parse_config_h(fp, g=None): if g is None: g = {} #def parse_config_h(fp, g=None): if g is None: g = {} getdef parse_config_h(fp, g=None): if g is None: g = {} itdef parse_config_h(fp, g=None): if g is None: g = {} ondef parse_config_h(fp, g=None): if g is None: g = {} adef parse_config_h(fp, g=None): if g is None: g = {} subsequentdef parse_config_h(fp, g=None): if g is None: g = {} rounddef parse_config_h(fp, g=None): if g is None: g = {} passdef parse_config_h(fp, g=None): if g is None: g = {} else:def parse_config_h(fp, g=None): if g is None: g = {} done[n]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} ""def parse_config_h(fp, g=None): if g is None: g = {} afterdef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} value[m.end():]def parse_config_h(fp, g=None): if g is None: g = {} valuedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} value[:m.start()]def parse_config_h(fp, g=None): if g is None: g = {} +def parse_config_h(fp, g=None): if g is None: g = {} afterdef parse_config_h(fp, g=None): if g is None: g = {} ifdef parse_config_h(fp, g=None): if g is None: g = {} "$"def parse_config_h(fp, g=None): if g is None: g = {} indef parse_config_h(fp, g=None): if g is None: g = {} after:def parse_config_h(fp, g=None): if g is None: g = {} notdone[name]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} valuedef parse_config_h(fp, g=None): if g is None: g = {} else:def parse_config_h(fp, g=None): if g is None: g = {} try:def parse_config_h(fp, g=None): if g is None: g = {} valuedef parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} string.atoi(value)def parse_config_h(fp, g=None): if g is None: g = {} exceptdef parse_config_h(fp, g=None): if g is None: g = {} ValueError:def parse_config_h(fp, g=None): if g is None: g = {} passdef parse_config_h(fp, g=None): if g is None: g = {} done[name]def parse_config_h(fp, g=None): if g is None: g = {} =def parse_config_h(fp, g=None): if g is None: g = {} string.strip(value)def parse_config_h(fp, g=None): if g is None: g = {} deldef parse_config_h(fp, g=None): if g is None: g = {} notdone[name]def parse_config_h(fp, g=None): if g is None: g = {} else:def parse_config_h(fp, g=None): if g is None: g = {} #def parse_config_h(fp, g=None): if g is None: g = {} bogusdef parse_config_h(fp, g=None): if g is None: g = {} variabledef parse_config_h(fp, g=None): if g is None: g = {} reference;def parse_config_h(fp, g=None): if g is None: g = {} justdef parse_config_h(fp, g=None): if g is None: g = {} dropdef parse_config_h(fp, g=None): if g is None: g = {} itdef parse_config_h(fp, g=None): if g is None: g = {} sincedef parse_config_h(fp, g=None): if g is None: g = {} wedef parse_config_h(fp, g=None): if g is None: g = {} can'tdef parse_config_h(fp, g=None): if g is None: g = {} dealdef parse_config_h(fp, g=None): if g is None: g = {} deldef parse_config_h(fp, g=None): if g is None: g = {} notdone[name]def parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {} #def parse_config_h(fp, g=None): if g is None: g = {} savedef parse_config_h(fp, g=None): if g is None: g = {} thedef parse_config_h(fp, g=None): if g is None: g = {} resultsdef parse_config_h(fp, g=None): if g is None: g = {} indef parse_config_h(fp, g=None): if g is None: g = {} thedef parse_config_h(fp, g=None): if g is None: g = {} globaldef parse_config_h(fp, g=None): if g is None: g = {} dictionarydef parse_config_h(fp, g=None): if g is None: g = {} g.update(done)def parse_config_h(fp, g=None): if g is None: g = {} def parse_config_h(fp, g=None): if g is None: g = {}
6,838
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
6,839
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
undef_rxdef parse_makefile(fp, g=None): if g is None: g = {} =def parse_makefile(fp, g=None): if g is None: g = {} re.compile("/[*]def parse_makefile(fp, g=None): if g is None: g = {} #undefdef parse_makefile(fp, g=None): if g is None: g = {} ([A-Z][A-Z0-9_]+)def parse_makefile(fp, g=None): if g is None: g = {} [*]/\n")
6,840
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
6,841
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
6,842
def _remote(self, action): assert "'" not in action cmd = "kfmclient '%s' >/dev/null 2>&1" % action rc = os.system(cmd) if rc: import time if self.basename == "konqueror": os.system(self.name + " --silent &") else: os.system(self.name + " -d &") time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc
def _remote(self, action): cmd = "kfmclient %s >/dev/null 2>&1" % action rc = os.system(cmd) if rc: import time if self.basename == "konqueror": os.system(self.name + " --silent &") else: os.system(self.name + " -d &") time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc
6,843
def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info()
def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info()
6,844
def do_open(self, http_class, req): """Return an addinfourl object for the request, using http_class.
def do_open(self, http_class, req): """Return an addinfourl object for the request, using http_class.
6,845
def __init__(self, path=None, debug=0, excludes = [], replace_paths = []): if path is None: path = sys.path self.path = path self.modules = {} self.badmodules = {} self.debug = debug self.indent = 0 self.excludes = excludes self.replace_paths = replace_paths self.processed_paths = [] # Used in debugging only
def __init__(self, path=None, debug=0, excludes=[], replace_paths=[]): if path is None: path = sys.path self.path = path self.modules = {} self.badmodules = {} self.debug = debug self.indent = 0 self.excludes = excludes self.replace_paths = replace_paths self.processed_paths = [] # Used in debugging only
6,846
def import_module(self, partname, fqname, parent): self.msgin(3, "import_module", partname, fqname, parent) try: m = self.modules[fqname] except KeyError: pass else: self.msgout(3, "import_module ->", m) return m if self.badmodules.has_key(fqname): self.msgout(3, "import_module -> None") if parent: self.badmodules[fqname][parent.__name__] = None return None try: fp, pathname, stuff = self.find_module(partname, parent and parent.__path__) except ImportError: self.msgout(3, "import_module ->", None) return None try: m = self.load_module(fqname, fp, pathname, stuff) finally: if fp: fp.close() if parent: setattr(parent, partname, m) self.msgout(3, "import_module ->", m) return m
def import_module(self, partname, fqname, parent): self.msgin(3, "import_module", partname, fqname, parent) try: m = self.modules[fqname] except KeyError: pass else: self.msgout(3, "import_module ->", m) return m if self.badmodules.has_key(fqname): self.msgout(3, "import_module -> None") return None try: fp, pathname, stuff = self.find_module(partname, parent and parent.__path__) except ImportError: self.msgout(3, "import_module ->", None) return None try: m = self.load_module(fqname, fp, pathname, stuff) finally: if fp: fp.close() if parent: setattr(parent, partname, m) self.msgout(3, "import_module ->", m) return m
6,847
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode pass else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 fromlist = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode pass else: fromlist = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
6,848
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode pass else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == LOAD_CONST: fromlist = co.co_consts[oparg] elif op == IMPORT_NAME: assert fromlist is None or type(fromlist) is tuple name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode pass else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
6,849
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode pass else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] have_star = 0 if fromlist is not None: if "*" in fromlist: have_star = 1 fromlist = [f for f in fromlist if f != "*"] self._safe_import_hook(name, m, fromlist) if have_star: mm = None if m.__path__: mm = self.modules.get(m.__name__ + "." + name) if mm is None: mm = self.modules.get(name) if mm is not None: m.globalnames.update(mm.globalnames) m.starimports.update(mm.starimports) if mm.__code__ is None: m.starimports[name] = 1 else: m.starimports[name] = 1 elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode pass else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
6,850
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode pass else: lastname = None for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
def scan_code(self, co, m): code = co.co_code n = len(code) i = 0 lastname = None while i < n: c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 if op == IMPORT_NAME: name = lastname = co.co_names[oparg] if not self.badmodules.has_key(lastname): try: self.import_hook(name, m) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) if not self.badmodules.has_key(name): self.badmodules[name] = {} self.badmodules[name][m.__name__] = None elif op == IMPORT_FROM: name = co.co_names[oparg] assert lastname is not None if not self.badmodules.has_key(lastname): try: self.import_hook(lastname, m, [name]) except ImportError, msg: self.msg(2, "ImportError:", str(msg)) fullname = lastname + "." + name if not self.badmodules.has_key(fullname): self.badmodules[fullname] = {} self.badmodules[fullname][m.__name__] = None elif op in STORE_OPS: # Skip; each IMPORT_FROM is followed by a STORE_* opcode name = co.co_names[oparg] m.globalnames[name] = 1 for c in co.co_consts: if isinstance(c, type(co)): self.scan_code(c, m)
6,851
def report(self): print print " %-25s %s" % ("Name", "File") print " %-25s %s" % ("----", "----") # Print modules found keys = self.modules.keys() keys.sort() for key in keys: m = self.modules[key] if m.__path__: print "P", else: print "m", print "%-25s" % key, m.__file__ or ""
def report(self): print print " %-25s %s" % ("Name", "File") print " %-25s %s" % ("----", "----") # Print modules found keys = self.modules.keys() keys.sort() for key in keys: m = self.modules[key] if m.__path__: print "P", else: print "m", print "%-25s" % key, m.__file__ or ""
6,852
def report(self): print print " %-25s %s" % ("Name", "File") print " %-25s %s" % ("----", "----") # Print modules found keys = self.modules.keys() keys.sort() for key in keys: m = self.modules[key] if m.__path__: print "P", else: print "m", print "%-25s" % key, m.__file__ or ""
def report(self): print print " %-25s %s" % ("Name", "File") print " %-25s %s" % ("----", "----") # Print modules found keys = self.modules.keys() keys.sort() for key in keys: m = self.modules[key] if m.__path__: print "P", else: print "m", print "%-25s" % key, m.__file__ or ""
6,853
def any_missing(self): keys = self.badmodules.keys() missing = [] for key in keys: if key not in self.excludes: # Missing, and its not supposed to be missing.append(key) return missing
def any_missing(self): """Return a list of modules that appear to be missing. Use any_missing_maybe() if you want to know which modules are certain to be missing, and which *may* be missing. """ missing, maybe = self.any_missing_maybe() return missing + maybe def any_missing_maybe(self): """Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package. The reason it can't always be determined is that it's impossible to tell which names are imported when "from module import *" is done with an extension module, short of actually importing it. """ missing = [] for key in keys: if key not in self.excludes: # Missing, and its not supposed to be missing.append(key) return missing
6,854
def any_missing(self): keys = self.badmodules.keys() missing = [] for key in keys: if key not in self.excludes: # Missing, and its not supposed to be missing.append(key) return missing
def any_missing(self): keys = self.badmodules.keys() missing = [] for key in keys: if key not in self.excludes: # Missing, and its not supposed to be missing.append(key) return missing
6,855
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f,r in self.replace_paths: if original_filename.startswith(f): new_filename = r+original_filename[len(f):] break
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f, r in self.replace_paths: if original_filename.startswith(f): new_filename = r+original_filename[len(f):] break
6,856
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f,r in self.replace_paths: if original_filename.startswith(f): new_filename = r+original_filename[len(f):] break
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f,r in self.replace_paths: if original_filename.startswith(f): new_filename = r + original_filename[len(f):] break
6,857
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f,r in self.replace_paths: if original_filename.startswith(f): new_filename = r+original_filename[len(f):] break
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f,r in self.replace_paths: if original_filename.startswith(f): new_filename = r+original_filename[len(f):] break
6,858
def test(): # Parse command line import getopt try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") except getopt.error, msg: print msg return # Process options debug = 1 domods = 0 addpath = [] exclude = [] for o, a in opts: if o == '-d': debug = debug + 1 if o == '-m': domods = 1 if o == '-p': addpath = addpath + a.split(os.pathsep) if o == '-q': debug = 0 if o == '-x': exclude.append(a) # Provide default arguments if not args: script = "hello.py" else: script = args[0] # Set the path based on sys.path and the script directory path = sys.path[:] path[0] = os.path.dirname(script) path = addpath + path if debug > 1: print "path:" for item in path: print " ", `item` # Create the module finder and turn its crank mf = ModuleFinder(path, debug, exclude) for arg in args[1:]: if arg == '-m': domods = 1 continue if domods: if arg[-2:] == '.*': mf.import_hook(arg[:-2], None, ["*"]) else: mf.import_hook(arg) else: mf.load_file(arg) mf.run_script(script) mf.report()
def test(): # Parse command line import getopt try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") except getopt.error, msg: print msg return # Process options debug = 1 domods = 0 addpath = [] exclude = [] for o, a in opts: if o == '-d': debug = debug + 1 if o == '-m': domods = 1 if o == '-p': addpath = addpath + a.split(os.pathsep) if o == '-q': debug = 0 if o == '-x': exclude.append(a) # Provide default arguments if not args: script = "hello.py" else: script = args[0] # Set the path based on sys.path and the script directory path = sys.path[:] path[0] = os.path.dirname(script) path = addpath + path if debug > 1: print "path:" for item in path: print " ", `item` # Create the module finder and turn its crank mf = ModuleFinder(path, debug, exclude) for arg in args[1:]: if arg == '-m': domods = 1 continue if domods: if arg[-2:] == '.*': mf.import_hook(arg[:-2], None, ["*"]) else: mf.import_hook(arg) else: mf.load_file(arg) mf.run_script(script) mf.report()
6,859
def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): """Process arguments and decide which source files to compile.
def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): """Process arguments and decide which source files to compile.
6,860
def _prep_compile(self, sources, output_dir, depends=None): """Decide which souce files must be recompiled.
def _prep_compile(self, sources, output_dir, depends=None): """Decide which souce files must be recompiled.
6,861
def add_ui(db): x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 add_data(db, 'ActionText', uisample.ActionText) add_data(db, 'UIText', uisample.UIText) # Bitmaps if not os.path.exists(srcdir+r"\PC\python_icon.exe"): raise "Run icons.mak in PC directory" add_data(db, "Binary", [("PythonWin", msilib.Binary(srcdir+r"\PCbuild\installer.bmp")), # 152x328 pixels ("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")), ]) add_data(db, "Icon", [("python_icon.exe", msilib.Binary(srcdir+r"\PC\python_icon.exe"))]) # Scripts # CheckDir sets TargetExists if TARGETDIR exists. # UpdateEditIDLE sets the REGISTRY.tcl component into # the installed/uninstalled state according to both the # Extensions and TclTk features. if os.system("nmake /nologo /c /f msisupport.mak") != 0: raise "'nmake /f msisupport.mak' failed" add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))]) # See "Custom Action Type 1" if msilib.Win64: CheckDir = "CheckDir" UpdateEditIDLE = "UpdateEditIDLE" else: CheckDir = "_CheckDir@4" UpdateEditIDLE = "_UpdateEditIDLE@4" add_data(db, "CustomAction", [("CheckDir", 1, "Script", CheckDir)]) if have_tcl: add_data(db, "CustomAction", [("UpdateEditIDLE", 1, "Script", UpdateEditIDLE)]) # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair")]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) compileargs = r"-Wi [TARGETDIR]Lib\compileall.py -f -x bad_coding|badsyntax|site-packages [TARGETDIR]Lib" # See "CustomAction Table" add_data(db, "CustomAction", [ # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty # See "Custom Action Type 51", # "Custom Action Execution Scheduling Options" ("InitialTargetDir", 307, "TARGETDIR", "[WindowsVolume]Python%s%s" % (major, minor)), ("SetDLLDirToTarget", 307, "DLLDIR", "[TARGETDIR]"), ("SetDLLDirToSystem32", 307, "DLLDIR", SystemFolderName), # msidbCustomActionTypeExe + msidbCustomActionTypeSourceFile # See "Custom Action Type 18" ("CompilePyc", 18, "python.exe", compileargs), ("CompilePyo", 18, "python.exe", "-O "+compileargs), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), ("InitialTargetDir", 'TARGETDIR=""', 750), # In the user interface, assume all-users installation if privileged. ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("SelectDirectoryDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, "AdminUISequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ]) # Execute Sequences add_data(db, "InstallExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("UpdateEditIDLE", None, 1050), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ]) add_data(db, "AdminExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ]) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") # See "ControlEvent Table". Parameters are the event, the parameter # to the action, and optionally the condition for the event, and the order # of events. c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Acknowledgements", 135, 95, 220, 120, 0x30003, "Special Windows thanks to:\n" " LettError, Erik van Blokland, for the \n" " Python for Windows graphic.\n" " http://www.letterror.com/\n" "\n" " Mark Hammond, without whose years of freely \n" " shared Windows expertise, Python for Windows \n" " would still be Python for DOS.") c = exit_dialog.text("warning", 135, 200, 220, 40, 0x30003, "{\\VerdanaRed9}Warning: Python 2.5.x is the last " "Python release for Windows 9x.") c.condition("Hide", "NOT Version9X") exit_dialog.text("Description", 135, 235, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") costing.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 135, 70, 220, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 135, 110, 220, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 135, 135, 220, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Target directory selection seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Destination Directory") c = seldlg.text("Existing", 135, 25, 235, 30, 0x30003, "{\VerdanaRed9}This update will replace your existing [ProductLine] installation.") c.condition("Hide", 'REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""') seldlg.text("Description", 135, 50, 220, 40, 0x30003, "Please select a directory for the [ProductName] files.") seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") c.event("DoAction", "CheckDir", "TargetExistsOk<>1", order=1) # If the target exists, but we found that we are going to remove old versions, don't bother # confirming that the target directory exists. Strictly speaking, we should determine that # the target directory is indeed the target of the product that we are going to remove, but # I don't know how to do that. c.event("SpawnDialog", "ExistingDirectoryDlg", 'TargetExists=1 and REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""', 2) c.event("SetTargetPath", "TARGETDIR", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 3) c.event("SpawnWaitDialog", "WaitForCostingDlg", "CostingComplete=1", 4) c.event("NewDialog", "SelectFeaturesDlg", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 5) c = seldlg.cancel("Cancel", "DirectoryCombo") c.event("SpawnDialog", "CancelDlg") seldlg.control("DirectoryCombo", "DirectoryCombo", 135, 70, 172, 80, 393219, "TARGETDIR", None, "DirectoryList", None) seldlg.control("DirectoryList", "DirectoryList", 135, 90, 208, 136, 3, "TARGETDIR", None, "PathEdit", None) seldlg.control("PathEdit", "PathEdit", 135, 230, 206, 16, 3, "TARGETDIR", None, "Next", None) c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) c.event("DirectoryListUp", "0") c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) c.event("DirectoryListNew", "0") ##################################################################### # SelectFeaturesDlg features = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal|track_disk_space, title, "Tree", "Next", "Cancel") features.title("Customize [ProductName]") features.text("Description", 135, 35, 220, 15, 0x30003, "Select the way you want features to be installed.") features.text("Text", 135,45,220,30, 3, "Click on the icons in the tree below to change the way features will be installed.") c=features.back("< Back", "Next") c.event("NewDialog", "SelectDirectoryDlg") c=features.next("Next >", "Cancel") c.mapping("SelectionNoItems", "Enabled") c.event("SpawnDialog", "DiskCostDlg", "OutOfDiskSpace=1", order=1) c.event("EndDialog", "Return", "OutOfDiskSpace<>1", order=2) c=features.cancel("Cancel", "Tree") c.event("SpawnDialog", "CancelDlg") # The browse property is not used, since we have only a single target path (selected already) features.control("Tree", "SelectionTree", 135, 75, 220, 95, 7, "_BrowseProperty", "Tree of selections", "Back", None) #c=features.pushbutton("Reset", 42, 243, 56, 17, 3, "Reset", "DiskCost") #c.mapping("SelectionNoItems", "Enabled") #c.event("Reset", "0") features.control("Box", "GroupBox", 135, 170, 225, 90, 1, None, None, None, None) c=features.xbutton("DiskCost", "Disk &Usage", None, 0.10) c.mapping("SelectionNoItems","Enabled") c.event("SpawnDialog", "DiskCostDlg") c=features.xbutton("Advanced", "Advanced", None, 0.30) c.event("SpawnDialog", "AdvancedDlg") c=features.text("ItemDescription", 140, 180, 210, 30, 3, "Multiline description of the currently selected item.") c.mapping("SelectionDescription","Text") c=features.text("ItemSize", 140, 210, 210, 45, 3, "The size of the currently selected item.") c.mapping("SelectionSize", "Text") ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 135, 60, 160, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", order = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Advanced Dialog. advanced = PyDialog(db, "AdvancedDlg", x, y, w, h, modal, title, "CompilePyc", "Next", "Cancel") advanced.title("Advanced Options for [ProductName]") # A radio group with two options: allusers, justme advanced.checkbox("CompilePyc", 135, 60, 230, 50, 3, "COMPILEALL", "Compile .py files to byte code after installation", "Next") c = advanced.next("Finish", "Cancel") c.event("EndDialog", "Return") c = advanced.cancel("Cancel", "CompilePyc") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Existing Directory dialog dlg = Dialog(db, "ExistingDirectoryDlg", 50, 30, 200, 80, modal, title, "No", "No", "No") dlg.text("Title", 10, 20, 180, 40, 3, "[TARGETDIR] exists. Are you sure you want to overwrite existing files?") c=dlg.pushbutton("Yes", 30, 60, 55, 17, 3, "Yes", "No") c.event("[TargetExists]", "0", order=1) c.event("[TargetExistsOk]", "1", order=2) c.event("EndDialog", "Return", order=3) c=dlg.pushbutton("No", 115, 60, 55, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 135, 63, 230, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 135, 108, 230, 60, 3, "MaintenanceForm_Action", "", "Next") g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg")
def add_ui(db): x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 add_data(db, 'ActionText', uisample.ActionText) add_data(db, 'UIText', uisample.UIText) # Bitmaps if not os.path.exists(srcdir+r"\PC\python_icon.exe"): raise "Run icons.mak in PC directory" add_data(db, "Binary", [("PythonWin", msilib.Binary(srcdir+r"\PCbuild\installer.bmp")), # 152x328 pixels ("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")), ]) add_data(db, "Icon", [("python_icon.exe", msilib.Binary(srcdir+r"\PC\python_icon.exe"))]) # Scripts # CheckDir sets TargetExists if TARGETDIR exists. # UpdateEditIDLE sets the REGISTRY.tcl component into # the installed/uninstalled state according to both the # Extensions and TclTk features. if os.system("nmake /nologo /c /f msisupport.mak") != 0: raise "'nmake /f msisupport.mak' failed" add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))]) # See "Custom Action Type 1" if msilib.Win64: CheckDir = "CheckDir" UpdateEditIDLE = "UpdateEditIDLE" else: CheckDir = "_CheckDir@4" UpdateEditIDLE = "_UpdateEditIDLE@4" add_data(db, "CustomAction", [("CheckDir", 1, "Script", CheckDir)]) if have_tcl: add_data(db, "CustomAction", [("UpdateEditIDLE", 1, "Script", UpdateEditIDLE)]) # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair")]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) compileargs = r"-Wi [TARGETDIR]Lib\compileall.py -f -x bad_coding|badsyntax|site-packages [TARGETDIR]Lib" # See "CustomAction Table" add_data(db, "CustomAction", [ # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty # See "Custom Action Type 51", # "Custom Action Execution Scheduling Options" ("InitialTargetDir", 307, "TARGETDIR", "[WindowsVolume]Python%s%s" % (major, minor)), ("SetDLLDirToTarget", 307, "DLLDIR", "[TARGETDIR]"), ("SetDLLDirToSystem32", 307, "DLLDIR", SystemFolderName), # msidbCustomActionTypeExe + msidbCustomActionTypeSourceFile # See "Custom Action Type 18" ("CompilePyc", 18, "python.exe", compileargs), ("CompilePyo", 18, "python.exe", "-O "+compileargs), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), ("InitialTargetDir", 'TARGETDIR=""', 750), # In the user interface, assume all-users installation if privileged. ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("SelectDirectoryDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, "AdminUISequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ]) # Execute Sequences add_data(db, "InstallExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751), ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752), ("UpdateEditIDLE", None, 1050), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ]) add_data(db, "AdminExecuteSequence", [("InitialTargetDir", 'TARGETDIR=""', 750), ("SetDLLDirToTarget", 'DLLDIR=""', 751), ("CompilePyc", "COMPILEALL", 6800), ("CompilePyo", "COMPILEALL", 6801), ]) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") # See "ControlEvent Table". Parameters are the event, the parameter # to the action, and optionally the condition for the event, and the order # of events. c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 135, 70, 220, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 135, 155, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Acknowledgements", 135, 95, 220, 120, 0x30003, "Special Windows thanks to:\n" " Mark Hammond, without whose years of freely \n" " shared Windows expertise, Python for Windows \n" " would still be Python for DOS.") c = exit_dialog.text("warning", 135, 200, 220, 40, 0x30003, "{\\VerdanaRed9}Warning: Python 2.5.x is the last " "Python release for Windows 9x.") c.condition("Hide", "NOT Version9X") exit_dialog.text("Description", 135, 235, 220, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") costing.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, "py.ico", None, None) c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 135, 70, 220, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 135, 110, 220, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 135, 135, 220, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Target directory selection seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Destination Directory") c = seldlg.text("Existing", 135, 25, 235, 30, 0x30003, "{\VerdanaRed9}This update will replace your existing [ProductLine] installation.") c.condition("Hide", 'REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""') seldlg.text("Description", 135, 50, 220, 40, 0x30003, "Please select a directory for the [ProductName] files.") seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") c.event("DoAction", "CheckDir", "TargetExistsOk<>1", order=1) # If the target exists, but we found that we are going to remove old versions, don't bother # confirming that the target directory exists. Strictly speaking, we should determine that # the target directory is indeed the target of the product that we are going to remove, but # I don't know how to do that. c.event("SpawnDialog", "ExistingDirectoryDlg", 'TargetExists=1 and REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""', 2) c.event("SetTargetPath", "TARGETDIR", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 3) c.event("SpawnWaitDialog", "WaitForCostingDlg", "CostingComplete=1", 4) c.event("NewDialog", "SelectFeaturesDlg", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 5) c = seldlg.cancel("Cancel", "DirectoryCombo") c.event("SpawnDialog", "CancelDlg") seldlg.control("DirectoryCombo", "DirectoryCombo", 135, 70, 172, 80, 393219, "TARGETDIR", None, "DirectoryList", None) seldlg.control("DirectoryList", "DirectoryList", 135, 90, 208, 136, 3, "TARGETDIR", None, "PathEdit", None) seldlg.control("PathEdit", "PathEdit", 135, 230, 206, 16, 3, "TARGETDIR", None, "Next", None) c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) c.event("DirectoryListUp", "0") c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) c.event("DirectoryListNew", "0") ##################################################################### # SelectFeaturesDlg features = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal|track_disk_space, title, "Tree", "Next", "Cancel") features.title("Customize [ProductName]") features.text("Description", 135, 35, 220, 15, 0x30003, "Select the way you want features to be installed.") features.text("Text", 135,45,220,30, 3, "Click on the icons in the tree below to change the way features will be installed.") c=features.back("< Back", "Next") c.event("NewDialog", "SelectDirectoryDlg") c=features.next("Next >", "Cancel") c.mapping("SelectionNoItems", "Enabled") c.event("SpawnDialog", "DiskCostDlg", "OutOfDiskSpace=1", order=1) c.event("EndDialog", "Return", "OutOfDiskSpace<>1", order=2) c=features.cancel("Cancel", "Tree") c.event("SpawnDialog", "CancelDlg") # The browse property is not used, since we have only a single target path (selected already) features.control("Tree", "SelectionTree", 135, 75, 220, 95, 7, "_BrowseProperty", "Tree of selections", "Back", None) #c=features.pushbutton("Reset", 42, 243, 56, 17, 3, "Reset", "DiskCost") #c.mapping("SelectionNoItems", "Enabled") #c.event("Reset", "0") features.control("Box", "GroupBox", 135, 170, 225, 90, 1, None, None, None, None) c=features.xbutton("DiskCost", "Disk &Usage", None, 0.10) c.mapping("SelectionNoItems","Enabled") c.event("SpawnDialog", "DiskCostDlg") c=features.xbutton("Advanced", "Advanced", None, 0.30) c.event("SpawnDialog", "AdvancedDlg") c=features.text("ItemDescription", 140, 180, 210, 30, 3, "Multiline description of the currently selected item.") c.mapping("SelectionDescription","Text") c=features.text("ItemSize", 140, 210, 210, 45, 3, "The size of the currently selected item.") c.mapping("SelectionSize", "Text") ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 135, 60, 160, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", order = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Advanced Dialog. advanced = PyDialog(db, "AdvancedDlg", x, y, w, h, modal, title, "CompilePyc", "Next", "Cancel") advanced.title("Advanced Options for [ProductName]") # A radio group with two options: allusers, justme advanced.checkbox("CompilePyc", 135, 60, 230, 50, 3, "COMPILEALL", "Compile .py files to byte code after installation", "Next") c = advanced.next("Finish", "Cancel") c.event("EndDialog", "Return") c = advanced.cancel("Cancel", "CompilePyc") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Existing Directory dialog dlg = Dialog(db, "ExistingDirectoryDlg", 50, 30, 200, 80, modal, title, "No", "No", "No") dlg.text("Title", 10, 20, 180, 40, 3, "[TARGETDIR] exists. Are you sure you want to overwrite existing files?") c=dlg.pushbutton("Yes", 30, 60, 55, 17, 3, "Yes", "No") c.event("[TargetExists]", "0", order=1) c.event("[TargetExistsOk]", "1", order=2) c.event("EndDialog", "Return", order=3) c=dlg.pushbutton("No", 115, 60, 55, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 135, 63, 230, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 135, 108, 230, 60, 3, "MaintenanceForm_Action", "", "Next") g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg")
6,862
def main(): global root, tk, top, mid, bot global folderbox, foldermenu, scanbox, scanmenu, viewer global folder, seq global mh, mhf # Parse command line options folder = 'inbox' seq = 'all' try: opts, args = getopt.getopt(sys.argv[1:], '') except getopt.error, msg: print msg sys.exit(2) for arg in args: if arg[:1] == '+': folder = arg[1:] else: seq = arg # Initialize MH mh = mhlib.MH() mhf = mh.openfolder(folder) # Build widget hierarchy root = Tk() tk = root.tk top = Frame(root) top.pack({'expand': 1, 'fill': 'both'}) # Build right part: folder list right = Frame(top) right.pack({'fill': 'y', 'side': 'right'}) folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2}) folderbar.pack({'fill': 'y', 'side': 'right'}) folderbox = Listbox(right) folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) foldermenu = Menu(root) foldermenu.add('command', {'label': 'Open Folder', 'command': open_folder}) foldermenu.add('separator') foldermenu.add('command', {'label': 'Quit', 'command': 'exit'}) foldermenu.bind('<ButtonRelease-3>', folder_unpost) folderbox['yscrollcommand'] = (folderbar, 'set') folderbar['command'] = (folderbox, 'yview') folderbox.bind('<Double-1>', open_folder, 1) folderbox.bind('<3>', folder_post) # Build left part: scan list left = Frame(top) left.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2}) scanbar.pack({'fill': 'y', 'side': 'right'}) scanbox = Listbox(left, {'font': 'fixed'}) scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) scanmenu = Menu(root) scanmenu.add('command', {'label': 'Open Message', 'command': open_message}) scanmenu.add('command', {'label': 'Remove Message', 'command': remove_message}) scanmenu.add('command', {'label': 'Refile Message', 'command': refile_message}) scanmenu.add('separator') scanmenu.add('command', {'label': 'Quit', 'command': 'exit'}) scanmenu.bind('<ButtonRelease-3>', scan_unpost) scanbox['yscrollcommand'] = (scanbar, 'set') scanbar['command'] = (scanbox, 'yview') scanbox.bind('<Double-1>', open_message) scanbox.bind('<3>', scan_post) # Separator between middle and bottom part rule2 = Frame(root, {'bg': 'black'}) rule2.pack({'fill': 'x'}) # Build bottom part: current message bot = Frame(root) bot.pack({'expand': 1, 'fill': 'both'}) # viewer = None # Window manager commands root.minsize(800, 1) # Make window resizable # Fill folderbox with text setfolders() # Fill scanbox with text rescan() # Enter mainloop root.mainloop()
def main(): global root, tk, top, mid, bot global folderbox, foldermenu, scanbox, scanmenu, viewer global folder, seq global mh, mhf # Parse command line options folder = 'inbox' seq = 'all' try: opts, args = getopt.getopt(sys.argv[1:], '') except getopt.error, msg: print msg sys.exit(2) for arg in args: if arg[:1] == '+': folder = arg[1:] else: seq = arg # Initialize MH mh = mhlib.MH() mhf = mh.openfolder(folder) # Build widget hierarchy root = Tk() tk = root.tk top = Frame(root) top.pack({'expand': 1, 'fill': 'both'}) # Build right part: folder list right = Frame(top) right.pack({'fill': 'y', 'side': 'right'}) folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2}) folderbar.pack({'fill': 'y', 'side': 'right'}) folderbox = Listbox(right, {'exportselection': 0}) folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) foldermenu = Menu(root) foldermenu.add('command', {'label': 'Open Folder', 'command': open_folder}) foldermenu.add('separator') foldermenu.add('command', {'label': 'Quit', 'command': 'exit'}) foldermenu.bind('<ButtonRelease-3>', folder_unpost) folderbox['yscrollcommand'] = (folderbar, 'set') folderbar['command'] = (folderbox, 'yview') folderbox.bind('<Double-1>', open_folder, 1) folderbox.bind('<3>', folder_post) # Build left part: scan list left = Frame(top) left.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2}) scanbar.pack({'fill': 'y', 'side': 'right'}) scanbox = Listbox(left, {'font': 'fixed'}) scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) scanmenu = Menu(root) scanmenu.add('command', {'label': 'Open Message', 'command': open_message}) scanmenu.add('command', {'label': 'Remove Message', 'command': remove_message}) scanmenu.add('command', {'label': 'Refile Message', 'command': refile_message}) scanmenu.add('separator') scanmenu.add('command', {'label': 'Quit', 'command': 'exit'}) scanmenu.bind('<ButtonRelease-3>', scan_unpost) scanbox['yscrollcommand'] = (scanbar, 'set') scanbar['command'] = (scanbox, 'yview') scanbox.bind('<Double-1>', open_message) scanbox.bind('<3>', scan_post) # Separator between middle and bottom part rule2 = Frame(root, {'bg': 'black'}) rule2.pack({'fill': 'x'}) # Build bottom part: current message bot = Frame(root) bot.pack({'expand': 1, 'fill': 'both'}) # viewer = None # Window manager commands root.minsize(800, 1) # Make window resizable # Fill folderbox with text setfolders() # Fill scanbox with text rescan() # Enter mainloop root.mainloop()
6,863
def open_folder(*e): global folder, mhf sel = folderbox.curselection() if len(sel) != 1: if len(sel) > 1: msg = "Please open one folder at a time" else: msg = "Please select a folder to open" dialog(root, "Can't Open Folder", msg, "", 0, "OK") return i = sel[0] folder = folderbox.get(i) mhf = mh.openfolder(folder) rescan()
def open_folder(e=None): global folder, mhf sel = folderbox.curselection() if len(sel) != 1: if len(sel) > 1: msg = "Please open one folder at a time" else: msg = "Please select a folder to open" dialog(root, "Can't Open Folder", msg, "", 0, "OK") return i = sel[0] folder = folderbox.get(i) mhf = mh.openfolder(folder) rescan()
6,864
def open_message(*e): global viewer sel = scanbox.curselection() if len(sel) != 1: if len(sel) > 1: msg = "Please open one message at a time" else: msg = "Please select a message to open" dialog(root, "Can't Open Message", msg, "", 0, "OK") return cursor = scanbox['cursor'] scanbox['cursor'] = 'watch' tk.call('update', 'idletasks') i = sel[0] line = scanbox.get(i) if scanparser.match(line) >= 0: num = string.atoi(scanparser.group(1)) m = mhf.openmessage(num) if viewer: viewer.destroy() from MimeViewer import MimeViewer viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m) viewer.pack() viewer.show() scanbox['cursor'] = cursor
def open_message(e=None): global viewer sel = scanbox.curselection() if len(sel) != 1: if len(sel) > 1: msg = "Please open one message at a time" else: msg = "Please select a message to open" dialog(root, "Can't Open Message", msg, "", 0, "OK") return cursor = scanbox['cursor'] scanbox['cursor'] = 'watch' tk.call('update', 'idletasks') i = sel[0] line = scanbox.get(i) if scanparser.match(line) >= 0: num = string.atoi(scanparser.group(1)) m = mhf.openmessage(num) if viewer: viewer.destroy() from MimeViewer import MimeViewer viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m) viewer.pack() viewer.show() scanbox['cursor'] = cursor
6,865
def remove_message(): itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Remove", "Please select a message to remove", "", 0, "OK") return todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) mhf.removemessages(todo) rescan() fixfocus(min(todo), itop)
def remove_message(e=None): itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Remove", "Please select a message to remove", "", 0, "OK") return todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) mhf.removemessages(todo) rescan() fixfocus(min(todo), itop)
6,866
def refile_message(): global lastrefile, tofolder itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Refile", "Please select a message to refile", "", 0, "OK") return foldersel = folderbox.curselection() if len(foldersel) != 1: if not foldersel: msg = "Please select a folder to refile to" else: msg = "Please select exactly one folder to refile to" dialog(root, "No Folder To Refile", msg, "", 0, "OK") return refileto = folderbox.get(foldersel[0]) todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) print 'refile', todo, tofolder if lastrefile != refileto or not tofolder: print 'new folder' lastrefile = refileto tofolder = None tofolder = mh.openfolder(lastrefile) mhf.refilemessages(todo, tofolder) rescan() fixfocus(min(todo), itop)
def refile_message(e=None): global lastrefile, tofolder itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Refile", "Please select a message to refile", "", 0, "OK") return foldersel = folderbox.curselection() if len(foldersel) != 1: if not foldersel: msg = "Please select a folder to refile to" else: msg = "Please select exactly one folder to refile to" dialog(root, "No Folder To Refile", msg, "", 0, "OK") return refileto = folderbox.get(foldersel[0]) todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) print 'refile', todo, tofolder if lastrefile != refileto or not tofolder: print 'new folder' lastrefile = refileto tofolder = None tofolder = mh.openfolder(lastrefile) mhf.refilemessages(todo, tofolder) rescan() fixfocus(min(todo), itop)
6,867
def refile_message(): global lastrefile, tofolder itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Refile", "Please select a message to refile", "", 0, "OK") return foldersel = folderbox.curselection() if len(foldersel) != 1: if not foldersel: msg = "Please select a folder to refile to" else: msg = "Please select exactly one folder to refile to" dialog(root, "No Folder To Refile", msg, "", 0, "OK") return refileto = folderbox.get(foldersel[0]) todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) print 'refile', todo, tofolder if lastrefile != refileto or not tofolder: print 'new folder' lastrefile = refileto tofolder = None tofolder = mh.openfolder(lastrefile) mhf.refilemessages(todo, tofolder) rescan() fixfocus(min(todo), itop)
def refile_message(): global lastrefile, tofolder itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Refile", "Please select a message to refile", "", 0, "OK") return foldersel = folderbox.curselection() if len(foldersel) != 1: if not foldersel: msg = "Please select a folder to refile to" else: msg = "Please select exactly one folder to refile to" dialog(root, "No Folder To Refile", msg, "", 0, "OK") return refileto = folderbox.get(foldersel[0]) todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) if lastrefile != refileto or not tofolder: print 'new folder' lastrefile = refileto tofolder = None tofolder = mh.openfolder(lastrefile) mhf.refilemessages(todo, tofolder) rescan() fixfocus(min(todo), itop)
6,868
def refile_message(): global lastrefile, tofolder itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Refile", "Please select a message to refile", "", 0, "OK") return foldersel = folderbox.curselection() if len(foldersel) != 1: if not foldersel: msg = "Please select a folder to refile to" else: msg = "Please select exactly one folder to refile to" dialog(root, "No Folder To Refile", msg, "", 0, "OK") return refileto = folderbox.get(foldersel[0]) todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) print 'refile', todo, tofolder if lastrefile != refileto or not tofolder: print 'new folder' lastrefile = refileto tofolder = None tofolder = mh.openfolder(lastrefile) mhf.refilemessages(todo, tofolder) rescan() fixfocus(min(todo), itop)
def refile_message(): global lastrefile, tofolder itop = scanbox.nearest(0) sel = scanbox.curselection() if not sel: dialog(root, "No Message To Refile", "Please select a message to refile", "", 0, "OK") return foldersel = folderbox.curselection() if len(foldersel) != 1: if not foldersel: msg = "Please select a folder to refile to" else: msg = "Please select exactly one folder to refile to" dialog(root, "No Folder To Refile", msg, "", 0, "OK") return refileto = folderbox.get(foldersel[0]) todo = [] for i in sel: line = scanbox.get(i) if scanparser.match(line) >= 0: todo.append(string.atoi(scanparser.group(1))) print 'refile', todo, tofolder if lastrefile != refileto or not tofolder: lastrefile = refileto tofolder = None tofolder = mh.openfolder(lastrefile) mhf.refilemessages(todo, tofolder) rescan() fixfocus(min(todo), itop)
6,869
def fixfocus(near, itop): n = scanbox.size() for i in range(n): line = scanbox.get(`i`) if scanparser.match(line) >= 0: num = string.atoi(scanparser.group(1)) if num >= near: break else: i = 'end' scanbox.select_from(i) print 'yview', `itop` scanbox.yview(itop)
def fixfocus(near, itop): n = scanbox.size() for i in range(n): line = scanbox.get(`i`) if scanparser.match(line) >= 0: num = string.atoi(scanparser.group(1)) if num >= near: break else: i = 'end' scanbox.select_from(i) scanbox.yview(itop)
6,870
def test_alias_nofallback(self): try: winsound.PlaySound( '!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT ) except RuntimeError: pass
def test_alias_nofallback(self): try: winsound.PlaySound( '!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT ) except RuntimeError: pass
6,871
def makedirs(name, mode=0777): """makedirs(path [, mode=0777]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. """ head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): makedirs(head, mode) if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists return mkdir(name, mode)
def makedirs(name, mode=0777): """makedirs(path [, mode=0777]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. """ head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs(head, mode) except OSError, e: if e.errno != EEXIST: raise if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists return mkdir(name, mode)
6,872
def _execvpe(file, args, env=None): from errno import ENOENT, ENOTDIR if env is not None: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ head, tail = path.split(file) if head: func(file, *argrest) return if 'PATH' in env: envpath = env['PATH'] else: envpath = defpath PATH = envpath.split(pathsep) saved_exc = None saved_tb = None for dir in PATH: fullname = path.join(dir, file) try: func(fullname, *argrest) except error, e: tb = sys.exc_info()[2] if (e.errno != ENOENT and e.errno != ENOTDIR and saved_exc is None): saved_exc = e saved_tb = tb if saved_exc: raise error, saved_exc, saved_tb raise error, e, tb
def _execvpe(file, args, env=None): if env is not None: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ head, tail = path.split(file) if head: func(file, *argrest) return if 'PATH' in env: envpath = env['PATH'] else: envpath = defpath PATH = envpath.split(pathsep) saved_exc = None saved_tb = None for dir in PATH: fullname = path.join(dir, file) try: func(fullname, *argrest) except error, e: tb = sys.exc_info()[2] if (e.errno != ENOENT and e.errno != ENOTDIR and saved_exc is None): saved_exc = e saved_tb = tb if saved_exc: raise error, saved_exc, saved_tb raise error, e, tb
6,873
def gettempdir(): global tempdir if tempdir is not None: return tempdir attempdirs = ['/usr/tmp', '/tmp', os.getcwd(), os.curdir] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 0) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir
def gettempdir(): global tempdir if tempdir is not None: return tempdir attempdirs = ['/usr/tmp', '/tmp', os.getcwd(), os.curdir] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 0) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir
6,874
def mktemp(): global counter dir = gettempdir() pre = gettempprefix() while 1: counter = counter + 1 file = os.path.join(dir, pre + `counter`) if not os.path.exists(file): return file
def mktemp(suffix=""): global counter dir = gettempdir() pre = gettempprefix() while 1: counter = counter + 1 file = os.path.join(dir, pre + `counter`) if not os.path.exists(file): return file
6,875
def mktemp(): global counter dir = gettempdir() pre = gettempprefix() while 1: counter = counter + 1 file = os.path.join(dir, pre + `counter`) if not os.path.exists(file): return file
def mktemp(): global counter dir = gettempdir() pre = gettempprefix() while 1: counter = counter + 1 file = os.path.join(dir, pre + `counter` + suffix) if not os.path.exists(file): return file
6,876
def __init__(self, file, path):
def __init__(self, file, path):
6,877
def __getattr__(self, name):
def __getattr__(self, name):
6,878
def __init__(self, name, level, pathname, lineno, msg, args, exc_info): """ Initialize a logging record with interesting information. """ ct = time.time() self.name = name self.msg = msg # # The following statement allows passing of a dictionary as a sole # argument, so that you can do something like # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) # Suggested by Stefan Behnel. # Note that without the test for args[0], we get a problem because # during formatting, we test to see if the arg is present using # 'if self.args:'. If the event being logged is e.g. 'Value is %d' # and if the passed arg fails 'if self.args:' then no formatting # is done. For example, logger.warn('Value is %d', 0) would log # 'Value is %d' instead of 'Value is 0'. # For the use case of passing a dictionary, this should not be a # problem. if args and (len(args) == 1) and args[0]: args = args[0] self.args = args self.levelname = getLevelName(level) self.levelno = level self.pathname = pathname try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] except: self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info self.exc_text = None # used to cache the traceback text self.lineno = lineno self.created = ct self.msecs = (ct - long(ct)) * 1000 self.relativeCreated = (self.created - _startTime) * 1000 if thread: self.thread = thread.get_ident() else: self.thread = None if hasattr(os, 'getpid'): self.process = os.getpid() else: self.process = None
def __init__(self, name, level, pathname, lineno, msg, args, exc_info): """ Initialize a logging record with interesting information. """ ct = time.time() self.name = name self.msg = msg # # The following statement allows passing of a dictionary as a sole # argument, so that you can do something like # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) # Suggested by Stefan Behnel. # Note that without the test for args[0], we get a problem because # during formatting, we test to see if the arg is present using # 'if self.args:'. If the event being logged is e.g. 'Value is %d' # and if the passed arg fails 'if self.args:' then no formatting # is done. For example, logger.warn('Value is %d', 0) would log # 'Value is %d' instead of 'Value is 0'. # For the use case of passing a dictionary, this should not be a # problem. if args and (len(args) == 1) and args[0] and (type(args[0]) == types.DictType): args = args[0] self.args = args self.levelname = getLevelName(level) self.levelno = level self.pathname = pathname try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] except: self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info self.exc_text = None # used to cache the traceback text self.lineno = lineno self.created = ct self.msecs = (ct - long(ct)) * 1000 self.relativeCreated = (self.created - _startTime) * 1000 if thread: self.thread = thread.get_ident() else: self.thread = None if hasattr(os, 'getpid'): self.process = os.getpid() else: self.process = None
6,879
def play_sound_file(path): fp = open(path, 'r') data = fp.read() fp.close() try: a = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV): raise TestSkipped, msg raise TestFailed, msg else: a.write(data) a.close()
def play_sound_file(path): fp = open(path, 'r') data = fp.read() fp.close() try: a = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV): raise TestSkipped, msg raise TestFailed, msg a.bufsize() a.obufcount() a.obuffree() a.getptr() a.fileno() a.setparameters(rate, 8, nchannels, linuxaudiodev.AFMT_MU_LAW, 1) a.write(data) a.flush() a.close() def test_errors(): a = linuxaudiodev.open("w") size = 8 fmt = linuxaudiodev.AFMT_U8 rate = 8000 nchannels = 1 try: a.setparameters(-1, size, nchannels, fmt) except ValueError, msg: print msg try: a.setparameters(rate, -2, nchannels, fmt) except ValueError, msg: print msg try: a.setparameters(rate, size, 3, fmt) except ValueError, msg: print msg try: a.setparameters(rate, size, nchannels, 177) except ValueError, msg: print msg try: a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE) except ValueError, msg: print msg try: a.setparameters(rate, 16, nchannels, fmt) except ValueError, msg: print msg
6,880
def main(): # Find the template # (there's no point in proceeding if we can't find it) for p in sys.path: template = os.path.join(p, TEMPLATE) try: template, d1, d2 = macfs.ResolveAliasFile(template) break except (macfs.error, ValueError): continue else: die("Template %s not found on sys.path" % `TEMPLATE`) return template = template.as_pathname() print 'Using template', template # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select Python source file:', 'TEXT') if not ok: return filename = srcfss.as_pathname() tp, tf = os.path.split(filename) if tf[-3:] == '.py': tf = tf[:-3] else: tf = tf + '.applet' dstfss, ok = macfs.StandardPutFile('Save application as:', tf) if not ok: return process(template, filename, dstfss.as_pathname()) else: # Loop over all files to be processed for filename in sys.argv[1:]: process(template, filename, '')
def main(): # Find the template # (there's no point in proceeding if we can't find it) for p in sys.path: template = os.path.join(p, TEMPLATE) try: template, d1, d2 = macfs.ResolveAliasFile(template) break except (macfs.error, ValueError): continue else: die("Template %s not found on sys.path" % `TEMPLATE`) return template = template.as_pathname() print 'Using template', template # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select Python source file:', 'TEXT') if not ok: return filename = srcfss.as_pathname() tp, tf = os.path.split(filename) if tf[-3:] == '.py': tf = tf[:-3] else: tf = tf + '.applet' dstfss, ok = macfs.StandardPutFile('Save application as:', tf) if not ok: return process(template, filename, dstfss.as_pathname()) else: # Loop over all files to be processed for filename in sys.argv[1:]: process(template, filename, '')
6,881
def process(template, filename, output): print "Processing", `filename`, "..." # Read the source and compile it # (there's no point overwriting the destination if it has a syntax error) fp = open(filename) text = fp.read() fp.close() try: code = compile(text, filename, "exec") except (SyntaxError, EOFError): die("Syntax error in script %s" % `filename`) return # Set the destination file name if string.lower(filename[-3:]) == ".py": destname = filename[:-3] rsrcname = destname + '.rsrc' else: destname = filename + ".applet" rsrcname = filename + '.rsrc' if output: destname = output # Copy the data from the template (creating the file as well) template_fss = macfs.FSSpec(template) template_fss, d1, d2 = macfs.ResolveAliasFile(template_fss) dest_fss = macfs.FSSpec(destname) tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() # Copy the creator of the template to the destination # unless it already got one. Set type to APPL tctor, ttype = template_fss.GetCreatorType() ctor, type = dest_fss.GetCreatorType() if type in undefs: type = 'APPL' if ctor in undefs: ctor = tctor # Open the output resource fork try: output = FSpOpenResFile(dest_fss, WRITE) except MacOS.Error: print "Creating resource fork..." CreateResFile(destname) output = FSpOpenResFile(dest_fss, WRITE) # Copy the resources from the template input = FSpOpenResFile(template_fss, READ) newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Copy the resources from the target specific resource template, if any try: input = FSpOpenResFile(rsrcname, READ) except MacOS.Error: pass else: newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Now set the creator, type and bundle bit of the destination dest_finfo = dest_fss.GetFInfo() dest_finfo.Creator = ctor dest_finfo.Type = type dest_finfo.Flags = dest_finfo.Flags | MACFS.kHasBundle dest_finfo.Flags = dest_finfo.Flags & ~MACFS.kHasBeenInited dest_fss.SetFInfo(dest_finfo) # Make sure we're manipulating the output resource file now UseResFile(output) # Delete any existing 'PYC 'resource named __main__ try: res = Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Error: pass # Create the raw data for the resource from the code object data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Unique1ID(RESTYPE) res = Resource(data) res.AddResource(RESTYPE, id, RESNAME) res.WriteResource() res.ReleaseResource() # Close the output file CloseResFile(output) # Give positive feedback message("Applet %s created." % `destname`)
def process(template, filename, output): if DEBUG: print "Processing", `filename`, "..." # Read the source and compile it # (there's no point overwriting the destination if it has a syntax error) fp = open(filename) text = fp.read() fp.close() try: code = compile(text, filename, "exec") except (SyntaxError, EOFError): die("Syntax error in script %s" % `filename`) return # Set the destination file name if string.lower(filename[-3:]) == ".py": destname = filename[:-3] rsrcname = destname + '.rsrc' else: destname = filename + ".applet" rsrcname = filename + '.rsrc' if output: destname = output # Copy the data from the template (creating the file as well) template_fss = macfs.FSSpec(template) template_fss, d1, d2 = macfs.ResolveAliasFile(template_fss) dest_fss = macfs.FSSpec(destname) tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() # Copy the creator of the template to the destination # unless it already got one. Set type to APPL tctor, ttype = template_fss.GetCreatorType() ctor, type = dest_fss.GetCreatorType() if type in undefs: type = 'APPL' if ctor in undefs: ctor = tctor # Open the output resource fork try: output = FSpOpenResFile(dest_fss, WRITE) except MacOS.Error: print "Creating resource fork..." CreateResFile(destname) output = FSpOpenResFile(dest_fss, WRITE) # Copy the resources from the template input = FSpOpenResFile(template_fss, READ) newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Copy the resources from the target specific resource template, if any try: input = FSpOpenResFile(rsrcname, READ) except MacOS.Error: pass else: newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Now set the creator, type and bundle bit of the destination dest_finfo = dest_fss.GetFInfo() dest_finfo.Creator = ctor dest_finfo.Type = type dest_finfo.Flags = dest_finfo.Flags | MACFS.kHasBundle dest_finfo.Flags = dest_finfo.Flags & ~MACFS.kHasBeenInited dest_fss.SetFInfo(dest_finfo) # Make sure we're manipulating the output resource file now UseResFile(output) # Delete any existing 'PYC 'resource named __main__ try: res = Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Error: pass # Create the raw data for the resource from the code object data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Unique1ID(RESTYPE) res = Resource(data) res.AddResource(RESTYPE, id, RESNAME) res.WriteResource() res.ReleaseResource() # Close the output file CloseResFile(output) # Give positive feedback message("Applet %s created." % `destname`)
6,882
def process(template, filename, output): print "Processing", `filename`, "..." # Read the source and compile it # (there's no point overwriting the destination if it has a syntax error) fp = open(filename) text = fp.read() fp.close() try: code = compile(text, filename, "exec") except (SyntaxError, EOFError): die("Syntax error in script %s" % `filename`) return # Set the destination file name if string.lower(filename[-3:]) == ".py": destname = filename[:-3] rsrcname = destname + '.rsrc' else: destname = filename + ".applet" rsrcname = filename + '.rsrc' if output: destname = output # Copy the data from the template (creating the file as well) template_fss = macfs.FSSpec(template) template_fss, d1, d2 = macfs.ResolveAliasFile(template_fss) dest_fss = macfs.FSSpec(destname) tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() # Copy the creator of the template to the destination # unless it already got one. Set type to APPL tctor, ttype = template_fss.GetCreatorType() ctor, type = dest_fss.GetCreatorType() if type in undefs: type = 'APPL' if ctor in undefs: ctor = tctor # Open the output resource fork try: output = FSpOpenResFile(dest_fss, WRITE) except MacOS.Error: print "Creating resource fork..." CreateResFile(destname) output = FSpOpenResFile(dest_fss, WRITE) # Copy the resources from the template input = FSpOpenResFile(template_fss, READ) newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Copy the resources from the target specific resource template, if any try: input = FSpOpenResFile(rsrcname, READ) except MacOS.Error: pass else: newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Now set the creator, type and bundle bit of the destination dest_finfo = dest_fss.GetFInfo() dest_finfo.Creator = ctor dest_finfo.Type = type dest_finfo.Flags = dest_finfo.Flags | MACFS.kHasBundle dest_finfo.Flags = dest_finfo.Flags & ~MACFS.kHasBeenInited dest_fss.SetFInfo(dest_finfo) # Make sure we're manipulating the output resource file now UseResFile(output) # Delete any existing 'PYC 'resource named __main__ try: res = Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Error: pass # Create the raw data for the resource from the code object data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Unique1ID(RESTYPE) res = Resource(data) res.AddResource(RESTYPE, id, RESNAME) res.WriteResource() res.ReleaseResource() # Close the output file CloseResFile(output) # Give positive feedback message("Applet %s created." % `destname`)
def process(template, filename, output): print "Processing", `filename`, "..." # Read the source and compile it # (there's no point overwriting the destination if it has a syntax error) fp = open(filename) text = fp.read() fp.close() try: code = compile(text, filename, "exec") except (SyntaxError, EOFError): die("Syntax error in script %s" % `filename`) return # Set the destination file name if string.lower(filename[-3:]) == ".py": destname = filename[:-3] rsrcname = destname + '.rsrc' else: destname = filename + ".applet" rsrcname = filename + '.rsrc' if output: destname = output # Copy the data from the template (creating the file as well) template_fss = macfs.FSSpec(template) template_fss, d1, d2 = macfs.ResolveAliasFile(template_fss) dest_fss = macfs.FSSpec(destname) tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() # Copy the creator of the template to the destination # unless it already got one. Set type to APPL tctor, ttype = template_fss.GetCreatorType() ctor, type = dest_fss.GetCreatorType() if type in undefs: type = 'APPL' if ctor in undefs: ctor = tctor # Open the output resource fork try: output = FSpOpenResFile(dest_fss, WRITE) except MacOS.Error: if DEBUG: print "Creating resource fork..." CreateResFile(destname) output = FSpOpenResFile(dest_fss, WRITE) # Copy the resources from the template input = FSpOpenResFile(template_fss, READ) newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Copy the resources from the target specific resource template, if any try: input = FSpOpenResFile(rsrcname, READ) except MacOS.Error: pass else: newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Now set the creator, type and bundle bit of the destination dest_finfo = dest_fss.GetFInfo() dest_finfo.Creator = ctor dest_finfo.Type = type dest_finfo.Flags = dest_finfo.Flags | MACFS.kHasBundle dest_finfo.Flags = dest_finfo.Flags & ~MACFS.kHasBeenInited dest_fss.SetFInfo(dest_finfo) # Make sure we're manipulating the output resource file now UseResFile(output) # Delete any existing 'PYC 'resource named __main__ try: res = Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Error: pass # Create the raw data for the resource from the code object data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Unique1ID(RESTYPE) res = Resource(data) res.AddResource(RESTYPE, id, RESNAME) res.WriteResource() res.ReleaseResource() # Close the output file CloseResFile(output) # Give positive feedback message("Applet %s created." % `destname`)
6,883
def process(template, filename, output): print "Processing", `filename`, "..." # Read the source and compile it # (there's no point overwriting the destination if it has a syntax error) fp = open(filename) text = fp.read() fp.close() try: code = compile(text, filename, "exec") except (SyntaxError, EOFError): die("Syntax error in script %s" % `filename`) return # Set the destination file name if string.lower(filename[-3:]) == ".py": destname = filename[:-3] rsrcname = destname + '.rsrc' else: destname = filename + ".applet" rsrcname = filename + '.rsrc' if output: destname = output # Copy the data from the template (creating the file as well) template_fss = macfs.FSSpec(template) template_fss, d1, d2 = macfs.ResolveAliasFile(template_fss) dest_fss = macfs.FSSpec(destname) tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() # Copy the creator of the template to the destination # unless it already got one. Set type to APPL tctor, ttype = template_fss.GetCreatorType() ctor, type = dest_fss.GetCreatorType() if type in undefs: type = 'APPL' if ctor in undefs: ctor = tctor # Open the output resource fork try: output = FSpOpenResFile(dest_fss, WRITE) except MacOS.Error: print "Creating resource fork..." CreateResFile(destname) output = FSpOpenResFile(dest_fss, WRITE) # Copy the resources from the template input = FSpOpenResFile(template_fss, READ) newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Copy the resources from the target specific resource template, if any try: input = FSpOpenResFile(rsrcname, READ) except MacOS.Error: pass else: newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Now set the creator, type and bundle bit of the destination dest_finfo = dest_fss.GetFInfo() dest_finfo.Creator = ctor dest_finfo.Type = type dest_finfo.Flags = dest_finfo.Flags | MACFS.kHasBundle dest_finfo.Flags = dest_finfo.Flags & ~MACFS.kHasBeenInited dest_fss.SetFInfo(dest_finfo) # Make sure we're manipulating the output resource file now UseResFile(output) # Delete any existing 'PYC 'resource named __main__ try: res = Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Error: pass # Create the raw data for the resource from the code object data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Unique1ID(RESTYPE) res = Resource(data) res.AddResource(RESTYPE, id, RESNAME) res.WriteResource() res.ReleaseResource() # Close the output file CloseResFile(output) # Give positive feedback message("Applet %s created." % `destname`)
def process(template, filename, output): print "Processing", `filename`, "..." # Read the source and compile it # (there's no point overwriting the destination if it has a syntax error) fp = open(filename) text = fp.read() fp.close() try: code = compile(text, filename, "exec") except (SyntaxError, EOFError): die("Syntax error in script %s" % `filename`) return # Set the destination file name if string.lower(filename[-3:]) == ".py": destname = filename[:-3] rsrcname = destname + '.rsrc' else: destname = filename + ".applet" rsrcname = filename + '.rsrc' if output: destname = output # Copy the data from the template (creating the file as well) template_fss = macfs.FSSpec(template) template_fss, d1, d2 = macfs.ResolveAliasFile(template_fss) dest_fss = macfs.FSSpec(destname) tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() # Copy the creator of the template to the destination # unless it already got one. Set type to APPL tctor, ttype = template_fss.GetCreatorType() ctor, type = dest_fss.GetCreatorType() if type in undefs: type = 'APPL' if ctor in undefs: ctor = tctor # Open the output resource fork try: output = FSpOpenResFile(dest_fss, WRITE) except (MacOS.Error, ValueError): print 'No resource file', rsrcname print "Creating resource fork..." CreateResFile(destname) output = FSpOpenResFile(dest_fss, WRITE) # Copy the resources from the template input = FSpOpenResFile(template_fss, READ) newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Copy the resources from the target specific resource template, if any try: input = FSpOpenResFile(rsrcname, READ) except (MacOS.Error, ValueError): print 'No resource file', rsrcname pass else: newctor = copyres(input, output) CloseResFile(input) if newctor: ctor = newctor # Now set the creator, type and bundle bit of the destination dest_finfo = dest_fss.GetFInfo() dest_finfo.Creator = ctor dest_finfo.Type = type dest_finfo.Flags = dest_finfo.Flags | MACFS.kHasBundle dest_finfo.Flags = dest_finfo.Flags & ~MACFS.kHasBeenInited dest_fss.SetFInfo(dest_finfo) # Make sure we're manipulating the output resource file now UseResFile(output) # Delete any existing 'PYC 'resource named __main__ try: res = Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Error: pass # Create the raw data for the resource from the code object data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Unique1ID(RESTYPE) res = Resource(data) res.AddResource(RESTYPE, id, RESNAME) res.WriteResource() res.ReleaseResource() # Close the output file CloseResFile(output) # Give positive feedback message("Applet %s created." % `destname`)
6,884
def copyres(input, output): ctor = None UseResFile(input) ntypes = Count1Types() for itype in range(1, 1+ntypes): type = Get1IndType(itype) nresources = Count1Resources(type) for ires in range(1, 1+nresources): res = Get1IndResource(type, ires) id, type, name = res.GetResInfo() lcname = string.lower(name) if (type, lcname) == (RESTYPE, RESNAME): continue # Don't copy __main__ from template if lcname == OWNERNAME: ctor = type size = res.size attrs = res.GetResAttrs() print id, type, name, size, hex(attrs) res.LoadResource() res.DetachResource() UseResFile(output) try: res2 = Get1Resource(type, id) except MacOS.Error: res2 = None if res2: print "Overwriting..." res2.RemoveResource() res.AddResource(type, id, name) res.WriteResource() attrs = attrs | res.GetResAttrs() print "New attrs =", hex(attrs) res.SetResAttrs(attrs) UseResFile(input) return ctor
def copyres(input, output): ctor = None UseResFile(input) ntypes = Count1Types() for itype in range(1, 1+ntypes): type = Get1IndType(itype) nresources = Count1Resources(type) for ires in range(1, 1+nresources): res = Get1IndResource(type, ires) id, type, name = res.GetResInfo() lcname = string.lower(name) if (type, lcname) == (RESTYPE, RESNAME): continue # Don't copy __main__ from template if lcname == OWNERNAME: ctor = type size = res.size attrs = res.GetResAttrs() if DEBUG: print id, type, name, size, hex(attrs) res.LoadResource() res.DetachResource() UseResFile(output) try: res2 = Get1Resource(type, id) except MacOS.Error: res2 = None if res2: print "Overwriting..." res2.RemoveResource() res.AddResource(type, id, name) res.WriteResource() attrs = attrs | res.GetResAttrs() print "New attrs =", hex(attrs) res.SetResAttrs(attrs) UseResFile(input) return ctor
6,885
def copyres(input, output): ctor = None UseResFile(input) ntypes = Count1Types() for itype in range(1, 1+ntypes): type = Get1IndType(itype) nresources = Count1Resources(type) for ires in range(1, 1+nresources): res = Get1IndResource(type, ires) id, type, name = res.GetResInfo() lcname = string.lower(name) if (type, lcname) == (RESTYPE, RESNAME): continue # Don't copy __main__ from template if lcname == OWNERNAME: ctor = type size = res.size attrs = res.GetResAttrs() print id, type, name, size, hex(attrs) res.LoadResource() res.DetachResource() UseResFile(output) try: res2 = Get1Resource(type, id) except MacOS.Error: res2 = None if res2: print "Overwriting..." res2.RemoveResource() res.AddResource(type, id, name) res.WriteResource() attrs = attrs | res.GetResAttrs() print "New attrs =", hex(attrs) res.SetResAttrs(attrs) UseResFile(input) return ctor
def copyres(input, output): ctor = None UseResFile(input) ntypes = Count1Types() for itype in range(1, 1+ntypes): type = Get1IndType(itype) nresources = Count1Resources(type) for ires in range(1, 1+nresources): res = Get1IndResource(type, ires) id, type, name = res.GetResInfo() lcname = string.lower(name) if (type, lcname) == (RESTYPE, RESNAME): continue # Don't copy __main__ from template if lcname == OWNERNAME: ctor = type size = res.size attrs = res.GetResAttrs() print id, type, name, size, hex(attrs) res.LoadResource() res.DetachResource() UseResFile(output) try: res2 = Get1Resource(type, id) except MacOS.Error: res2 = None if res2: if DEBUG: print "Overwriting..." res2.RemoveResource() res.AddResource(type, id, name) res.WriteResource() attrs = attrs | res.GetResAttrs() print "New attrs =", hex(attrs) res.SetResAttrs(attrs) UseResFile(input) return ctor
6,886
def copyres(input, output): ctor = None UseResFile(input) ntypes = Count1Types() for itype in range(1, 1+ntypes): type = Get1IndType(itype) nresources = Count1Resources(type) for ires in range(1, 1+nresources): res = Get1IndResource(type, ires) id, type, name = res.GetResInfo() lcname = string.lower(name) if (type, lcname) == (RESTYPE, RESNAME): continue # Don't copy __main__ from template if lcname == OWNERNAME: ctor = type size = res.size attrs = res.GetResAttrs() print id, type, name, size, hex(attrs) res.LoadResource() res.DetachResource() UseResFile(output) try: res2 = Get1Resource(type, id) except MacOS.Error: res2 = None if res2: print "Overwriting..." res2.RemoveResource() res.AddResource(type, id, name) res.WriteResource() attrs = attrs | res.GetResAttrs() print "New attrs =", hex(attrs) res.SetResAttrs(attrs) UseResFile(input) return ctor
def copyres(input, output): ctor = None UseResFile(input) ntypes = Count1Types() for itype in range(1, 1+ntypes): type = Get1IndType(itype) nresources = Count1Resources(type) for ires in range(1, 1+nresources): res = Get1IndResource(type, ires) id, type, name = res.GetResInfo() lcname = string.lower(name) if (type, lcname) == (RESTYPE, RESNAME): continue # Don't copy __main__ from template if lcname == OWNERNAME: ctor = type size = res.size attrs = res.GetResAttrs() print id, type, name, size, hex(attrs) res.LoadResource() res.DetachResource() UseResFile(output) try: res2 = Get1Resource(type, id) except MacOS.Error: res2 = None if res2: print "Overwriting..." res2.RemoveResource() res.AddResource(type, id, name) res.WriteResource() attrs = attrs | res.GetResAttrs() if DEBUG: print "New attrs =", hex(attrs) res.SetResAttrs(attrs) UseResFile(input) return ctor
6,887
def urlparse(url, scheme = '', allow_framents = 1): key = url, scheme, allow_framents try: return _parse_cache[key] except KeyError: pass if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() netloc = path = params = query = fragment = '' i = string.find(url, ':') if i > 0: for c in url[:i]: if c not in scheme_chars: break else: scheme, url = string.lower(url[:i]), url[i+1:] if scheme in uses_netloc: if url[:2] == '//': i = string.find(url, '/', 2) if i < 0: i = len(url) netloc, url = url[2:i], url[i:] if allow_framents and scheme in uses_fragment: i = string.rfind(url, '#') if i >= 0: url, fragment = url[:i], url[i+1:] if scheme in uses_query: i = string.find(url, '?') if i >= 0: url, query = url[:i], url[i+1:] if scheme in uses_params: i = string.find(url, ';') if i >= 0: url, params = url[:i], url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple
def urlparse(url, scheme = '', allow_fragments = 1): key = url, scheme, allow_fragments try: return _parse_cache[key] except KeyError: pass if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() netloc = path = params = query = fragment = '' i = string.find(url, ':') if i > 0: for c in url[:i]: if c not in scheme_chars: break else: scheme, url = string.lower(url[:i]), url[i+1:] if scheme in uses_netloc: if url[:2] == '//': i = string.find(url, '/', 2) if i < 0: i = len(url) netloc, url = url[2:i], url[i:] if allow_framents and scheme in uses_fragment: i = string.rfind(url, '#') if i >= 0: url, fragment = url[:i], url[i+1:] if scheme in uses_query: i = string.find(url, '?') if i >= 0: url, query = url[:i], url[i+1:] if scheme in uses_params: i = string.find(url, ';') if i >= 0: url, params = url[:i], url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple
6,888
def urlparse(url, scheme = '', allow_framents = 1): key = url, scheme, allow_framents try: return _parse_cache[key] except KeyError: pass if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() netloc = path = params = query = fragment = '' i = string.find(url, ':') if i > 0: for c in url[:i]: if c not in scheme_chars: break else: scheme, url = string.lower(url[:i]), url[i+1:] if scheme in uses_netloc: if url[:2] == '//': i = string.find(url, '/', 2) if i < 0: i = len(url) netloc, url = url[2:i], url[i:] if allow_framents and scheme in uses_fragment: i = string.rfind(url, '#') if i >= 0: url, fragment = url[:i], url[i+1:] if scheme in uses_query: i = string.find(url, '?') if i >= 0: url, query = url[:i], url[i+1:] if scheme in uses_params: i = string.find(url, ';') if i >= 0: url, params = url[:i], url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple
def urlparse(url, scheme = '', allow_framents = 1): key = url, scheme, allow_framents try: return _parse_cache[key] except KeyError: pass if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() netloc = path = params = query = fragment = '' i = string.find(url, ':') if i > 0: for c in url[:i]: if c not in scheme_chars: break else: scheme, url = string.lower(url[:i]), url[i+1:] if scheme in uses_netloc: if url[:2] == '//': i = string.find(url, '/', 2) if i < 0: i = len(url) netloc, url = url[2:i], url[i:] if allow_fragments and scheme in uses_fragment: i = string.rfind(url, '#') if i >= 0: url, fragment = url[:i], url[i+1:] if scheme in uses_query: i = string.find(url, '?') if i >= 0: url, query = url[:i], url[i+1:] if scheme in uses_params: i = string.find(url, ';') if i >= 0: url, params = url[:i], url[i+1:] tuple = scheme, netloc, url, params, query, fragment _parse_cache[key] = tuple return tuple
6,889
def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
def urljoin(base, url, allow_fragments = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
6,890
def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
6,891
def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
6,892
def translate(s, table, deletions=""): """translate(s,table [,deletechars]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. """ return s.translate(table, deletions)
def translate(s, table, deletions=""): """translate(s,table [,deletions]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. """ return s.translate(table, deletions)
6,893
def translate(s, table, deletions=""): """translate(s,table [,deletechars]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. """ return s.translate(table, deletions)
def translate(s, table, deletions=""): """translate(s,table [,deletechars]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletions are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. """ return s.translate(table, deletions)
6,894
def translate(s, table, deletions=""): """translate(s,table [,deletechars]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. """ return s.translate(table, deletions)
def translate(s, table, deletions=""): """translate(s,table [,deletechars]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. The deletions argument is not allowed for Unicode strings. """ if deletions: return s.translate(table, deletions) else: return s.translate(table + s[:0])
6,895
def __init__(self, flavorOrder=None, downloadDir=None, buildDir=None, installDir=None, pimpDatabase=None): if not flavorOrder: flavorOrder = DEFAULT_FLAVORORDER if not downloadDir: downloadDir = DEFAULT_DOWNLOADDIR if not buildDir: buildDir = DEFAULT_BUILDDIR if not installDir: installDir = DEFAULT_INSTALLDIR if not pimpDatabase: pimpDatabase = DEFAULT_PIMPDATABASE self.flavorOrder = flavorOrder self.downloadDir = downloadDir self.buildDir = buildDir self.installDir = installDir self.pimpDatabase = pimpDatabase
def __init__(self, flavorOrder=None, downloadDir=None, buildDir=None, installDir=None, pimpDatabase=None): if not flavorOrder: flavorOrder = DEFAULT_FLAVORORDER if not downloadDir: downloadDir = DEFAULT_DOWNLOADDIR if not buildDir: buildDir = DEFAULT_BUILDDIR if not pimpDatabase: pimpDatabase = DEFAULT_PIMPDATABASE self.flavorOrder = flavorOrder self.downloadDir = downloadDir self.buildDir = buildDir self.installDir = installDir self.pimpDatabase = pimpDatabase
6,896
def check(self): """Check that the preferences make sense: directories exist and are writable, the install directory is on sys.path, etc.""" rv = "" RWX_OK = os.R_OK|os.W_OK|os.X_OK if not os.path.exists(self.downloadDir): rv += "Warning: Download directory \"%s\" does not exist\n" % self.downloadDir elif not os.access(self.downloadDir, RWX_OK): rv += "Warning: Download directory \"%s\" is not writable or not readable\n" % self.downloadDir if not os.path.exists(self.buildDir): rv += "Warning: Build directory \"%s\" does not exist\n" % self.buildDir elif not os.access(self.buildDir, RWX_OK): rv += "Warning: Build directory \"%s\" is not writable or not readable\n" % self.buildDir if not os.path.exists(self.installDir): rv += "Warning: Install directory \"%s\" does not exist\n" % self.installDir elif not os.access(self.installDir, RWX_OK): rv += "Warning: Install directory \"%s\" is not writable or not readable\n" % self.installDir else: installDir = os.path.realpath(self.installDir) for p in sys.path: try: realpath = os.path.realpath(p) except: pass if installDir == realpath: break else: rv += "Warning: Install directory \"%s\" is not on sys.path\n" % self.installDir return rv
def check(self): """Check that the preferences make sense: directories exist and are writable, the install directory is on sys.path, etc.""" rv = "" RWX_OK = os.R_OK|os.W_OK|os.X_OK if not os.path.exists(self.downloadDir): rv += "Warning: Download directory \"%s\" does not exist\n" % self.downloadDir elif not os.access(self.downloadDir, RWX_OK): rv += "Warning: Download directory \"%s\" is not writable or not readable\n" % self.downloadDir if not os.path.exists(self.buildDir): rv += "Warning: Build directory \"%s\" does not exist\n" % self.buildDir elif not os.access(self.buildDir, RWX_OK): rv += "Warning: Build directory \"%s\" is not writable or not readable\n" % self.buildDir if not os.path.exists(self.installDir): rv += "Warning: Install directory \"%s\" does not exist\n" % self.installDir elif not os.access(self.installDir, RWX_OK): rv += "Warning: Install directory \"%s\" is not writable or not readable\n" % self.installDir else: installDir = os.path.realpath(self.installDir) for p in sys.path: try: realpath = os.path.realpath(p) except: pass if installDir == realpath: break else: rv += "Warning: Install directory \"%s\" is not on sys.path\n" % self.installDir return rv
6,897
def _cmd(self, output, dir, *cmditems): """Internal routine to run a shell command in a given directory.""" cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems) if output: output.write("+ %s\n" % cmd) if NO_EXECUTE: return 0 child = popen2.Popen4(cmd) child.tochild.close() while 1: line = child.fromchild.readline() if not line: break if output: output.write(line) return child.wait()
6,898
def downloadPackageOnly(self, output=None): """Download a single package, if needed. An MD5 signature is used to determine whether download is needed, and to test that we actually downloaded what we expected. If output is given it is a file-like object that will receive a log of what happens. If anything unforeseen happened the method returns an error message string. """ scheme, loc, path, query, frag = urlparse.urlsplit(self._dict['Download-URL']) path = urllib.url2pathname(path) filename = os.path.split(path)[1] self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename) if not self._archiveOK(): if scheme == 'manual': return "Please download package manually and save as %s" % self.archiveFilename if self._cmd(output, self._db.preferences.downloadDir, "curl", "--output", self.archiveFilename, self._dict['Download-URL']): return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: return "archive not found after download" if not self._archiveOK(): return "archive does not have correct MD5 checksum"
def downloadPackageOnly(self, output=None): """Download a single package, if needed. An MD5 signature is used to determine whether download is needed, and to test that we actually downloaded what we expected. If output is given it is a file-like object that will receive a log of what happens. If anything unforeseen happened the method returns an error message string. """ scheme, loc, path, query, frag = urlparse.urlsplit(self._dict['Download-URL']) path = urllib.url2pathname(path) filename = os.path.split(path)[1] self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename) if not self._archiveOK(): if scheme == 'manual': return "Please download package manually and save as %s" % self.archiveFilename if _cmd(output, self._db.preferences.downloadDir, "curl", "--output", self.archiveFilename, self._dict['Download-URL']): return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: return "archive not found after download" if not self._archiveOK(): return "archive does not have correct MD5 checksum"
6,899