rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.rpcpid = os.spawnv(os.P_NOWAIT, args[0], args)
self.rpcpid = os.spawnv(os.P_NOWAIT, sys.executable, args)
def spawn_subprocess(self): args = self.subprocess_arglist self.rpcpid = os.spawnv(os.P_NOWAIT, args[0], args)
return [sys.executable] + w + ["-c", command, str(self.port)]
if sys.platform[:3] == 'win' and ' ' in sys.executable: decorated_exec = '"%s"' % sys.executable else: decorated_exec = sys.executable return [decorated_exec] + w + ["-c", command, str(self.port)]
def build_subprocess_arglist(self): w = ['-W' + s for s in sys.warnoptions] # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') if __name__ == 'idlelib.PyShell': command = "__import__('idlelib.run').run.main(" + `del_exitf` +")" else: command = "__import__('run').main(" + `del_exitf` + ")" return [sys.executable] + w + ["-c", command, str(self.port)]
curses_libs = ['curses', 'termcap']
curses_libs = ['curses']
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
if os.path.exists(filename) or hasattr(getmodule(object), '__loader__'):
if os.path.exists(filename): return filename if filename[:1]!='<' and hasattr(getmodule(object), '__loader__'):
def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. return None if os.path.exists(filename) or hasattr(getmodule(object), '__loader__'): return filename
a.pop()
x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type`
def testtype(type, example): a = array.array(type) a.append(example) if verbose: print 40*'*' print 'array after append: ', a a.typecode a.itemsize if a.typecode in ('i', 'b', 'h', 'l'): a.byteswap() if a.typecode == 'c': f = open(TESTFN, "w") f.write("The quick brown fox jumps over the lazy dog.\n") f.close() f = open(TESTFN, 'r') a.fromfile(f, 10) f.close() if verbose: print 'char array with 10 bytes of TESTFN appended: ', a a.fromlist(['a', 'b', 'c']) if verbose: print 'char array with list appended: ', a a.insert(0, example) if verbose: print 'array of %s after inserting another:' % a.typecode, a f = open(TESTFN, 'w') a.tofile(f) f.close() a.tolist() a.tostring() if verbose: print 'array of %s converted to a list: ' % a.typecode, a.tolist() if verbose: print 'array of %s converted to a string: ' \ % a.typecode, `a.tostring()` if type == 'c': a = array.array(type, "abcde") a[:-1] = a if a != array.array(type, "abcdee"): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, "abcde") a[1:] = a if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, "abcde") a[1:-1] = a if a != array.array(type, "aabcdee"): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index("e") != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count("a") != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove("e") if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != "a": raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != "b": raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, "xyz")) if a != array.array(type, "acdexyz"): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, "acd"): raise TestFailed, "array(%s) pop-test" % `type` else: a = array.array(type, [1, 2, 3, 4, 5]) a[:-1] = a if a != array.array(type, [1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:] = a if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:-1] = a if a != array.array(type, [1, 1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index(5) != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count(1) != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove(5) if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != 1: raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != 2: raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, [7, 8, 9])) if a != array.array(type, [1, 3, 4, 5, 7, 8, 9]): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, [1, 3, 4]): raise TestFailed, "array(%s) pop-test" % `type` # test that overflow exceptions are raised as expected for assignment # to array of specific integral types from math import pow if type in ('b', 'h', 'i', 'l'): # check signed and unsigned versions a = array.array(type) signedLowerLimit = -1 * long(pow(2, a.itemsize * 8 - 1)) signedUpperLimit = long(pow(2, a.itemsize * 8 - 1)) - 1L unsignedLowerLimit = 0 unsignedUpperLimit = long(pow(2, a.itemsize * 8)) - 1L testoverflow(type, signedLowerLimit, signedUpperLimit) testoverflow(type.upper(), unsignedLowerLimit, unsignedUpperLimit)
a.pop()
x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type`
def testtype(type, example): a = array.array(type) a.append(example) if verbose: print 40*'*' print 'array after append: ', a a.typecode a.itemsize if a.typecode in ('i', 'b', 'h', 'l'): a.byteswap() if a.typecode == 'c': f = open(TESTFN, "w") f.write("The quick brown fox jumps over the lazy dog.\n") f.close() f = open(TESTFN, 'r') a.fromfile(f, 10) f.close() if verbose: print 'char array with 10 bytes of TESTFN appended: ', a a.fromlist(['a', 'b', 'c']) if verbose: print 'char array with list appended: ', a a.insert(0, example) if verbose: print 'array of %s after inserting another:' % a.typecode, a f = open(TESTFN, 'w') a.tofile(f) f.close() a.tolist() a.tostring() if verbose: print 'array of %s converted to a list: ' % a.typecode, a.tolist() if verbose: print 'array of %s converted to a string: ' \ % a.typecode, `a.tostring()` if type == 'c': a = array.array(type, "abcde") a[:-1] = a if a != array.array(type, "abcdee"): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, "abcde") a[1:] = a if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, "abcde") a[1:-1] = a if a != array.array(type, "aabcdee"): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index("e") != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count("a") != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove("e") if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != "a": raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != "b": raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, "xyz")) if a != array.array(type, "acdexyz"): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, "acd"): raise TestFailed, "array(%s) pop-test" % `type` else: a = array.array(type, [1, 2, 3, 4, 5]) a[:-1] = a if a != array.array(type, [1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:] = a if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:-1] = a if a != array.array(type, [1, 1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index(5) != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count(1) != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove(5) if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != 1: raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != 2: raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, [7, 8, 9])) if a != array.array(type, [1, 3, 4, 5, 7, 8, 9]): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, [1, 3, 4]): raise TestFailed, "array(%s) pop-test" % `type` # test that overflow exceptions are raised as expected for assignment # to array of specific integral types from math import pow if type in ('b', 'h', 'i', 'l'): # check signed and unsigned versions a = array.array(type) signedLowerLimit = -1 * long(pow(2, a.itemsize * 8 - 1)) signedUpperLimit = long(pow(2, a.itemsize * 8 - 1)) - 1L unsignedLowerLimit = 0 unsignedUpperLimit = long(pow(2, a.itemsize * 8)) - 1L testoverflow(type, signedLowerLimit, signedUpperLimit) testoverflow(type.upper(), unsignedLowerLimit, unsignedUpperLimit)
r'(?P<header>[-\w_.*,(){} ]+)'
r'(?P<header>[^]]+)'
def remove_section(self, section): """Remove a file section.""" if self.__sections.has_key(section): del self.__sections[section] return 1 else: return 0
if not str:
if not s:
def decode(in_file, out_file=None, mode=None): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr: raise Error, 'No valid begin line found in input file' if hdr[:5] != 'begin': continue hdrfields = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): fp = open(out_file, 'wb') try: os.path.chmod(out_file, mode) except AttributeError: pass out_file = fp # # Main decoding loop # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = binascii.a2b_uu(s[:nbytes]) sys.stderr.write("Warning: %s\n" % str(v)) out_file.write(data) s = in_file.readline() if not str: raise Error, 'Truncated input file'
if platform_specific:
if plat_specific:
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
def __init__(self, environ=os.environ): self.dict = self.data = parse(environ=environ)
def __init__(self, environ=os.environ, keep_blank_values=0, strict_parsing=0): self.dict = self.data = parse(environ=environ, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing)
def __init__(self, environ=os.environ): self.dict = self.data = parse(environ=environ) self.query_string = environ['QUERY_STRING']
if not grouping:return s
if not grouping:return (s, 0)
def _group(s): conv=localeconv() grouping=conv['grouping'] if not grouping:return s result="" seps = 0 spaces = "" if s[-1] == ' ': sp = s.find(' ') spaces = s[sp:] s = s[:sp] while s and grouping: # if grouping is -1, we are done if grouping[0]==CHAR_MAX: break # 0: re-use last group ad infinitum elif grouping[0]!=0: #process last group group=grouping[0] grouping=grouping[1:] if result: result=s[-group:]+conv['thousands_sep']+result seps += 1 else: result=s[-group:] s=s[:-group] if s and s[-1] not in "0123456789": # the leading string is only spaces and signs return s+result+spaces,seps if not result: return s+spaces,seps if s: result=s+conv['thousands_sep']+result seps += 1 return result+spaces,seps
event = self.getevent(mask, wait) if event:
ok, event = self.getevent(mask, wait) if IsDialogEvent(event): if self.do_dialogevent(event): return if ok:
def do1event(self, mask = everyEvent, wait = 0): event = self.getevent(mask, wait) if event: self.dispatch(event)
if ok: return event else: return None
return ok, event
def getevent(self, mask = everyEvent, wait = 0): ok, event = WaitNextEvent(mask, wait) if ok: return event else: return None
if IsDialogEvent(event): self.do_dialogevent(event) return
def dispatch(self, event): if IsDialogEvent(event): self.do_dialogevent(event) return (what, message, when, where, modifiers) = event if eventname.has_key(what): name = "do_" + eventname[what] else: name = "do_%d" % what try: handler = getattr(self, name) except AttributeError: handler = self.do_unknownevent handler(event)
window.do_itemhit(item, event)
self._windows[window].do_itemhit(item, event)
def do_dialogevent(self, event): gotone, window, item = DialogSelect(event) if gotone: if self._windows.has_key(window): window.do_itemhit(item, event) else: print 'Dialog event for unknown dialog'
self.wid.DisposeDialog()
def close(self): self.wid.DisposeDialog() self.do_postclose()
iv = (float(i)/float(maxi-1))-0.5
if maxi = 1: iv = 0 else: iv = (float(i)/float(maxi-1))-0.5
def initcmap(ybits,ibits,qbits,chrompack): if ybits+ibits+qbits > 11: raise 'Sorry, 11 bits max' maxy = pow(2,ybits) maxi = pow(2,ibits) maxq = pow(2,qbits) for i in range(2048,4096-256): mapcolor(i, 0, 255, 0) for y in range(maxy): yv = float(y)/float(maxy-1) for i in range(maxi): iv = (float(i)/float(maxi-1))-0.5 for q in range(maxq): qv = (float(q)/float(maxq-1))-0.5 index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) if index < 4096 - 256: mapcolor(index, r,g,b)
qv = (float(q)/float(maxq-1))-0.5
if maxq = 1: qv = 0 else: qv = (float(q)/float(maxq-1))-0.5
def initcmap(ybits,ibits,qbits,chrompack): if ybits+ibits+qbits > 11: raise 'Sorry, 11 bits max' maxy = pow(2,ybits) maxi = pow(2,ibits) maxq = pow(2,qbits) for i in range(2048,4096-256): mapcolor(i, 0, 255, 0) for y in range(maxy): yv = float(y)/float(maxy-1) for i in range(maxi): iv = (float(i)/float(maxi-1))-0.5 for q in range(maxq): qv = (float(q)/float(maxq-1))-0.5 index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) if index < 4096 - 256: mapcolor(index, r,g,b)
assert len(a) == 1
vereq(len(a), 1)
def __init__(self, *a, **kw): if a: assert len(a) == 1 self.state = a[0] if kw: for k, v in kw.items(): self[v] = k
assert isinstance(key, type(0))
verify(isinstance(key, type(0)))
def __setitem__(self, key, value): assert isinstance(key, type(0)) dict.__setitem__(self, key, value)
assert x.__class__ == a.__class__ assert sorteditems(x.__dict__) == sorteditems(a.__dict__) assert y.__class__ == b.__class__ assert sorteditems(y.__dict__) == sorteditems(b.__dict__) assert `x` == `a` assert `y` == `b`
vereq(x.__class__, a.__class__) vereq(sorteditems(x.__dict__), sorteditems(a.__dict__)) vereq(y.__class__, b.__class__) vereq(sorteditems(y.__dict__), sorteditems(b.__dict__)) vereq(`x`, `a`) vereq(`y`, `b`)
def __repr__(self): return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
return self.socket.recvfrom(self.max_packet_size)
data, client_addr = self.socket.recvfrom(self.max_packet_size) return (data, self.socket), client_addr def server_activate(self): pass
def get_request(self): return self.socket.recvfrom(self.max_packet_size)
unsigned int uiValue;
Py_UCS4 value;
typedef struct
except ValueError: pass else: raise TestFailed, "int(%s)" % `s[1:]` + " should raise ValueError"
except: raise TestFailed, "int(%s)" % `s[1:]` + " should return long"
def f(): pass
try: int('1' * 512) except ValueError: pass else: raise TestFailed("int('1' * 512) didn't raise ValueError")
try: int('1' * 600) except: raise TestFailed("int('1' * 600) didn't return long") if have_unicode: try: int(unichr(0x661) * 600) except: raise TestFailed("int('\\u0661' * 600) didn't return long")
def f(): pass
elif type( item )==StringType:
elif type( item ) in [StringType, UnicodeType]:
def _getName( item, nameFromNum ): "Helper function -- don't use it directly" if type( item ) == IntType: try: keyname = nameFromNum( item ) except (WindowsError, EnvironmentError): raise IndexError, item elif type( item )==StringType: keyname=item else: raise exceptions.TypeError, \ "Requires integer index or string key name" return keyname
if type( data )==StringType:
if type( data ) in [StringType, UnicodeType]:
def setValue( self, valname, data, regtype=None ): "Set a data value's data (and optionally type)" if regtype: typeint=regtype.intval else: if type( data )==StringType: typeint=_winreg.REG_SZ elif type( data )==IntType: typeint=_winreg.REG_DWORD elif type( data )==array.ArrayType: typeint=_winreg.REG_BINARY data=data.tostring() _winreg.SetValueEx( self.handle, valname, 0, typeint, data )
data=data.tostring()
def setValue( self, valname, data, regtype=None ): "Set a data value's data (and optionally type)" if regtype: typeint=regtype.intval else: if type( data )==StringType: typeint=_winreg.REG_SZ elif type( data )==IntType: typeint=_winreg.REG_DWORD elif type( data )==array.ArrayType: typeint=_winreg.REG_BINARY data=data.tostring() _winreg.SetValueEx( self.handle, valname, 0, typeint, data )
def _monthcalendar(year, month):
def monthcalendar(year, month):
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
day = 1 - day1
day = (_firstweekday - day1 + 6) % 7 - 5
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
_mc_cache = {} def monthcalendar(year, month): """Caching interface to _monthcalendar.""" key = (year, month) if _mc_cache.has_key(key): return _mc_cache[key] else: _mc_cache[key] = ret = _monthcalendar(year, month) return ret
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
def prweek(week, width):
def prweek(theweek, width):
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
for day in week: if day == 0: s = '' else: s = `day` print _center(s, width),
print week(theweek, width), def week(theweek, width): """Returns a single week in a string (no newline).""" days = [] for day in theweek: if day == 0: s = '' else: s = '%2i' % day days.append(_center(s, width)) return ' '.join(days)
def prweek(week, width): """Print a single week (no newline).""" for day in week: if day == 0: s = '' else: s = `day` print _center(s, width),
str = '' if width >= 9: names = day_name else: names = day_abbr for i in range(7): if str: str = str + ' ' str = str + _center(names[i%7][:width], width) return str def prmonth(year, month, w = 0, l = 0):
if width >= 9: names = day_name else: names = day_abbr days = [] for i in range(_firstweekday, _firstweekday + 7): days.append(_center(names[i%7][:width], width)) return ' '.join(days) def prmonth(theyear, themonth, w=0, l=0):
def weekheader(width): """Return a header for a week.""" str = '' if width >= 9: names = day_name else: names = day_abbr for i in range(7): if str: str = str + ' ' str = str + _center(names[i%7][:width], width) return str
print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print '\n'*l, print weekheader(w), print '\n'*l, for week in monthcalendar(year, month): prweek(week, w) print '\n'*l,
s = (_center(month_name[themonth] + ' ' + `theyear`, 7 * (w + 1) - 1).rstrip() + '\n' * l + weekheader(w).rstrip() + '\n' * l) for aweek in monthcalendar(theyear, themonth): s = s + week(aweek, w).rstrip() + '\n' * l return s[:-l] + '\n'
def prmonth(year, month, w = 0, l = 0): """Print a month's calendar.""" w = max(2, w) l = max(1, l) print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print '\n'*l, print weekheader(w), print '\n'*l, for week in monthcalendar(year, month): prweek(week, w) print '\n'*l,
_spacing = ' '*4 def format3c(a, b, c): """3-column formatting for year calendars""" print _center(a, _colwidth), print _spacing, print _center(b, _colwidth), print _spacing, print _center(c, _colwidth) def prcal(year):
_spacing = 6 def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing): """Prints 3-column formatting for year calendars""" print format3cstring(a, b, c, colwidth, spacing) def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from 3 strings, centered within 3 columns.""" return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) + ' ' * spacing + _center(c, colwidth)) def prcal(year, w=0, l=0, c=_spacing):
def prmonth(year, month, w = 0, l = 0): """Print a month's calendar.""" w = max(2, w) l = max(1, l) print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print '\n'*l, print weekheader(w), print '\n'*l, for week in monthcalendar(year, month): prweek(week, w) print '\n'*l,
header = weekheader(2) format3c('', `year`, '')
print calendar(year, w, l, c), def calendar(year, w=0, l=0, c=_spacing): """Returns a year's calendar as a multi-line string.""" w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip()
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header)
s = (s + '\n' * l + format3cstring(month_name[q], month_name[q+1], month_name[q+2], colwidth, c).rstrip() + '\n' * l + header + '\n' * l)
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal)
for amonth in range(q, q + 3): cal = monthcalendar(year, amonth) if len(cal) > height: height = len(cal)
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
print ' '*_colwidth,
weeks.append('')
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
prweek(cal[i], 2) print _spacing, print
weeks.append(week(cal[i], w)) s = s + format3cstring(weeks[0], weeks[1], weeks[2], colwidth, c).rstrip() + '\n' * l return s[:-l] + '\n'
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
def loop(timeout=30.0, use_poll=False, map=None):
def loop(timeout=30.0, use_poll=False, map=None, count=None):
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
while map: poll_fun(timeout, map)
if count is None: while map: poll_fun(timeout, map) else: while map and count > 0: poll_fun(timeout, map) count = count - 1
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
"""Fail if the two objects are unequal as determined by the '!='
"""Fail if the two objects are unequal as determined by the '=='
def failUnlessEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '!=' operator. """ if first != second: raise self.failureException, \ (msg or '%s != %s' % (`first`, `second`))
if first != second:
if not first == second:
def failUnlessEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '!=' operator. """ if first != second: raise self.failureException, \ (msg or '%s != %s' % (`first`, `second`))
return '\n'.join(output)
return '\n'.join(output) + '\n'
def script_from_examples(s): r"""Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum """ output = [] for piece in DocTestParser().parse(s): if isinstance(piece, Example): # Add the example's source code (strip trailing NL) output.append(piece.source[:-1]) # Add the expected output: want = piece.want if want: output.append('# Expected:') output += ['## '+l for l in want.split('\n')[:-1]] else: # Add non-example text. output += [_comment_line(l) for l in piece.split('\n')[:-1]] # Trim junk on both ends. while output and output[-1] == '#': output.pop() while output and output[0] == '#': output.pop(0) # Combine the output, and return it. return '\n'.join(output)
msg = self.idb.set_break(filename, lineno) if msg: text.bell() return
self.idb.set_break(filename, lineno)
def set_breakpoint_here(self, filename, lineno): msg = self.idb.set_break(filename, lineno) if msg: text.bell() return
msg = self.idb.clear_break(filename, lineno) if msg: text.bell() return
self.idb.clear_break(filename, lineno)
def clear_breakpoint_here(self, filename, lineno): msg = self.idb.clear_break(filename, lineno) if msg: text.bell() return
msg = self.idb.clear_all_file_breaks(filename) if msg: text.bell() return
self.idb.clear_all_file_breaks(filename)
def clear_file_breaks(self, filename): msg = self.idb.clear_all_file_breaks(filename) if msg: text.bell() return
raise error, "flags should be one of 'r', 'w', 'c' or 'n' or use the bsddb.db.DB_* flags"
raise db.DBError, "flags should be one of 'r', 'w', 'c' or 'n' or use the bsddb.db.DB_* flags"
def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH, dbenv=None, dbname=None): """ A simple factory function for compatibility with the standard shleve.py module. It can be used like this, where key is a string and data is a pickleable object: from bsddb import dbshelve db = dbshelve.open(filename) db[key] = data db.close() """ if type(flags) == type(''): sflag = flags if sflag == 'r': flags = db.DB_RDONLY elif sflag == 'rw': flags = 0 elif sflag == 'w': flags = db.DB_CREATE elif sflag == 'c': flags = db.DB_CREATE elif sflag == 'n': flags = db.DB_TRUNCATE | db.DB_CREATE else: raise error, "flags should be one of 'r', 'w', 'c' or 'n' or use the bsddb.db.DB_* flags" d = DBShelf(dbenv) d.open(filename, dbname, filetype, flags, mode) return d
data = cPickle.dumps(value, self.binary) return self.db.append(data, txn)
if self.get_type() != db.DB_RECNO: self.append = self.__append return self.append(value, txn=txn) raise db.DBError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"
def append(self, value, txn=None): data = cPickle.dumps(value, self.binary) return self.db.append(data, txn)
import os
import os, fcntl
def export_add(self, x, y): return x + y
class Backquote(Node): def __init__(self, expr, lineno=None): self.expr = expr self.lineno = lineno def getChildren(self): return self.expr, def getChildNodes(self): return self.expr, def __repr__(self): return "Backquote(%s)" % (repr(self.expr),)
def __repr__(self): return "AugAssign(%s, %s, %s)" % (repr(self.node), repr(self.op), repr(self.expr))
self.local_hostname = socket.getfqdn()
fqdn = socket.getfqdn() if '.' in fqdn: self.local_hostname = fqdn else: addr = socket.gethostbyname(socket.gethostname()) self.local_hostname = '[%s]' % addr
def __init__(self, host = '', port = 0, local_hostname = None): """Initialize a new instance.
list of strings (???) containing version numbers; the list will be
list of strings containing version numbers; the list will be
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings (???) containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found. (XXX is this correct???)""" try: import win32api import win32con except ImportError: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (win32con.HKEY_CLASSES_ROOT, win32con.HKEY_LOCAL_MACHINE, win32con.HKEY_CURRENT_USER, win32con.HKEY_USERS): try: k = win32api.RegOpenKeyEx(base,K) i = 0 while 1: try: p = win32api.RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except win32api.error: break i = i + 1 except win32api.error: pass L.sort() L.reverse() return L
found. (XXX is this correct???)"""
found."""
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings (???) containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found. (XXX is this correct???)""" try: import win32api import win32con except ImportError: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (win32con.HKEY_CLASSES_ROOT, win32con.HKEY_LOCAL_MACHINE, win32con.HKEY_CURRENT_USER, win32con.HKEY_USERS): try: k = win32api.RegOpenKeyEx(base,K) i = 0 while 1: try: p = win32api.RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except win32api.error: break i = i + 1 except win32api.error: pass L.sort() L.reverse() return L
return None
return []
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a devstudio path (include, lib or path).""" try: import win32api import win32con except ImportError: return None L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (win32con.HKEY_CLASSES_ROOT, win32con.HKEY_LOCAL_MACHINE, win32con.HKEY_CURRENT_USER, win32con.HKEY_USERS): try: k = win32api.RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = win32api.RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except win32api.error: break except win32api.error: pass return L
def _find_exe(exe): for v in get_devstudio_versions(): for p in get_msvc_paths('path',v): fn = os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn try: for p in string.split(os.environ['Path'],';'): fn=os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn except: pass return exe def _find_SET(n): for v in get_devstudio_versions(): p = get_msvc_paths(n,v) if p: return p return [] def _do_SET(n): p = _find_SET(n)
def find_exe (exe, version_number): """Try to find an MSVC executable program 'exe' (from version 'version_number' of MSVC) in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the original program name, 'exe'.""" for p in get_msvc_paths ('path', version_number): fn = os.path.join (os.path.abspath(p), exe) if os.path.isfile(fn): return fn for p in string.split (os.environ['Path'],';'): fn = os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn return exe def _find_SET(name,version_number): """looks up in the registry and returns a list of values suitable for use in a SET command eg SET name=value. Normally the value will be a ';' separated list similar to a path list. name is the name of an MSVC path and version_number is a version_number of an MSVC installation.""" return get_msvc_paths(name, version_number) def _do_SET(name, version_number): """sets os.environ[name] to an MSVC path type value obtained from _find_SET. This is equivalent to a SET command prior to execution of spawned commands.""" p=_find_SET(name, version_number)
def _find_exe(exe): for v in get_devstudio_versions(): for p in get_msvc_paths('path',v): fn = os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn #didn't find it; try existing path try: for p in string.split(os.environ['Path'],';'): fn=os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn # XXX BAD BAD BAD BAD BAD BAD BAD BAD BAD BAD BAD BAD !!!!!!!!!!!!!!!! except: # XXX WHAT'S BEING CAUGHT HERE?!?!? pass return exe #last desperate hope
os.environ[n] = string.join(p,';')
os.environ[name]=string.join(p,';')
def _do_SET(n): p = _find_SET(n) if p: os.environ[n] = string.join(p,';')
self.cc = _find_exe("cl.exe") self.link = _find_exe("link.exe") _do_SET('lib') _do_SET('include') path=_find_SET('path') try: for p in string.split(os.environ['path'],';'): path.append(p) except KeyError: pass os.environ['path'] = string.join(path,';')
vNum = get_devstudio_versions () if vNum: vNum = vNum[0] self.cc = _find_exe("cl.exe", vNum) self.link = _find_exe("link.exe", vNum) _do_SET('lib', vNum) _do_SET('include', vNum) path=_find_SET('path', vNum) try: for p in string.split(os.environ['path'],';'): path.append(p) except KeyError: pass os.environ['path'] = string.join(path,';') else: self.cc = "cl.exe" self.link = "link.exe"
def __init__ (self, verbose=0, dry_run=0, force=0):
self.compile_options = [ '/nologo', '/Ox', '/MD' ]
self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3' ]
def __init__ (self, verbose=0, dry_run=0, force=0):
'/nologo', '/Od', '/MDd', '/Z7', '/D_DEBUG'
'/nologo', '/Od', '/MDd', '/W3', '/Z7', '/D_DEBUG'
def __init__ (self, verbose=0, dry_run=0, force=0):
if ( PyString_Check(args) ) { OSStatus err;
if ( PyString_Check(v) ) {
#ifdef WITHOUT_FRAMEWORKS
PyErr_Mac(ErrorObject, err);
PyMac_Error(err);
#ifdef WITHOUT_FRAMEWORKS
if (FSpMakeFSRef(&((FSSpecObject *)v)->ob_itself, fsr))
if ((err=FSpMakeFSRef(&((FSSpecObject *)v)->ob_itself, fsr)) == 0)
#ifdef WITHOUT_FRAMEWORKS
getsetlist = [ ("data", """int size; PyObject *rv; size = GetHandleSize((Handle)self->ob_itself); HLock((Handle)self->ob_itself); rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size); HUnlock((Handle)self->ob_itself); return rv; """, None, "Raw data of the alias object" ) ]
def output_tp_initBody(self): Output("PyObject *v;") Output("char *kw[] = {\"itself\", 0};") Output() Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O\", kw, &v))") Output("return -1;") Output("if (myPyMac_GetFSRef(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype) Output("return -1;")
module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff)
module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff, longname=LONGMODNAME)
def parseArgumentList(self, args): args0, arg1, argsrest = args[:1], args[1], args[2:] t0, n0, m0 = arg1 args = args0 + argsrest if m0 != InMode: raise ValueError, "method's 'self' must be 'InMode'" self.itself = Variable(t0, "_self->ob_itself", SelfMode) FunctionGenerator.parseArgumentList(self, args) self.argumentList.insert(2, self.itself)
self.compile = None self.no_compile = None
self.compile = 0
def initialize_options (self):
import sys
if debug_stderr: sys.stderr = debug_stderr
def __init__(self): self.preffilepath = ":Python:PythonIDE preferences" Wapplication.Application.__init__(self, 'Pide') from Carbon import AE from Carbon import AppleEvents AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEReopenApplication, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEPrintDocuments, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenDocuments, self.opendocsevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEQuitApplication, self.quitevent) import PyConsole, PyEdit Splash.wait() PyConsole.installoutput() PyConsole.installconsole() import sys for path in sys.argv[1:]: self.opendoc(path) try: import Wthreading except ImportError: self.mainloop() else: if Wthreading.haveThreading: self.mainthread = Wthreading.Thread("IDE event loop", self.mainloop) self.mainthread.start() #self.mainthread.setResistant(1) Wthreading.run() else: self.mainloop()
self.filename = filename
self.filename = _normpath(filename)
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.filename = filename # Name of the file in the archive self.date_time = date_time # year, month, day, hour, min, sec # Standard values: self.compress_type = ZIP_STORED # Type of compression for the file self.comment = "" # Comment for each file self.extra = "" # ZIP extra data self.create_system = 0 # System which created ZIP archive self.create_version = 20 # Version which created ZIP archive self.extract_version = 20 # Version needed to extract archive self.reserved = 0 # Must be zero self.flag_bits = 0 # ZIP flag bits self.volume = 0 # Volume number of file header self.internal_attr = 0 # Internal attributes self.external_attr = 0 # External file attributes # Other attributes are set by class ZipFile: # header_offset Byte offset to the file header # file_offset Byte offset to the start of the file data # CRC CRC-32 of the uncompressed file # compress_size Size of the compressed file # file_size Size of the uncompressed file
key = (filename, lineno,)
key = filename, lineno
def localtrace_trace_and_count(self, frame, why, arg): if why == 'line': # record the file name and line number of every trace # XXX I wish inspect offered me an optimized # `getfilename(frame)' to use in place of the presumably # heavier `getframeinfo()'. --Zooko 2001-10-14 filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 1) key = (filename, lineno,) self.counts[key] = self.counts.get(key, 0) + 1 # XXX not convinced that this memoizing is a performance # win -- I don't know enough about Python guts to tell. # --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: # Using setdefault faster than two separate lines? # --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) try: print "%s(%d): %s" % (bname, lineno, context[lineindex]), except IndexError: # Uh.. sometimes getframeinfo gives me a context of # length 1 and a lineindex of -2. Oh well. pass return self.localtrace
listfuncs = false
listfuncs = False
def main(argv=None): import getopt if argv is None: argv = sys.argv try: opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l", ["help", "version", "trace", "count", "report", "no-report", "file=", "missing", "ignore-module=", "ignore-dir=", "coverdir=", "listfuncs",]) except getopt.error, msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) sys.exit(1) trace = 0 count = 0 report = 0 no_report = 0 counts_file = None missing = 0 ignore_modules = [] ignore_dirs = [] coverdir = None summary = 0 listfuncs = false for opt, val in opts: if opt == "--help": usage(sys.stdout) sys.exit(0) if opt == "--version": sys.stdout.write("trace 2.0\n") sys.exit(0) if opt == "-l" or opt == "--listfuncs": listfuncs = true continue if opt == "-t" or opt == "--trace": trace = 1 continue if opt == "-c" or opt == "--count": count = 1 continue if opt == "-r" or opt == "--report": report = 1 continue if opt == "-R" or opt == "--no-report": no_report = 1 continue if opt == "-f" or opt == "--file": counts_file = val continue if opt == "-m" or opt == "--missing": missing = 1 continue if opt == "-C" or opt == "--coverdir": coverdir = val continue if opt == "-s" or opt == "--summary": summary = 1 continue if opt == "--ignore-module": ignore_modules.append(val) continue if opt == "--ignore-dir": for s in val.split(os.pathsep): s = os.path.expandvars(s) # should I also call expanduser? (after all, could use $HOME) s = s.replace("$prefix", os.path.join(sys.prefix, "lib", "python" + sys.version[:3])) s = s.replace("$exec_prefix", os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3])) s = os.path.normpath(s) ignore_dirs.append(s) continue assert 0, "Should never get here" if listfuncs and (count or trace): _err_exit("cannot specify both --listfuncs and (--trace or --count)") if not count and not trace and not report and not listfuncs: _err_exit("must specify one of --trace, --count, --report or --listfuncs") if report and no_report: _err_exit("cannot specify both --report and --no-report") if report and not counts_file: _err_exit("--report requires a --file") if no_report and len(prog_argv) == 0: _err_exit("missing name of file to run") # everything is ready if report: results = CoverageResults(infile=counts_file, outfile=counts_file) results.write_results(missing, summary=summary, coverdir=coverdir) else: sys.argv = prog_argv progname = prog_argv[0] sys.path[0] = os.path.split(progname)[0] t = Trace(count, trace, countfuncs=listfuncs, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, outfile=counts_file) try: t.run('execfile(' + `progname` + ')') except IOError, err: _err_exit("Cannot run file %s because: %s" % (`sys.argv[0]`, err)) except SystemExit: pass results = t.results() if not no_report: results.write_results(missing, summary=summary, coverdir=coverdir)
listfuncs = true
listfuncs = True
def main(argv=None): import getopt if argv is None: argv = sys.argv try: opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l", ["help", "version", "trace", "count", "report", "no-report", "file=", "missing", "ignore-module=", "ignore-dir=", "coverdir=", "listfuncs",]) except getopt.error, msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) sys.exit(1) trace = 0 count = 0 report = 0 no_report = 0 counts_file = None missing = 0 ignore_modules = [] ignore_dirs = [] coverdir = None summary = 0 listfuncs = false for opt, val in opts: if opt == "--help": usage(sys.stdout) sys.exit(0) if opt == "--version": sys.stdout.write("trace 2.0\n") sys.exit(0) if opt == "-l" or opt == "--listfuncs": listfuncs = true continue if opt == "-t" or opt == "--trace": trace = 1 continue if opt == "-c" or opt == "--count": count = 1 continue if opt == "-r" or opt == "--report": report = 1 continue if opt == "-R" or opt == "--no-report": no_report = 1 continue if opt == "-f" or opt == "--file": counts_file = val continue if opt == "-m" or opt == "--missing": missing = 1 continue if opt == "-C" or opt == "--coverdir": coverdir = val continue if opt == "-s" or opt == "--summary": summary = 1 continue if opt == "--ignore-module": ignore_modules.append(val) continue if opt == "--ignore-dir": for s in val.split(os.pathsep): s = os.path.expandvars(s) # should I also call expanduser? (after all, could use $HOME) s = s.replace("$prefix", os.path.join(sys.prefix, "lib", "python" + sys.version[:3])) s = s.replace("$exec_prefix", os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3])) s = os.path.normpath(s) ignore_dirs.append(s) continue assert 0, "Should never get here" if listfuncs and (count or trace): _err_exit("cannot specify both --listfuncs and (--trace or --count)") if not count and not trace and not report and not listfuncs: _err_exit("must specify one of --trace, --count, --report or --listfuncs") if report and no_report: _err_exit("cannot specify both --report and --no-report") if report and not counts_file: _err_exit("--report requires a --file") if no_report and len(prog_argv) == 0: _err_exit("missing name of file to run") # everything is ready if report: results = CoverageResults(infile=counts_file, outfile=counts_file) results.write_results(missing, summary=summary, coverdir=coverdir) else: sys.argv = prog_argv progname = prog_argv[0] sys.path[0] = os.path.split(progname)[0] t = Trace(count, trace, countfuncs=listfuncs, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, outfile=counts_file) try: t.run('execfile(' + `progname` + ')') except IOError, err: _err_exit("Cannot run file %s because: %s" % (`sys.argv[0]`, err)) except SystemExit: pass results = t.results() if not no_report: results.write_results(missing, summary=summary, coverdir=coverdir)
if isdir(name) and not islink(name):
st = os.lstat(name) if stat.S_ISDIR(st[stat.ST_MODE]):
def walk(top, func, arg): """walk(top,func,arg) calls func(arg, d, files) for each directory "d"
self.socket.close()
def process_request(self, request, client_address): """Fork a new subprocess to process the request.""" self.collect_children() pid = os.fork() if pid: # Parent process if self.active_children is None: self.active_children = [] self.active_children.append(pid) return else: # Child process. # This must never return, hence os._exit()! try: self.finish_request(request, client_address) os._exit(0) except: try: self.socket.close() self.handle_error(request, client_address) finally: os._exit(1)
def __init__(self, s): self.__lines = s.split('\n')
def __init__(self, name, data, files=(), dirs=()): self.__name = name self.__data = data self.__files = files self.__dirs = dirs self.__lines = None def __setup(self): if self.__lines: return data = None for dir in self.__dirs: for file in self.__files: file = os.path.join(dir, file) try: fp = open(file) data = fp.read() fp.close() break except IOError: pass if data: break if not data: data = self.__data self.__lines = data.split('\n')
def __init__(self, s): self.__lines = s.split('\n') self.__linecnt = len(self.__lines)
return '' __builtin__.copyright = _Printer(sys.copyright) __builtin__.credits = _Printer( '''Python development is led by BeOpen PythonLabs (www.pythonlabs.com).''') def make_license(filename): try: return _Printer(open(filename).read()) except IOError: return None
__builtin__.copyright = _Printer("copyright", sys.copyright) __builtin__.credits = _Printer("credits", "Python development is led by BeOpen PythonLabs (www.pythonlabs.com).")
def __repr__(self): prompt = 'Hit Return for more, or q (and Return) to quit: ' lineno = 0 while 1: try: for i in range(lineno, lineno + self.MAXLINES): print self.__lines[i] except IndexError: break else: lineno += self.MAXLINES key = None while key is None: key = raw_input(prompt) if key not in ('', 'q'): key = None if key == 'q': break return ''
for dir in here, os.path.join(here, os.pardir), os.curdir: for file in "LICENSE.txt", "LICENSE": lic = make_license(os.path.join(dir, file)) if lic: break if lic: __builtin__.license = lic break else: __builtin__.license = _Printer('See http://hdl.handle.net/1895.22/1012')
__builtin__.license = _Printer( "license", "See http://www.pythonlabs.com/products/python2.0/license.html", ["LICENSE.txt", "LICENSE"], [here, os.path.join(here, os.pardir), os.curdir])
def make_license(filename): try: return _Printer(open(filename).read()) except IOError: return None
adlist = None
adlist = ""
def getrouteaddr(self): """Parse a route address (Return-path value).
result.append('\\') result.append(char)
if char == '\000': result.append(r'\000') else: result.append('\\' + char) else: result.append(char)
def escape(pattern): "Escape all non-alphanumeric characters in pattern." result = [] alphanum=string.letters+'_'+string.digits for char in pattern: if char not in alphanum: result.append('\\') result.append(char) return string.join(result, '')
while not self.state:
if not self.state:
def wait(self): self.posted.acquire() while not self.state: self.posted.wait() self.posted.release()
self.plist.CFBundleExecutable = self.name
def preProcess(self): self.plist.CFBundleExecutable = self.name resdir = pathjoin("Contents", "Resources") if self.executable is not None: if self.mainprogram is None: execpath = pathjoin(self.execdir, self.name) else: execpath = pathjoin(resdir, os.path.basename(self.executable)) self.files.append((self.executable, execpath)) # For execve wrapper setexecutable = setExecutableTemplate % os.path.basename(self.executable) else: setexecutable = "" # XXX for locals() call
python [options] command
python bundlebuilder.py [options] command
def pathjoin(*args): """Safe wrapper for os.path.join: asserts that all but the first argument are relative paths.""" for seg in args[1:]: assert seg[0] != "/" return os.path.join(*args)
b = (12,) c = (6, 6) d = (4, 4, 4) e = (3, 3, 3, 3)
b = (1,) c = (1, 2) d = (1, 2, 3) e = (1, 2, 3, 4)
def test_short_tuples(self): a = () b = (12,) c = (6, 6) d = (4, 4, 4) e = (3, 3, 3, 3) for proto in 0, 1, 2: for x in a, b, c, d, e: s = self.dumps(x, proto) y = self.loads(s) self.assertEqual(x, y, (proto, x, s, y))
if not debugger:
if not debugger and \ self.editwin.getvar("<<toggle-jit-stack-viewer>>"):
def run_module_event(self, event, debugger=None): if not self.editwin.get_saved(): tkMessageBox.showerror("Not saved", "Please save first!", master=self.editwin.text) self.editwin.text.focus_set() return filename = self.editwin.io.filename if not filename: tkMessageBox.showerror("No file name", "This window has no file name", master=self.editwin.text) self.editwin.text.focus_set() return modname, ext = os.path.splitext(os.path.basename(filename)) if sys.modules.has_key(modname): mod = sys.modules[modname] else: mod = imp.new_module(modname) sys.modules[modname] = mod mod.__file__ = filename saveout = sys.stdout saveerr = sys.stderr owin = OnDemandOutputWindow(self.editwin.flist) try: sys.stderr = PseudoFile(owin, "stderr") try: sys.stdout = PseudoFile(owin, "stdout") try: if debugger: debugger.run("execfile(%s)" % `filename`, mod.__dict__) else: execfile(filename, mod.__dict__) except: (sys.last_type, sys.last_value, sys.last_traceback) = sys.exc_info() linecache.checkcache() traceback.print_exc() if not debugger: from StackViewer import StackBrowser sv = StackBrowser(self.root, self.flist) finally: sys.stdout = saveout finally: sys.stderr = saveerr
to_convert = to_convert[:] to_convert.sort(key=len, reverse=True)
def __seqToRE(self, to_convert, directive): """Convert a list to a regex string for matching a directive.
def test_main():
def test_basic():
def test_main(): test_support.requires('network') if not hasattr(socket, "ssl"): raise test_support.TestSkipped("socket module has no ssl support") import urllib socket.RAND_status() try: socket.RAND_egd(1) except TypeError: pass else: print "didn't raise TypeError" socket.RAND_add("this is a random string", 75.0) f = urllib.urlopen('https://sf.net') buf = f.read() f.close()
if not self._dict['Download-URL']:
if not self._dict.get('Download-URL'):
def prerequisites(self): """Return a list of prerequisites for this package. The list contains 2-tuples, of which the first item is either a PimpPackage object or None, and the second is a descriptive string. The first item can be None if this package depends on something that isn't pimp-installable, in which case the descriptive string should tell the user what to do.""" rv = [] if not self._dict['Download-URL']: return [(None, "This package needs to be installed manually")] if not self._dict['Prerequisites']: return [] for item in self._dict['Prerequisites']: if type(item) == str: pkg = None descr = str(item) else: name = item['Name'] if item.has_key('Version'): name = name + '-' + item['Version'] if item.has_key('Flavor'): name = name + '-' + item['Flavor'] pkg = self._db.find(name) if not pkg: descr = "Requires unknown %s"%name else: descr = pkg.description() rv.append((pkg, descr)) return rv
fp = os.popen(cmd, "r")
dummy, fp = os.popen4(cmd, "r") dummy.close()
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 fp = os.popen(cmd, "r") while 1: line = fp.readline() if not line: break if output: output.write(line) rv = fp.close() return rv
cast = "(PyObject*(*)(void*))"
self.emit("{", depth) self.emit("int i, n = asdl_seq_LEN(%s);" % value, depth+1) self.emit("value = PyList_New(n);", depth+1) self.emit("if (!value) goto failed;", depth+1) self.emit("for(i = 0; i < n; i++)", depth+1) self.emit("PyList_SET_ITEM(value, i, ast2obj_%s((%s_ty)asdl_seq_GET(%s, i)));" % (field.type, field.type, value), depth+2, reflow=False) self.emit("}", depth)
def set(self, field, value, depth): if field.seq: if field.type.value == "cmpop": # XXX check that this cast is safe, i.e. works independent on whether # sizeof(cmpop_ty) != sizeof(void*) cast = "(PyObject*(*)(void*))" else: cast = "" self.emit("value = ast2obj_list(%s, %sast2obj_%s);" % (value, cast, field.type), depth) else: ctype = get_c_type(field.type) self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
cast = "" self.emit("value = ast2obj_list(%s, %sast2obj_%s);" % (value, cast, field.type), depth)
self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth)
def set(self, field, value, depth): if field.seq: if field.type.value == "cmpop": # XXX check that this cast is safe, i.e. works independent on whether # sizeof(cmpop_ty) != sizeof(void*) cast = "(PyObject*(*)(void*))" else: cast = "" self.emit("value = ast2obj_list(%s, %sast2obj_%s);" % (value, cast, field.type), depth) else: ctype = get_c_type(field.type) self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False)
if not string.find(value, "%("):
if string.find(value, "%(") >= 0:
def get(self, section, option, raw=0, vars=None): """Get an option value for a given section.
onoff = 0 else: onoff = 255 if self.barx: self.barx.HiliteControl(onoff) if self.bary: self.bary.HiliteControl(onoff)
if self.barx and self.barx_enabled: self.barx.HiliteControl(0) if self.bary and self.bary_enabled: self.bary.HiliteControl(0) else: if self.barx: self.barx.HiliteControl(255) if self.bary: self.bary.HiliteControl(255)
def do_activate(self, onoff, event): if onoff: onoff = 0 else: onoff = 255 if self.barx: self.barx.HiliteControl(onoff) if self.bary: self.bary.HiliteControl(onoff)
self.barx.SetControlValue(vx)
if vx == None: self.barx.HiliteControl(255) self.barx_enabled = 0 else: if not self.barx_enabled: self.barx_enabled = 1 if self.activated: self.barx.HiliteControl(0) self.barx.SetControlValue(vx)
def updatescrollbars(self): SetPort(self.wid) vx, vy = self.getscrollbarvalues() if self.barx: self.barx.SetControlValue(vx) if self.bary: self.bary.SetControlValue(vy)
self.bary.SetControlValue(vy)
if vy == None: self.bary.HiliteControl(255) self.bary_enabled = 0 else: if not self.bary_enabled: self.bary_enabled = 1 if self.activated: self.bary.HiliteControl(0) self.bary.SetControlValue(vy) def scalebarvalue(self, absmin, absmax, curmin, curmax): if curmin <= absmin and curmax >= absmax: return None if curmin <= absmin: return 0 if curmax >= absmax: return 32767 perc = float(curmin-absmin)/float(absmax-absmin) return int(perc*32767)
def updatescrollbars(self): SetPort(self.wid) vx, vy = self.getscrollbarvalues() if self.barx: self.barx.SetControlValue(vx) if self.bary: self.bary.SetControlValue(vy)
for i in range(3):
for count in range(3):
def test_trashcan(): # "trashcan" is a hack to prevent stack overflow when deallocating # very deeply nested tuples etc. It works in part by abusing the # type pointer and refcount fields, and that can yield horrible # problems when gc tries to traverse the structures. # If this test fails (as it does in 2.0, 2.1 and 2.2), it will # most likely die via segfault. gc.enable() N = 200 for i in range(3): t = [] for i in range(N): t = [t, Ouch()] u = [] for i in range(N): u = [u, Ouch()] v = {} for i in range(N): v = {1: v, 2: Ouch()} gc.disable()
if s1[-2:] == "\r\n": s1 = s1[:-2] + "\n" sys.stdout.write(s1)
sys.stdout.write(s1.replace("\r\n", "\n"))
def debug(msg): pass
if s2[-2:] == "\r\n": s2 = s2[:-2] + "\n" sys.stdout.write(s2)
sys.stdout.write(s2.replace("\r\n", "\n"))
def debug(msg): pass
pid, status = os.wait()
exited_pid, status = os.waitpid(pid, 0)
def test_lock_conflict(self): # Fork off a subprocess that will lock the file for 2 seconds, # unlock it, and then exit. if not hasattr(os, 'fork'): return pid = os.fork() if pid == 0: # In the child, lock the mailbox. self._box.lock() time.sleep(2) self._box.unlock() os._exit(0)
(typ, [data]) = <instance>.search(charset, criterium, ...)
(typ, [data]) = <instance>.search(charset, criterion, ...)
def search(self, charset, *criteria): """Search mailbox for matching messages.