rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.assertEqual(list(a), range(2, n))
self.assertEqual(list(a), range(100, n))
def irange(n): for i in xrange(n): yield i
try: class A(tee): pass except TypeError: pass else: self.fail("tee constructor should not be subclassable") a, b = tee(xrange(10)) self.assertRaises(TypeError, type(a)) self.assert_(a is iter(a))
self.assertRaises(TypeError, tee, [1,2], 3, 'x') a, b = tee('abc') c = type(a)('def') self.assertEqual(list(c), list('def')) a, b, c = tee(xrange(2000), 3) for i in xrange(100): self.assertEqual(a.next(), i) self.assertEqual(list(b), range(2000)) self.assertEqual([c.next(), c.next()], range(2)) self.assertEqual(list(a), range(100,2000)) self.assertEqual(list(c), range(2,2000)) a, b = tee('abc') c, d = tee(a) self.assert_(a is c)
def irange(n): for i in xrange(n): yield i
def test_tee(self): a = [] p, q = t = tee([a]*2) a += [a, p, q, t] p.next() del a, p, q, t
def test_starmap(self): a = [] self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
... return izip(a, islice(b, 1, None))
... try: ... b.next() ... except StopIteration: ... pass ... return izip(a, b)
>>> def pairwise(iterable):
start += stop
start += step
def frange(start, stop, step): while start <= stop: yield start start += stop
self.status = status = int(status)
try: self.status = status = int(status) if status < 100 or status > 999: raise BadStatusLine(line) except ValueError: raise BadStatusLine(line)
def begin(self): if self.msg is not None: # we've already started reading the response return
self.includepath = [':', INCLUDEDIR]
self.includepath = [os.curdir, INCLUDEDIR]
def initpaths(self): self.includepath = [':', INCLUDEDIR]
if MacOS:
if MacOS and CREATOR:
def initosspecifics(self): if MacOS: self.filetype = 'TEXT' self.filecreator = CREATOR else: self.filetype = self.filecreator = None
save_warnings_filters = warnings.filters[:] globals = func.func_globals if '__warningregistry__' in globals: del globals['__warningregistry__'] warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) warnings.filterwarnings("error", r""".*format requires.*""", DeprecationWarning)
def deprecated_err(func, *args): # The `warnings` module doesn't have an advertised way to restore # its filter list. Cheat. save_warnings_filters = warnings.filters[:] # Grrr, we need this function to warn every time. Without removing # the warningregistry, running test_tarfile then test_struct would fail # on 64-bit platforms. globals = func.func_globals if '__warningregistry__' in globals: del globals['__warningregistry__'] warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) warnings.filterwarnings("error", r""".*format requires.*""", DeprecationWarning) try: try: func(*args) except (struct.error, TypeError): pass except DeprecationWarning: if not PY_STRUCT_OVERFLOW_MASKING: raise TestFailed, "%s%s expected to raise struct.error" % ( func.__name__, args) else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args) finally: warnings.filters[:] = save_warnings_filters[:]
try: func(*args) except (struct.error, TypeError): pass except DeprecationWarning: if not PY_STRUCT_OVERFLOW_MASKING: raise TestFailed, "%s%s expected to raise struct.error" % ( func.__name__, args) else: raise TestFailed, "%s%s did not raise error" % (
func(*args) except (struct.error, TypeError): pass except DeprecationWarning: if not PY_STRUCT_OVERFLOW_MASKING: raise TestFailed, "%s%s expected to raise struct.error" % (
def deprecated_err(func, *args): # The `warnings` module doesn't have an advertised way to restore # its filter list. Cheat. save_warnings_filters = warnings.filters[:] # Grrr, we need this function to warn every time. Without removing # the warningregistry, running test_tarfile then test_struct would fail # on 64-bit platforms. globals = func.func_globals if '__warningregistry__' in globals: del globals['__warningregistry__'] warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) warnings.filterwarnings("error", r""".*format requires.*""", DeprecationWarning) try: try: func(*args) except (struct.error, TypeError): pass except DeprecationWarning: if not PY_STRUCT_OVERFLOW_MASKING: raise TestFailed, "%s%s expected to raise struct.error" % ( func.__name__, args) else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args) finally: warnings.filters[:] = save_warnings_filters[:]
finally: warnings.filters[:] = save_warnings_filters[:]
else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args) deprecated_err = with_warning_restore(deprecated_err)
def deprecated_err(func, *args): # The `warnings` module doesn't have an advertised way to restore # its filter list. Cheat. save_warnings_filters = warnings.filters[:] # Grrr, we need this function to warn every time. Without removing # the warningregistry, running test_tarfile then test_struct would fail # on 64-bit platforms. globals = func.func_globals if '__warningregistry__' in globals: del globals['__warningregistry__'] warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) warnings.filterwarnings("error", r""".*format requires.*""", DeprecationWarning) try: try: func(*args) except (struct.error, TypeError): pass except DeprecationWarning: if not PY_STRUCT_OVERFLOW_MASKING: raise TestFailed, "%s%s expected to raise struct.error" % ( func.__name__, args) else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args) finally: warnings.filters[:] = save_warnings_filters[:]
mime_header = regex.compile('\\([ \t(]\\)\\([-a-zA-Z0-9_+]*[\240-\377][-a-zA-Z0-9_+\240-\377]*\\)\\([ \t)]\\|$\\)')
mime_header = regex.compile('\\([ \t(]\\|^\\)\\([-a-zA-Z0-9_+]*[\240-\377][-a-zA-Z0-9_+\240-\377]*\\)\\([ \t)]\\|$\\)')
def mime_encode(line, header): '''Code a single line as quoted-printable. If header is set, quote some extra characters.''' if header: reg = mime_header_char else: reg = mime_char newline = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) line = line[1:] while 1: i = reg.search(line) if i < 0: break newline = newline + line[:i] + \ string.upper('=%02x' % ord(line[i])) line = line[i+1:] line = newline + line newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
QSIZE = 16 TIME = 5
format = SV.RGB8_FRAMES qsize = 2
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:')
rate = 2 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:')
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
QSIZE = string.atoi(arg)
qsize = string.atoi(arg)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
[nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg)
rate = string.atoi(arg) if rate < 2: sys.stderr.write('-r rate must be >= 2\n') sys.exit(2)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
v.BindGLWindow(win, SV.IN_REPLACE)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
recorded = 0
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
if recorded: gl.ringbell() continue gl.prefsize(x, y) gl.winconstraints() record(v, filename, audiofilename) recorded = 1 print 'Wait until "Done writing" is printed!'
info = format, x, y, qsize, rate record(v, info, filename, audiofilename)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
if not recorded: x, y = gl.getsize() print x, 'x', y v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE)
x, y = gl.getsize() print x, 'x', y v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
if not recorded: posix._exit(0) v.EndCapture()
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg) if args[2:]: sys.stderr.write('usage: Vrec [options] [file [audiofile]]\n') sys.exit(2) if args: filename = args[0] else: filename = 'film.video' if args[1:] and not audio: sys.stderr.write('-a turned on by appearance of 2nd file\n') audio = 1 if audio: if args[1:]: audiofilename = args[1] else: audiofilename = 'film.aiff' else: audiofilename = None gl.foreground() x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 print x, 'x', y gl.minsize(40, 30) gl.stepunit(8, 6) gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) win = gl.winopen(filename) x, y = gl.getsize() print x, 'x', y v = sv.OpenVideo() v.BindGLWindow(win, SV.IN_REPLACE) v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE) v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
def record(v, filename, audiofilename):
def record(v, info, filename, audiofilename):
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' + filename) v.StartCapture() t0 = time.millitimer() while not gl.qtest(): if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) buffer.append(None) # Sentinel gl.wintitle('(done) ' + filename)
x, y = gl.getsize()
format, x, y, qsize, rate = info fps = 59.64 tpf = 1000.0 / fps
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' + filename) v.StartCapture() t0 = time.millitimer() while not gl.qtest(): if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) buffer.append(None) # Sentinel gl.wintitle('(done) ' + filename)
buffer = [] thread.start_new_thread(saveframes, (vout, buffer))
MAXSIZE = 20 import Queue queue = Queue.Queue().init(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() thread.start_new_thread(saveframes, (vout, queue, done))
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' + filename) v.StartCapture() t0 = time.millitimer() while not gl.qtest(): if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) buffer.append(None) # Sentinel gl.wintitle('(done) ' + filename)
initaudio(audiofilename, buffer)
audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone)
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' + filename) v.StartCapture() t0 = time.millitimer() while not gl.qtest(): if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) buffer.append(None) # Sentinel gl.wintitle('(done) ' + filename)
v.StartCapture()
lastid = 0
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' + filename) v.StartCapture() t0 = time.millitimer() while not gl.qtest(): if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) buffer.append(None) # Sentinel gl.wintitle('(done) ' + filename)
if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y)
try: cd, id = v.GetCaptureData() except RuntimeError: time.millisleep(10) continue id = id + 2*rate lastid = id data = cd.InterleaveFields(1)
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' + filename) v.StartCapture() t0 = time.millitimer() while not gl.qtest(): if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) buffer.append(None) # Sentinel gl.wintitle('(done) ' + filename)
buffer.append(data, t) buffer.append(None)
queue.put(data, int(id*tpf)) t1 = time.millitimer() gl.wintitle('(busy) ' + filename) print lastid, 'fields in', t1-t0, 'msec', print '--', 0.1 * int(lastid * 10000.0 / (t1-t0)), 'fields/sec' if audiofilename: audiostop.append(None) audiodone.acquire_lock() v.EndContinuousCapture() queue.put(None) done.acquire_lock()
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' + filename) v.StartCapture() t0 = time.millitimer() while not gl.qtest(): if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) buffer.append(None) # Sentinel gl.wintitle('(done) ' + filename)
def saveframes(vout, buffer):
def saveframes(vout, queue, done):
def saveframes(vout, buffer): while 1: if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n') vout.close()
if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n')
x = queue.get() if not x: break data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing video\n')
def saveframes(vout, buffer): while 1: if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n') vout.close()
AQSIZE = 8000 def initaudio(filename, buffer):
AQSIZE = 8000 def initaudio(filename, stop, done):
def saveframes(vout, buffer): while 1: if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n') vout.close()
thread.start_new_thread(audiorecord, (afile, aport, buffer))
thread.start_new_thread(audiorecord, (afile, aport, stop, done))
def initaudio(filename, buffer): import thread, aiff afile = aiff.Aiff().init(filename, 'w') afile.nchannels = AL.MONO afile.sampwidth = AL.SAMPLE_8 params = [AL.INPUT_RATE, 0] al.getparams(AL.DEFAULT_DEVICE, params) print 'audio sampling rate =', params[1] afile.samprate = params[1] c = al.newconfig() c.setchannels(AL.MONO) c.setqueuesize(AQSIZE) c.setwidth(AL.SAMPLE_8) aport = al.openport(filename, 'r', c) thread.start_new_thread(audiorecord, (afile, aport, buffer))
def audiorecord(afile, aport, buffer): while buffer[-1:] <> [None]:
def audiorecord(afile, aport, stop, done): while not stop:
def audiorecord(afile, aport, buffer): while buffer[-1:] <> [None]: data = aport.readsamps(AQSIZE/2)
self.flags = []
self.flags = 0
def __init__(self):
def setflag(self, flag): if flag in self.flags: self.flags.append(flag)
def setflag(self, flag):
self.flags = []
def __init__(self, pattern, data=None):
lo = lo + i * av[0] hi = hi + j * av[1]
lo = lo + long(i) * av[0] hi = hi + long(j) * av[1]
def getwidth(self):
def set(self, flag): if not flag in self.flags: self.flags.append(flag) def reset(self, flag): if flag in self.flags: self.flags.remove(flag)
def set(self, flag):
self.string = list(string)
self.index = 0 self.string = string
def __init__(self, string):
if not self.string:
if self.index >= len(self.string):
def __next(self):
char = self.string[0]
char = self.string[self.index]
def __next(self):
c = self.string[1]
c = self.string[self.index + 1]
def __next(self):
try: if c == "x": for i in xrange(2, sys.maxint): c = self.string[i] if str(c) not in HEXDIGITS: break char = char + c elif str(c) in DIGITS: for i in xrange(2, sys.maxint): c = self.string[i] if str(c) not in DIGITS: break char = char + c except IndexError: pass del self.string[0:len(char)]
self.index = self.index + len(char)
def __next(self):
def _fixescape(escape, character_class=0): if character_class: code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code = ESCAPES.get(escape)
def _group(escape, state): try: group = int(escape[1:]) if group and group < state.groups: return group except ValueError: pass return None def _class_escape(source, escape): code = ESCAPES.get(escape)
def _fixescape(escape, character_class=0): # convert escape to (type, value) if character_class: # inside a character class, we'll look in the character # escapes dictionary first code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code = ESCAPES.get(escape) if code: return code if not character_class: try: group = int(escape[1:]) # FIXME: only valid if group <= current number of groups return GROUP, group except ValueError: pass try: if escape[1:2] == "x": escape = escape[2:] return LITERAL, chr(int(escape[-2:], 16) & 0xff) elif str(escape[1:2]) in DIGITS: return LITERAL, chr(int(escape[1:], 8) & 0xff) elif len(escape) == 2: return LITERAL, escape[1] except ValueError: pass raise SyntaxError, "bogus escape: %s" % repr(escape)
if not character_class: try: group = int(escape[1:]) return GROUP, group except ValueError: pass
code = CATEGORIES.get(escape) if code: return code
def _fixescape(escape, character_class=0): # convert escape to (type, value) if character_class: # inside a character class, we'll look in the character # escapes dictionary first code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code = ESCAPES.get(escape) if code: return code if not character_class: try: group = int(escape[1:]) # FIXME: only valid if group <= current number of groups return GROUP, group except ValueError: pass try: if escape[1:2] == "x": escape = escape[2:] return LITERAL, chr(int(escape[-2:], 16) & 0xff) elif str(escape[1:2]) in DIGITS: return LITERAL, chr(int(escape[1:], 8) & 0xff) elif len(escape) == 2: return LITERAL, escape[1] except ValueError: pass raise SyntaxError, "bogus escape: %s" % repr(escape)
return LITERAL, chr(int(escape[-2:], 16) & 0xff) elif str(escape[1:2]) in DIGITS: return LITERAL, chr(int(escape[1:], 8) & 0xff) elif len(escape) == 2:
return LITERAL, chr(int(escape[-4:], 16) & 0xff) elif str(escape[1:2]) in OCTDIGITS: while source.next in OCTDIGITS: escape = escape + source.get() escape = escape[1:] return LITERAL, chr(int(escape[-6:], 8) & 0xff) if len(escape) == 2:
def _fixescape(escape, character_class=0): # convert escape to (type, value) if character_class: # inside a character class, we'll look in the character # escapes dictionary first code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code = ESCAPES.get(escape) if code: return code if not character_class: try: group = int(escape[1:]) # FIXME: only valid if group <= current number of groups return GROUP, group except ValueError: pass try: if escape[1:2] == "x": escape = escape[2:] return LITERAL, chr(int(escape[-2:], 16) & 0xff) elif str(escape[1:2]) in DIGITS: return LITERAL, chr(int(escape[1:], 8) & 0xff) elif len(escape) == 2: return LITERAL, escape[1] except ValueError: pass raise SyntaxError, "bogus escape: %s" % repr(escape)
def _branch(subpattern, items):
def _escape(source, escape, state): code = CATEGORIES.get(escape) if code: return code code = ESCAPES.get(escape) if code: return code try: if escape[1:2] == "x": while source.next in HEXDIGITS: escape = escape + source.get() escape = escape[2:] return LITERAL, chr(int(escape[-4:], 16) & 0xff) elif str(escape[1:2]) in DIGITS: while 1: group = _group(escape, state) if group: if (not source.next or not _group(escape + source.next, state)): return GROUP, group escape = escape + source.get() elif source.next in OCTDIGITS: escape = escape + source.get() else: break escape = escape[1:] return LITERAL, chr(int(escape[-6:], 8) & 0xff) if len(escape) == 2: return LITERAL, escape[1] except ValueError: pass raise SyntaxError, "bogus escape: %s" % repr(escape) def _branch(pattern, items):
def _branch(subpattern, items): # form a branch operator from a set of items (FIXME: move this # optimization to the compiler module!) # check if all items share a common prefix while 1: prefix = None for item in items: if not item: break if prefix is None: prefix = item[0] elif item[0] != prefix: break else: # all subitems start with a common "prefix". # move it out of the branch for item in items: del item[0] subpattern.append(prefix) continue # check next one break # check if the branch can be replaced by a character set for item in items: if len(item) != 1 or item[0][0] != LITERAL: break else: # we can store this as a character set instead of a # branch (FIXME: use a range if possible) set = [] for item in items: set.append(item[0]) subpattern.append((IN, set)) return subpattern.append((BRANCH, (None, items)))
return
return subpattern
def _branch(subpattern, items): # form a branch operator from a set of items (FIXME: move this # optimization to the compiler module!) # check if all items share a common prefix while 1: prefix = None for item in items: if not item: break if prefix is None: prefix = item[0] elif item[0] != prefix: break else: # all subitems start with a common "prefix". # move it out of the branch for item in items: del item[0] subpattern.append(prefix) continue # check next one break # check if the branch can be replaced by a character set for item in items: if len(item) != 1 or item[0][0] != LITERAL: break else: # we can store this as a character set instead of a # branch (FIXME: use a range if possible) set = [] for item in items: set.append(item[0]) subpattern.append((IN, set)) return subpattern.append((BRANCH, (None, items)))
def _parse(source, pattern, flags=()):
return subpattern def _parse(source, state, flags=0):
def _branch(subpattern, items): # form a branch operator from a set of items (FIXME: move this # optimization to the compiler module!) # check if all items share a common prefix while 1: prefix = None for item in items: if not item: break if prefix is None: prefix = item[0] elif item[0] != prefix: break else: # all subitems start with a common "prefix". # move it out of the branch for item in items: del item[0] subpattern.append(prefix) continue # check next one break # check if the branch can be replaced by a character set for item in items: if len(item) != 1 or item[0][0] != LITERAL: break else: # we can store this as a character set instead of a # branch (FIXME: use a range if possible) set = [] for item in items: set.append(item[0]) subpattern.append((IN, set)) return subpattern.append((BRANCH, (None, items)))
subpattern = SubPattern(pattern) this = None
subpattern = SubPattern(state)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
code1 = _fixescape(this, 1)
code1 = _class_escape(source, this)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
code2 = _fixescape(this, 1)
code2 = _class_escape(source, this)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
min, max = 0, sys.maxint
min, max = 0, MAXREPEAT
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
min, max = 1, sys.maxint
min, max = 1, MAXREPEAT
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
index = len(subpattern)-1 while subpattern[index][0] is MARK: index = index - 1 item = subpattern[index:index+1]
item = subpattern[-1:]
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
subpattern[index] = (MIN_REPEAT, (min, max, item))
subpattern[-1] = (MIN_REPEAT, (min, max, item))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
subpattern[index] = (MAX_REPEAT, (min, max, item))
subpattern[-1] = (MAX_REPEAT, (min, max, item))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
if char is None or char == ">":
if char is None: raise SyntaxError, "unterminated name" if char == ">":
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
elif source.match_set("iI"): pattern.setflag("i") elif source.match_set("lL"): pattern.setflag("l") elif source.match_set("mM"): pattern.setflag("m") elif source.match_set("sS"): pattern.setflag("s") elif source.match_set("xX"): pattern.setflag("x")
elif source.match(" while 1: char = source.get() if char is None or char == ")": break else: while FLAGS.has_key(source.next): state.flags = state.flags | FLAGS[source.get()]
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
group = pattern.getgroup(name) if group: subpattern.append((MARK, (group-1)*2))
group = state.getgroup(name)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
p = _parse(source, pattern, flags)
p = _parse(source, state, flags)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
_branch(subpattern, b) else: subpattern.append((SUBPATTERN, (group, p)))
p = _branch(state, b) subpattern.append((SUBPATTERN, (group, p)))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
if group: subpattern.append((MARK, (group-1)*2+1))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
code =_fixescape(this)
code = _escape(source, this, state)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
def parse(source, flags=()): s = Tokenizer(source) g = Pattern()
def parse(pattern, flags=0): source = Tokenizer(pattern) state = State()
def parse(source, flags=()): s = Tokenizer(source) g = Pattern() b = [] while 1: p = _parse(s, g, flags) tail = s.get() if tail == "|": b.append(p) elif tail == ")": raise SyntaxError, "unbalanced parenthesis" elif tail is None: if b: b.append(p) p = SubPattern(g) _branch(p, b) break else: raise SyntaxError, "bogus characters at end of regular expression" return p
p = _parse(s, g, flags) tail = s.get()
p = _parse(source, state, flags) tail = source.get()
def parse(source, flags=()): s = Tokenizer(source) g = Pattern() b = [] while 1: p = _parse(s, g, flags) tail = s.get() if tail == "|": b.append(p) elif tail == ")": raise SyntaxError, "unbalanced parenthesis" elif tail is None: if b: b.append(p) p = SubPattern(g) _branch(p, b) break else: raise SyntaxError, "bogus characters at end of regular expression" return p
p = SubPattern(g) _branch(p, b)
p = _branch(state, b)
def parse(source, flags=()): s = Tokenizer(source) g = Pattern() b = [] while 1: p = _parse(s, g, flags) tail = s.get() if tail == "|": b.append(p) elif tail == ")": raise SyntaxError, "unbalanced parenthesis" elif tail is None: if b: b.append(p) p = SubPattern(g) _branch(p, b) break else: raise SyntaxError, "bogus characters at end of regular expression" return p
for dir in sys.path:
path = sys.path try: path = [os.path.dirname(__file__)] + path except NameError: pass for dir in path:
def get_qualified_path(name): """ return a more qualified path to name""" import sys import os for dir in sys.path: fullname = os.path.join(dir, name) if os.path.exists(fullname): return fullname return name
self._lookup()
assert self._toc is not None self._file.seek(0, 2) cur_len = self._file.tell() if cur_len != self._file_length: raise ExternalClashError('Size of mailbox file changed ' '(expected %i, found %i)' % (self._file_length, cur_len))
def flush(self): """Write any pending changes to disk.""" if not self._pending: return self._lookup() new_file = _create_temporary(self._path) try: new_toc = {} self._pre_mailbox_hook(new_file) for key in sorted(self._toc.keys()): start, stop = self._toc[key] self._file.seek(start) self._pre_message_hook(new_file) new_start = new_file.tell() while True: buffer = self._file.read(min(4096, stop - self._file.tell())) if buffer == '': break new_file.write(buffer) new_toc[key] = (new_start, new_file.tell()) self._post_message_hook(new_file) except: new_file.close() os.remove(new_file.name) raise _sync_close(new_file) # self._file is about to get replaced, so no need to sync. self._file.close() try: os.rename(new_file.name, self._path) except OSError, e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(self._path) os.rename(new_file.name, self._path) else: raise self._file = open(self._path, 'rb+') self._toc = new_toc self._pending = False if self._locked: _lock_file(self._file, dotlock=False)
self._file.seek(0, 2) self._file_length = self._file.tell()
def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 label_lists = [] while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == '\037\014' + os.linesep: if len(stops) < len(starts): stops.append(line_pos - len(os.linesep)) starts.append(next_pos) labels = [label.strip() for label in self._file.readline()[1:].split(',') if label.strip() != ''] label_lists.append(labels) elif line == '\037' or line == '\037' + os.linesep: if len(stops) < len(starts): stops.append(line_pos - len(os.linesep)) elif line == '': stops.append(line_pos - len(os.linesep)) break self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc)
exec("""def __%(method)s__(self, *args):
exec """def __%(method)s__(self, *args):
exec("""def __%(method)s__(self, *args): print "__%(method)s__:", args
"""%locals(), AllTests.__dict__);
"""%locals() in AllTests.__dict__
exec("""def __%(method)s__(self, *args): print "__%(method)s__:", args
f.seek(0)
def test_truncate(self): eq = self.assertEqual f = self.MODULE.StringIO() f.write(self._lines) f.seek(10) f.truncate() eq(f.getvalue(), 'abcdefghij') f.seek(0) f.truncate(5) eq(f.getvalue(), 'abcde') f.close() self.assertRaises(ValueError, f.write, 'frobnitz')
def testMultiply(self);
def testMultiply(self):
def testMultiply(self); self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40)
contain tuples of (testcase, exceptioninfo), where exceptioninfo is a tuple of values as returned by sys.exc_info().
contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred
def testMultiply(self); self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40)
"Called when an error has occurred" self.errors.append((test, err))
self.errors.append((test, self._exc_info_to_string(err)))
def addError(self, test, err): "Called when an error has occurred" self.errors.append((test, err))
"Called when a failure has occurred" self.failures.append((test, err))
self.failures.append((test, self._exc_info_to_string(err)))
def addFailure(self, test, err): "Called when a failure has occurred" self.failures.append((test, err))
for line in apply(traceback.format_exception, err): for l in string.split(line,"\n")[:-1]: self.stream.writeln("%s" % l)
self.stream.writeln("%s" % err)
def printErrorList(self, flavour, errors): for test, err in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) self.stream.writeln(self.separator2) for line in apply(traceback.format_exception, err): for l in string.split(line,"\n")[:-1]: self.stream.writeln("%s" % l)
spec_file.append('Source0: %{name}-%{version}.tar.bz2')
spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2')
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
spec_file.append('Source0: %{name}-%{version}.tar.gz')
spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
('prep', 'prep_script', "%setup"),
('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
origin_req_host = cookielib.request_host(self)
origin_req_host = request_host(self)
def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {} for key, value in headers.items(): self.add_header(key, value) self.unredirected_hdrs = {} if origin_req_host is None: origin_req_host = cookielib.request_host(self) self.origin_req_host = origin_req_host self.unverifiable = unverifiable
if inspect.isclass(check):
if isclass(check):
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP and FTP. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor] if hasattr(httplib, 'HTTPS'): default_classes.append(HTTPSHandler) skip = [] for klass in default_classes: for check in handlers: if inspect.isclass(check): if issubclass(check, klass): skip.append(klass) elif isinstance(check, klass): skip.append(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if inspect.isclass(h): h = h() opener.add_handler(h) return opener
if inspect.isclass(h):
if isclass(h):
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP and FTP. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor] if hasattr(httplib, 'HTTPS'): default_classes.append(HTTPSHandler) skip = [] for klass in default_classes: for check in handlers: if inspect.isclass(check): if issubclass(check, klass): skip.append(klass) elif isinstance(check, klass): skip.append(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if inspect.isclass(h): h = h() opener.add_handler(h) return opener
thingie = pickle.load(open(self.infile, 'r')) if isinstance(thingie, dict): self.update(self.__class__(thingie)) elif isinstance(thingie, tuple) and len(thingie) == 2: counts, calledfuncs = thingie self.update(self.__class__(counts, calledfuncs)) except (IOError, EOFError), err:
counts, calledfuncs = pickle.load(open(self.infile, 'r')) self.update(self.__class__(counts, calledfuncs)) except (IOError, EOFError, ValueError), err:
def __init__(self, counts=None, calledfuncs=None, infile=None, outfile=None): self.counts = counts if self.counts is None: self.counts = {} self.counter = self.counts.copy() # map (filename, lineno) to count self.calledfuncs = calledfuncs if self.calledfuncs is None: self.calledfuncs = {} self.calledfuncs = self.calledfuncs.copy() self.infile = infile self.outfile = outfile if self.infile: # Try and merge existing counts file. # This code understand a couple of old trace.py formats. try: thingie = pickle.load(open(self.infile, 'r')) if isinstance(thingie, dict): self.update(self.__class__(thingie)) elif isinstance(thingie, tuple) and len(thingie) == 2: counts, calledfuncs = thingie self.update(self.__class__(counts, calledfuncs)) except (IOError, EOFError), err: print >> sys.stderr, ("Skipping counts file %r: %s" % (self.infile, err)) except pickle.UnpicklingError: self.update(self.__class__(marshal.load(open(self.infile))))
bool,
def update(self): self.w.browser.update()
items = map(None, range(len(seq)), seq) items = map(lambda (k, v), type = type, simp = SIMPLE_TYPES, indent = indent: (k, v, not type(v) in simp, indent), items) return items
return [(i, v, not isinstance(v, SIMPLE_TYPES), indent) for i, v in enumerate(seq)]
def unpack_sequence(seq, indent = 0): items = map(None, range(len(seq)), seq) items = map(lambda (k, v), type = type, simp = SIMPLE_TYPES, indent = indent: (k, v, not type(v) in simp, indent), items) return items
def buildappbundle(executable, output=None, copyfunc=None, creator=None, plist=None, nib=None, resources=None): if not output: output = os.path.split(executable)[1] + '.app' if not copyfunc: copyfunc = shutil.copy2 if not creator: creator='????' if not resources: resources = [] if nib: resources = resources + [nib] if not os.path.isdir(output): os.mkdir(output) contents = os.path.join(output, 'Contents') if not os.path.isdir(contents): os.mkdir(contents) macos = os.path.join(contents, 'MacOS') if not os.path.isdir(macos): os.mkdir(macos) shortname = os.path.split(executable)[1] execname = os.path.join(macos, shortname) try: os.remove(execname) except OSError: pass copyfunc(executable, execname) pkginfo = os.path.join(contents, 'PkgInfo') open(pkginfo, 'wb').write('APPL'+creator) if plist: plistdata = open(plist).read() else: if not nib: nibname = "" else: nibname, ext = os.path.splitext(os.path.split(nib)[1]) if ext == '.lproj': files = os.listdir(nib) for f in files: if f[-4:] == '.nib': nibname = os.path.split(f)[1][:-4] break else: nibname = "" if nibname: cocoainfo = """ <key>NSMainNibFile</key> <string>%s</string> <key>NSPrincipalClass</key> <string>NSApplication</string>""" % nibname else: cocoainfo = "" plistdata = \ """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd"> <plist version="0.9"> <dict> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>%s</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>%s</string> <key>CFBundleVersion</key> <string>0.1</string> %s </dict> </plist> """ % (shortname, creator, cocoainfo) infoplist = os.path.join(contents, 'Info.plist') open(infoplist, 'w').write(plistdata) if resources: resdir = os.path.join(contents, 'Resources') if not os.path.isdir(resdir): os.mkdir(resdir) for src in resources: dst = os.path.join(resdir, os.path.split(src)[1]) if os.path.isdir(src): shutil.copytree(src, dst) else: shutil.copy2(src, dst)
def buildappbundle(executable, output=None, copyfunc=None, creator=None, plist=None, nib=None, resources=None): if not output: output = os.path.split(executable)[1] + '.app' if not copyfunc: copyfunc = shutil.copy2 if not creator: creator='????' if not resources: resources = [] if nib: resources = resources + [nib] # # Create the main directory structure # if not os.path.isdir(output): os.mkdir(output) contents = os.path.join(output, 'Contents') if not os.path.isdir(contents): os.mkdir(contents) macos = os.path.join(contents, 'MacOS') if not os.path.isdir(macos): os.mkdir(macos) # # Create the executable # shortname = os.path.split(executable)[1] execname = os.path.join(macos, shortname) try: os.remove(execname) except OSError: pass copyfunc(executable, execname) # # Create the PkgInfo file # pkginfo = os.path.join(contents, 'PkgInfo') open(pkginfo, 'wb').write('APPL'+creator) if plist: # A plist file is specified. Read it. plistdata = open(plist).read() else: # # If we have a main NIB we create the extra Cocoa specific info for the plist file # if not nib: nibname = "" else: nibname, ext = os.path.splitext(os.path.split(nib)[1]) if ext == '.lproj': # Special case: if the main nib is a .lproj we assum a directory # and use the first nib from there files = os.listdir(nib) for f in files: if f[-4:] == '.nib': nibname = os.path.split(f)[1][:-4] break else: nibname = "" if nibname: cocoainfo = """ <key>NSMainNibFile</key> <string>%s</string> <key>NSPrincipalClass</key> <string>NSApplication</string>""" % nibname else: cocoainfo = "" plistdata = \
print "buildappbundle creates an application bundle" print "Usage:" print " buildappbundle [options] executable" print "Options:" print " --output o Output file; default executable with .app appended, short -o" print " --link Symlink the executable (default: copy), short -l" print " --plist file Plist file (default: generate one), short -p" print " --nib file Main nib file or lproj folder for Cocoa program, short -n" print " --resource r Extra resource file to be copied to Resources, short -r" print " --creator c 4-char creator code (default: ????), short -c" print " --help This message, short -?"
print __doc__
def usage(): print "buildappbundle creates an application bundle" print "Usage:" print " buildappbundle [options] executable" print "Options:" print " --output o Output file; default executable with .app appended, short -o" print " --link Symlink the executable (default: copy), short -l" print " --plist file Plist file (default: generate one), short -p" print " --nib file Main nib file or lproj folder for Cocoa program, short -n" print " --resource r Extra resource file to be copied to Resources, short -r" print " --creator c 4-char creator code (default: ????), short -c" print " --help This message, short -?" sys.exit(1)
output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help")
output = None symlink = 0 creator = "????" plist = None nib = None resources = [] verbosity = 0 SHORTOPTS = "o:ln:r:p:c:v?h" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help", "verbose")
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for opt, arg in options: if opt in ('-o', '--output'): output = arg elif opt in ('-l', '--link'): copyfunc = os.symlink elif opt in ('-n', '--nib'): nib = arg elif opt in ('-r', '--resource'): resources.append(arg) elif opt in ('-c', '--creator'): creator = arg elif opt in ('-p', '--plist'): plist = arg elif opt in ('-?', '--help'): usage() buildappbundle(args[0], output=output, copyfunc=copyfunc, creator=creator, plist=plist, resources=resources)
copyfunc = os.symlink
symlink = 1
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for opt, arg in options: if opt in ('-o', '--output'): output = arg elif opt in ('-l', '--link'): copyfunc = os.symlink elif opt in ('-n', '--nib'): nib = arg elif opt in ('-r', '--resource'): resources.append(arg) elif opt in ('-c', '--creator'): creator = arg elif opt in ('-p', '--plist'): plist = arg elif opt in ('-?', '--help'): usage() buildappbundle(args[0], output=output, copyfunc=copyfunc, creator=creator, plist=plist, resources=resources)
elif opt in ('-?', '--help'):
elif opt in ('-v', '--verbose'): verbosity += 1 elif opt in ('-?', '-h', '--help'):
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for opt, arg in options: if opt in ('-o', '--output'): output = arg elif opt in ('-l', '--link'): copyfunc = os.symlink elif opt in ('-n', '--nib'): nib = arg elif opt in ('-r', '--resource'): resources.append(arg) elif opt in ('-c', '--creator'): creator = arg elif opt in ('-p', '--plist'): plist = arg elif opt in ('-?', '--help'): usage() buildappbundle(args[0], output=output, copyfunc=copyfunc, creator=creator, plist=plist, resources=resources)
buildappbundle(args[0], output=output, copyfunc=copyfunc, creator=creator, plist=plist, resources=resources)
if output is not None: builddir, bundlename = os.path.split(output) else: builddir = os.curdir bundlename = None if plist is not None: plist = Plist.fromFile(plist) builder = AppBuilder(name=bundlename, executable=executable, builddir=builddir, creator=creator, plist=plist, resources=resources, symlink=symlink, verbosity=verbosity) if nib is not None: resources.append(nib) nibname, ext = os.path.splitext(os.path.basename(nib)) if ext == '.lproj': files = os.listdir(nib) for f in files: if f[-4:] == '.nib': nibname = os.path.split(f)[1][:-4] break else: nibname = "" if nibname: builder.plist.NSMainNibFile = nibname if not hasattr(builder.plist, "NSPrincipalClass"): builder.plist.NSPrincipalClass = "NSApplication" builder.setup() builder.build()
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for opt, arg in options: if opt in ('-o', '--output'): output = arg elif opt in ('-l', '--link'): copyfunc = os.symlink elif opt in ('-n', '--nib'): nib = arg elif opt in ('-r', '--resource'): resources.append(arg) elif opt in ('-c', '--creator'): creator = arg elif opt in ('-p', '--plist'): plist = arg elif opt in ('-?', '--help'): usage() buildappbundle(args[0], output=output, copyfunc=copyfunc, creator=creator, plist=plist, resources=resources)
fullname = os.path.join(dirname, basename)
def updatecache(filename): """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list.""" if cache.has_key(filename): del cache[filename] if not filename or filename[0] + filename[-1] == '<>': return [] fullname = filename try: stat = os.stat(fullname) except os.error, msg: # Try looking through the module search path basename = os.path.split(filename)[1] for dirname in sys.path: fullname = os.path.join(dirname, basename) try: stat = os.stat(fullname) break except os.error: pass else: # No luck
stat = os.stat(fullname) break except os.error:
fullname = os.path.join(dirname, basename) except (TypeError, AttributeError):
def updatecache(filename): """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list.""" if cache.has_key(filename): del cache[filename] if not filename or filename[0] + filename[-1] == '<>': return [] fullname = filename try: stat = os.stat(fullname) except os.error, msg: # Try looking through the module search path basename = os.path.split(filename)[1] for dirname in sys.path: fullname = os.path.join(dirname, basename) try: stat = os.stat(fullname) break except os.error: pass else: # No luck
interp_path = os.path.join(sys.exec_prefix, "bin", "python")
interp_path = os.path.join(sys.exec_prefix, "Resources", "Python.app", "Contents", "MacOS", "Python") if not os.path.exists(interp_path): interp_path = os.path.join(sys.exec_prefix, "bin", "python")
def _run_with_cl_interpreter(self): import Terminal interp_path = os.path.join(sys.exec_prefix, "bin", "python") file_path = self.path if not os.path.exists(interp_path): # This "can happen" if we are running IDE under MacPython-OS9. raise W.AlertError, "Can't find command-line Python" cmd = '"%s" "%s" ; exit' % (interp_path, file_path) t = Terminal.Terminal() t.do_script(with_command=cmd)
t.do_script(with_command=cmd)
t.do_script(cmd)
def _run_with_cl_interpreter(self): import Terminal interp_path = os.path.join(sys.exec_prefix, "bin", "python") file_path = self.path if not os.path.exists(interp_path): # This "can happen" if we are running IDE under MacPython-OS9. raise W.AlertError, "Can't find command-line Python" cmd = '"%s" "%s" ; exit' % (interp_path, file_path) t = Terminal.Terminal() t.do_script(with_command=cmd)
if time.strftime(directive, time_tuple).find('00'):
if '00' in time.strftime(directive, time_tuple):
def __calc_date_time(self): # Set self.date_time, self.date, & self.time by using # time.strftime().
list.append('%s: %s\n' % (str(stype), str(value))) return list
list.append('%s: %s\n' % (str(stype), _some_str(value))) return list def _some_str(value): try: return str(value) except: return '<unprintable %s object>' % type(value).__name__
def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.""" list = [] if type(etype) == types.ClassType: stype = etype.__name__ else: stype = etype if value is None: list.append(str(stype) + '\n') else: if etype is SyntaxError: try: msg, (filename, lineno, offset, line) = value except: pass else: if not filename: filename = "<string>" list.append(' File "%s", line %d\n' % (filename, lineno)) i = 0 while i < len(line) and \ line[i] in string.whitespace: i = i+1 list.append(' %s\n' % string.strip(line)) s = ' ' for c in line[i:offset-1]: if c in string.whitespace: s = s + c else: s = s + ' ' list.append('%s^\n' % s) value = msg list.append('%s: %s\n' % (str(stype), str(value))) return list