rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
def addDataToDB(self, d):
|
def addDataToDB(self, d, txn=None):
|
def addDataToDB(self, d): for key, value in musicdata.items(): if type(self.keytype) == type(''): key = "%02d" % key d.put(key, string.join(value, '|'))
|
d.put(key, string.join(value, '|')) def createDB(self):
|
d.put(key, string.join(value, '|'), txn=txn) def createDB(self, txn=None):
|
def addDataToDB(self, d): for key, value in musicdata.items(): if type(self.keytype) == type(''): key = "%02d" % key d.put(key, string.join(value, '|'))
|
db.DB_CREATE | db.DB_THREAD)
|
db.DB_CREATE | db.DB_THREAD | self.dbFlags, txn=txn)
|
def createDB(self): self.primary = db.DB(self.env) self.primary.set_get_returns_none(2) self.primary.open(self.filename, "primary", self.dbtype, db.DB_CREATE | db.DB_THREAD)
|
db.DB_CREATE | db.DB_THREAD)
|
db.DB_CREATE | db.DB_THREAD | self.dbFlags)
|
def test01_associateWithDB(self): if verbose: print '\n', '-=' * 30 print "Running %s.test01_associateWithDB..." % \ self.__class__.__name__
|
db.DB_CREATE | db.DB_THREAD)
|
db.DB_CREATE | db.DB_THREAD | self.dbFlags)
|
def test02_associateAfterDB(self): if verbose: print '\n', '-=' * 30 print "Running %s.test02_associateAfterDB..." % \ self.__class__.__name__
|
def finish_test(self, secDB):
|
def finish_test(self, secDB, txn=None):
|
def finish_test(self, secDB): # 'Blues' should not be in the secondary database vals = secDB.pget('Blues') assert vals == None, vals
|
vals = secDB.pget('Blues')
|
vals = secDB.pget('Blues', txn=txn)
|
def finish_test(self, secDB): # 'Blues' should not be in the secondary database vals = secDB.pget('Blues') assert vals == None, vals
|
vals = secDB.pget('Unknown')
|
vals = secDB.pget('Unknown', txn=txn)
|
def finish_test(self, secDB): # 'Blues' should not be in the secondary database vals = secDB.pget('Blues') assert vals == None, vals
|
c = self.getDB().cursor()
|
c = self.getDB().cursor(txn)
|
def finish_test(self, secDB): # 'Blues' should not be in the secondary database vals = secDB.pget('Blues') assert vals == None, vals
|
c = secDB.cursor()
|
c = secDB.cursor(txn)
|
def finish_test(self, secDB): # 'Blues' should not be in the secondary database vals = secDB.pget('Blues') assert vals == None, vals
|
try: thunk() except TestFailed: if verbose: print "failed (expected %s but got %s)" % (result, test_result) raise TestFailed, name else: if verbose: print "ok"
|
thunk() if verbose: print "ok"
|
def run_test(name, thunk): if verbose: print "testing %s..." % name, try: thunk() except TestFailed: if verbose: print "failed (expected %s but got %s)" % (result, test_result) raise TestFailed, name else: if verbose: print "ok"
|
if gc.collect() != 1: raise TestFailed
|
expect(gc.collect(), 1, "list")
|
def test_list(): l = [] l.append(l) gc.collect() del l if gc.collect() != 1: raise TestFailed
|
if gc.collect() != 1: raise TestFailed
|
expect(gc.collect(), 1, "dict")
|
def test_dict(): d = {} d[1] = d gc.collect() del d if gc.collect() != 1: raise TestFailed
|
if gc.collect() != 2: raise TestFailed
|
expect(gc.collect(), 2, "tuple")
|
def test_tuple(): # since tuples are immutable we close the loop with a list l = [] t = (l,) l.append(t) gc.collect() del t del l if gc.collect() != 2: raise TestFailed
|
if gc.collect() == 0: raise TestFailed
|
expect_not(gc.collect(), 0, "class")
|
def test_class(): class A: pass A.a = A gc.collect() del A if gc.collect() == 0: raise TestFailed
|
if gc.collect() == 0: raise TestFailed
|
expect_not(gc.collect(), 0, "instance")
|
def test_instance(): class A: pass a = A() a.a = a gc.collect() del a if gc.collect() == 0: raise TestFailed
|
if gc.collect() == 0: raise TestFailed
|
expect_not(gc.collect(), 0, "method")
|
def __init__(self): self.init = self.__init__
|
if gc.collect() == 0: raise TestFailed
|
expect_not(gc.collect(), 0, "finalizer")
|
def __del__(self): pass
|
raise TestFailed
|
raise TestFailed, "didn't find obj in garbage (finalizer)"
|
def __del__(self): pass
|
if gc.collect() != 2: raise TestFailed
|
expect(gc.collect(), 2, "function")
|
exec("def f(): pass\n") in d
|
if gc.collect() != 1: raise TestFailed
|
expect(gc.collect(), 1, "frame")
|
def f(): frame = sys._getframe()
|
raise TestFailed
|
raise TestFailed, "didn't find obj in garbage (saveall)"
|
def test_saveall(): # Verify that cyclic garbage like lists show up in gc.garbage if the # SAVEALL option is enabled. debug = gc.get_debug() gc.set_debug(debug | gc.DEBUG_SAVEALL) l = [] l.append(l) id_l = id(l) del l gc.collect() try: for obj in gc.garbage: if id(obj) == id_l: del obj[:] break else: raise TestFailed gc.garbage.remove(obj) finally: gc.set_debug(debug)
|
append = "$append%d" % self.__list_count
|
tmpname = "$list%d" % self.__list_count
|
def visitListComp(self, node): self.set_lineno(node) # setup list append = "$append%d" % self.__list_count self.__list_count = self.__list_count + 1 self.emit('BUILD_LIST', 0) self.emit('DUP_TOP') self.emit('LOAD_ATTR', 'append') self._implicitNameOp('STORE', append)
|
self.emit('LOAD_ATTR', 'append') self._implicitNameOp('STORE', append)
|
self._implicitNameOp('STORE', tmpname)
|
def visitListComp(self, node): self.set_lineno(node) # setup list append = "$append%d" % self.__list_count self.__list_count = self.__list_count + 1 self.emit('BUILD_LIST', 0) self.emit('DUP_TOP') self.emit('LOAD_ATTR', 'append') self._implicitNameOp('STORE', append)
|
self._implicitNameOp('LOAD', append)
|
self._implicitNameOp('LOAD', tmpname)
|
def visitListComp(self, node): self.set_lineno(node) # setup list append = "$append%d" % self.__list_count self.__list_count = self.__list_count + 1 self.emit('BUILD_LIST', 0) self.emit('DUP_TOP') self.emit('LOAD_ATTR', 'append') self._implicitNameOp('STORE', append)
|
self.emit('CALL_FUNCTION', 1) self.emit('POP_TOP')
|
self.emit('LIST_APPEND',)
|
def visitListComp(self, node): self.set_lineno(node) # setup list append = "$append%d" % self.__list_count self.__list_count = self.__list_count + 1 self.emit('BUILD_LIST', 0) self.emit('DUP_TOP') self.emit('LOAD_ATTR', 'append') self._implicitNameOp('STORE', append)
|
self._implicitNameOp('DELETE', append)
|
self._implicitNameOp('DELETE', tmpname)
|
def visitListComp(self, node): self.set_lineno(node) # setup list append = "$append%d" % self.__list_count self.__list_count = self.__list_count + 1 self.emit('BUILD_LIST', 0) self.emit('DUP_TOP') self.emit('LOAD_ATTR', 'append') self._implicitNameOp('STORE', append)
|
e.num = getint(b)
|
e.num = getint_event(b)
|
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
|
e.height = getint(h) e.keycode = getint(k) try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y)
|
e.height = getint_event(h) e.keycode = getint_event(k) e.state = getint_event(s) e.time = getint_event(t) e.width = getint_event(w) e.x = getint_event(x) e.y = getint_event(y)
|
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
|
e.keysym_num = getint(N)
|
e.keysym_num = getint_event(N)
|
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
|
e.x_root = getint(X) e.y_root = getint(Y)
|
e.x_root = getint_event(X) e.y_root = getint_event(Y)
|
def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) try: e.delta = getint(D) except ValueError: e.delta = 0 return (e,)
|
initialcolor = (128, 128, 128)
|
initialcolor = 'grey50'
|
def main(): global app initialcolor = (128, 128, 128) try: opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['color=', 'help']) except getopt.error, msg: usage(1, msg) if args: usage(1) for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-c', '--color'): initialcolor = arg # create the windows and go for f in RGB_TXT: try: colordb = ColorDB.get_colordb(f) break except IOError: pass else: raise IOError('No color database file found') app = Pmw.initialise(fontScheme='pmw1') app.title('Pynche %s' % __version__) app.tk.createtimerhandler(KEEPALIVE_TIMER, keepalive) # get triplet for initial color try: red, green, blue = colordb.find_byname(initialcolor) except ColorDB.BadColor: # must be a #rrggbb style color try: red, green, blue = ColorDB.rrggbb_to_triplet(initialcolor) except ColorDB.BadColor: usage(1, 'Bad initial color: %s' % initialcolor) p = PyncheWidget(colordb, app, color=(red, green, blue)) try: keepalive() app.mainloop() except KeyboardInterrupt: pass
|
funcs = (None, lambda x: True)
|
funcs = (None, bool, lambda x: True)
|
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses # and that the result always go's through __getitem__ funcs = (None, lambda x: True) class tuple2(tuple): def __getitem__(self, index): return 2*tuple.__getitem__(self, index) class str2(str): def __getitem__(self, index): return 2*str.__getitem__(self, index) inputs = { tuple2: {(): (), (1, 2, 3): (2, 4, 6)}, str2: {"": "", "123": "112233"} } if have_unicode: class unicode2(unicode): def __getitem__(self, index): return 2*unicode.__getitem__(self, index) inputs[unicode2] = { unicode(): unicode(), unicode("123"): unicode("112233") }
|
L2 = L
|
L2 = L[:]
|
def test_long(self): self.assertEqual(long(314), 314L) self.assertEqual(long(3.14), 3L) self.assertEqual(long(314L), 314L) # Check that conversion from float truncates towards zero self.assertEqual(long(-3.14), -3L) self.assertEqual(long(3.9), 3L) self.assertEqual(long(-3.9), -3L) self.assertEqual(long(3.5), 3L) self.assertEqual(long(-3.5), -3L) self.assertEqual(long("-3"), -3L) if have_unicode: self.assertEqual(long(unicode("-3")), -3L) # Different base: self.assertEqual(long("10",16), 16L) if have_unicode: self.assertEqual(long(unicode("10"),16), 16L) # Check conversions from string (same test set as for int(), and then some) LL = [ ('1' + '0'*20, 10L**20), ('1' + '0'*100, 10L**100) ] L2 = L if have_unicode: L2 += [ (unicode('1') + unicode('0')*20, 10L**20), (unicode('1') + unicode('0')*100, 10L**100), ] for s, v in L2 + LL: for sign in "", "+", "-": for prefix in "", " ", "\t", " \t\t ": ss = prefix + sign + s vv = v if sign == "-" and v is not ValueError: vv = -v try: self.assertEqual(long(ss), long(vv)) except v: pass
|
return browser
|
return GenericBrowser(browser)
|
def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if browser.find('%s') > -1: # User gave us a command line, don't mess with it. return browser else: # User gave us a browser name. command = _browsers[browser.lower()] if command[1] is None: return command[0]() else: return command[1] raise Error("could not locate runnable browser")
|
cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall},
|
cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall, 'install_lib':PyBuildInstallLib},
|
def main(): # turn off warnings when deprecated modules are imported import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) setup(name = 'Python standard library', version = '%d.%d' % sys.version_info[:2], cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall}, # The struct module is defined here, because build_ext won't be # called unless there's at least one extension module defined. ext_modules=[Extension('struct', ['structmodule.c'])], # Scripts to install scripts = ['Tools/scripts/pydoc'] )
|
modulesbyfile[getabsfile(module)] = module.__name__
|
modulesbyfile[ os.path.realpath( getabsfile(module))] = module.__name__
|
def getmodule(object): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) main = sys.modules['__main__'] if not hasattr(object, '__name__'): return None if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main builtin = sys.modules['__builtin__'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin
|
def resolve_dotted_attribute(obj, attr):
|
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
|
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj
|
for i in attr.split('.'):
|
if allow_dotted_names: attrs = attr.split('.') else: attrs = [attr] for i in attrs:
|
def resolve_dotted_attribute(obj, attr): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. """ for i in attr.split('.'): if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj
|
def register_instance(self, instance):
|
def register_instance(self, instance, allow_dotted_names=False):
|
def register_instance(self, instance): """Registers an instance to respond to XML-RPC requests.
|
method_name
|
method_name, self.allow_dotted_names
|
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together"
|
method
|
method, self.allow_dotted_names
|
def _dispatch(self, method, params): """Dispatches the XML-RPC method.
|
vereq(x.a, None)
|
verify(not hasattr(x, "a"))
|
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) vereq(x.a, None) x.a = 1 vereq(x.a, 1) del x.a vereq(x.a, None) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(x.a is None) verify(x.b is None) verify(x.c is None) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
|
verify(x.a is None) verify(x.b is None) verify(x.c is None)
|
verify(not hasattr(x, 'a')) verify(not hasattr(x, 'b')) verify(not hasattr(x, 'c'))
|
def slots(): if verbose: print "Testing __slots__..." class C0(object): __slots__ = [] x = C0() verify(not hasattr(x, "__dict__")) verify(not hasattr(x, "foo")) class C1(object): __slots__ = ['a'] x = C1() verify(not hasattr(x, "__dict__")) vereq(x.a, None) x.a = 1 vereq(x.a, 1) del x.a vereq(x.a, None) class C3(object): __slots__ = ['a', 'b', 'c'] x = C3() verify(not hasattr(x, "__dict__")) verify(x.a is None) verify(x.b is None) verify(x.c is None) x.a = 1 x.b = 2 x.c = 3 vereq(x.a, 1) vereq(x.b, 2) vereq(x.c, 3)
|
internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
|
internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
|
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
|
if ';' in proxyServer:
|
if '=' in proxyServer:
|
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
|
protocol, address = p.split('=')
|
protocol, address = p.split('=', 1)
|
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
|
else: proxies['http'] = 'http://%s' % proxyServer proxies['ftp'] = 'ftp://%s' % proxyServer
|
else: if proxyServer[:5] == 'http:': proxies['http'] = proxyServer else: proxies['http'] = 'http://%s' % proxyServer proxies['ftp'] = 'ftp://%s' % proxyServer
|
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings.
|
def parseitem(x, self=self): return x[:1] + tuple(map(getint, x[1:])) return map(parseitem, data)
|
return map(self.__winfo_parseitem, data) def __winfo_parseitem(self, t): return t[:1] + tuple(map(self.__winfo_getint, t[1:])) def __winfo_getint(self, x): return _string.atoi(x, 0)
|
def parseitem(x, self=self): return x[:1] + tuple(map(getint, x[1:]))
|
self.assertEqual(lines, ['Test'])
|
self.assertEqual(xlines, ['Test'])
|
def testBug1191043(self): # readlines() for files containing no newline data = 'BZh91AY&SY\xd9b\x89]\x00\x00\x00\x03\x80\x04\x00\x02\x00\x0c\x00 \x00!\x9ah3M\x13<]\xc9\x14\xe1BCe\x8a%t' f = open(self.filename, "wb") f.write(data) f.close() bz2f = BZ2File(self.filename) lines = bz2f.readlines() bz2f.close() self.assertEqual(lines, ['Test']) bz2f = BZ2File(self.filename) xlines = list(bz2f.xreadlines()) bz2f.close() self.assertEqual(lines, ['Test'])
|
if sys.maxint > 0x7fffffff: self.assertRaises(ValueError, len, r) else: self.assertEqual(len(r), sys.maxint)
|
self.assertEqual(len(r), sys.maxint)
|
def test_xrange(self): self.assertEqual(list(xrange(3)), [0, 1, 2]) self.assertEqual(list(xrange(1, 5)), [1, 2, 3, 4]) self.assertEqual(list(xrange(0)), []) self.assertEqual(list(xrange(-3)), []) self.assertEqual(list(xrange(1, 10, 3)), [1, 4, 7]) self.assertEqual(list(xrange(5, -5, -3)), [5, 2, -1, -4])
|
print '--Call--' self.interaction(frame, None)
|
if self.stop_here(frame): print '--Call--' self.interaction(frame, None)
|
def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" print '--Call--' self.interaction(frame, None)
|
BasicStrTest
|
BasicStrTest, CharmapTest
|
def test_main(): test_support.run_unittest( UTF16Test, UTF16LETest, UTF16BETest, UTF8Test, EscapeDecodeTest, RecodingTest, PunycodeTest, UnicodeInternalTest, NameprepTest, CodecTest, CodecsModuleTest, StreamReaderTest, Str2StrTest, BasicUnicodeTest, BasicStrTest )
|
y = self.expovariate(alpha) z = self.expovariate(1.0/beta) return z/(y+z)
|
y = self.gammavariate(alpha, 1.) if y == 0: return 0.0 else: return y / (y + self.gammavariate(beta, 1.))
|
def betavariate(self, alpha, beta):
|
self.tempcache[url] = result = tfn, headers
|
self.tempcache[url] = result
|
def retrieve(self, url): if self.tempcache and self.tempcache.has_key(url): return self.tempcache[url] url1 = unwrap(url) if self.tempcache and self.tempcache.has_key(url1): self.tempcache[url] = self.tempcache[url1] return self.tempcache[url1] type, url1 = splittype(url1) if not type or type == 'file': try: fp = self.open_local_file(url1) del fp return splithost(url1)[1], None except IOError, msg: pass fp = self.open(url) headers = fp.info() import tempfile tfn = tempfile.mktemp() if self.tempcache is not None: self.tempcache[url] = result = tfn, headers tfp = open(tfn, 'w') bs = 1024*8 block = fp.read(bs) while block: tfp.write(block) block = fp.read(bs) del fp del tfp return result
|
tuple2: {(): (), (1, 2, 3): (1, 2, 3)},
|
tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
|
def __getitem__(self, index): return 2*str.__getitem__(self, index)
|
self.__delete()
|
try: self.__delete() except: pass
|
def __bootstrap(self): try: self.__started = 1 _active_limbo_lock.acquire() _active[_get_ident()] = self del _limbo[self] _active_limbo_lock.release() if __debug__: self._note("%s.__bootstrap(): thread started", self) try: self.run() except SystemExit: if __debug__: self._note("%s.__bootstrap(): raised SystemExit", self) except: if __debug__: self._note("%s.__bootstrap(): unhandled exception", self) s = _StringIO() _print_exc(file=s) _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), s.getvalue())) else: if __debug__: self._note("%s.__bootstrap(): normal return", self) finally: self.__stop() self.__delete()
|
basename, ext = os.path.splitext (output_filename) output_filename = basename + '_d' + ext
|
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
|
|
try: unicode(u'decoding unicode is not supported', 'utf-8', 'strict') except TypeError: pass else: raise TestFailed, "decoding unicode should NOT be supported"
|
if not sys.platform.startswith('java'): try: unicode(u'decoding unicode is not supported', 'utf-8', 'strict') except TypeError: pass else: raise TestFailed, "decoding unicode should NOT be supported"
|
def __str__(self): return self.x
|
verify(unicode(buffer('character buffers are decoded to unicode'), 'utf-8', 'strict') == u'character buffers are decoded to unicode')
|
if not sys.platform.startswith('java'): verify(unicode(buffer('character buffers are decoded to unicode'), 'utf-8', 'strict') == u'character buffers are decoded to unicode')
|
def __str__(self): return self.x
|
if (sysconfig.get_config_var('HAVE_GETSPNAM') or sysconfig.get_config_var('HAVE_GETSPENT')):
|
if (config_h_vars.get('HAVE_GETSPNAM', False) or config_h_vars.get('HAVE_GETSPENT', False)):
|
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')
|
config_h = sysconfig.get_config_h_filename() config_h_vars = sysconfig.parse_config_h(open(config_h))
|
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')
|
|
return 1
|
def test_expat_entityresolver(): return 1 # disabling this until pyexpat.c has been fixed parser = create_parser() parser.setEntityResolver(TestEntityResolver()) result = StringIO() parser.setContentHandler(XMLGenerator(result)) parser.feed('<!DOCTYPE doc [\n') parser.feed(' <!ENTITY test SYSTEM "whatever">\n') parser.feed(']>\n') parser.feed('<doc>&test;</doc>') parser.close() return result.getvalue() == start + "<doc><entity></entity></doc>"
|
|
if not self.__ensure_WMAvailable(): raise RuntimeError, "No window manager access, cannot send AppleEvent"
|
def sendevent(self, event): """Send a pre-created appleevent, await the reply and unpack it""" reply = event.AESend(self.send_flags, self.send_priority, self.send_timeout) parameters, attributes = unpackevent(reply, self._moduleName) return reply, parameters, attributes
|
|
text = self._split_header(text)
|
text = self._split_header(h, text)
|
def _write_headers(self, msg): for h, v in msg.items(): # We only write the MIME-Version: header for the outermost # container message. Unfortunately, we can't use same technique # as for the Unix-From above because we don't know when # MIME-Version: will occur. if h.lower() == 'mime-version' and not self.__first: continue # RFC 2822 says that lines SHOULD be no more than maxheaderlen # characters wide, so we're well within our rights to split long # headers. text = '%s: %s' % (h, v) if self.__maxheaderlen > 0 and len(text) > self.__maxheaderlen: text = self._split_header(text) print >> self._fp, text # A blank line always separates headers from body print >> self._fp
|
def _split_header(self, text):
|
def _split_header(self, name, text):
|
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
|
lines = [s.replace('\t', SPACE8) for s in text.split('\n')]
|
lines = [s.replace('\t', SPACE8) for s in text.splitlines()]
|
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
|
rtn = [] for line in text.split('\n'): splitline = [] if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue parts = re.split(r'(\s+)', line) if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
|
h = Header(text, maxlinelen=maxheaderlen, continuation_ws='\t') return h.encode()
|
def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): splitline = [] # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) else: oldlen = len(line) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(line) > maxheaderlen: i = line.rfind(';', 0, maxheaderlen) if i < 0: break splitline.append(line[:i]) line = line[i+1:].lstrip() if len(line) <> oldlen: # Splitting on semis worked splitline.append(line) rtn.append(SEMINLTAB.join(splitline)) continue # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', line) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: rtn.append(line) continue first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part splitline.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) splitline.append(EMPTYSTRING.join(sublines)) rtn.append(NLTAB.join(splitline)) return NL.join(rtn)
|
"""Check the LaTex formatting in a sequence of lines.
|
"""Check the LaTeX formatting in a sequence of lines.
|
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
|
Morecmds is a sequence of LaTex commands (without backslashes) that
|
Morecmds is a sequence of LaTeX commands (without backslashes) that
|
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
|
print "Unmatched open delimiter '%s' on line %d", (symbol, lineno)
|
print "Unmatched open delimiter '%s' on line %d" % (symbol, lineno)
|
def checkit(source, opts, morecmds=[]): """Check the LaTex formatting in a sequence of lines. Opts is a mapping of options to option values if any: -m munge parenthesis and brackets -f forward slash warnings to be skipped -d delimiters only checking -v verbose listing on delimiters -s lineno: linenumber to start scan (default is 1). Morecmds is a sequence of LaTex commands (without backslashes) that are to be considered valid in the scan. """ texcmd = re.compile(r'\\[A-Za-z]+') validcmds = sets.Set(cmdstr.split()) for cmd in morecmds: validcmds.add('\\' + cmd) openers = [] # Stack of pending open delimiters if '-m' in opts: pairmap = {']':'[(', ')':'(['} # Munged openers else: pairmap = {']':'[', ')':'('} # Normal opener for a given closer openpunct = sets.Set('([') # Set of valid openers delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])') startline = int(opts.get('-s', '1')) lineno = 0 for lineno, line in izip(count(startline), islice(source, startline-1, None)): line = line.rstrip() if '-f' not in opts and '/' in line: # Warn whenever forward slashes encountered line = line.rstrip() print 'Warning, forward slash on line %d: %s' % (lineno, line) if '-d' not in opts: # Validate commands nc = line.find(r'\newcommand') if nc != -1: start = line.find('{', nc) end = line.find('}', start) validcmds.add(line[start+1:end]) for cmd in texcmd.findall(line): if cmd not in validcmds: print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd) # Check balancing of open/close markers (parens, brackets, etc) for begend, name, punct in delimiters.findall(line): if '-v' in opts: print lineno, '|', begend, name, punct, if begend == 'begin' and '-d' not in opts: openers.append((lineno, name)) elif punct in openpunct: openers.append((lineno, punct)) elif begend == 'end' and '-d' not in opts: matchclose(lineno, name, openers, pairmap) elif punct in pairmap: matchclose(lineno, punct, openers, pairmap) if '-v' in opts: print ' --> ', openers for lineno, symbol in openers: print "Unmatched open delimiter '%s' on line %d", (symbol, lineno) print 'Done checking %d lines.' % (lineno,) return 0
|
def open(self, url, new=0):
|
def open(self, url, new=0, autoraise=1):
|
def open(self, url, new=0): os.system(self.command % url)
|
def open(self, url, new=1):
|
def open(self, url, new=1, autoraise=1):
|
def open(self, url, new=1): # XXX Currently I know no way to prevent KFM from opening a new win. self._remote("openURL %s" % url)
|
def open(self, url, new=0):
|
def open(self, url, new=0, autoraise=1):
|
def open(self, url, new=0): if new: self._remote("LOADNEW " + url) else: self._remote("LOAD " + url)
|
def open(self, url, new=0):
|
def open(self, url, new=0, autoraise=1):
|
def open(self, url, new=0): os.startfile(url)
|
def open(self, url, new=0):
|
def open(self, url, new=0, autoraise=1):
|
def open(self, url, new=0): ic.launchurl(url)
|
mo = AbstractBasicAuthHandler.rx.match(authreq)
|
mo = AbstractBasicAuthHandler.rx.search(authreq)
|
def http_error_auth_reqed(self, authreq, host, req, headers): # XXX could be multiple headers authreq = headers.get(authreq, None) if authreq: mo = AbstractBasicAuthHandler.rx.match(authreq) if mo: scheme, realm = mo.groups() if scheme.lower() == 'basic': return self.retry_http_basic_auth(host, req, realm)
|
Form.form({key: value})
|
Form.form(self, {key: value})
|
def __setitem__(self, key, value): Form.form({key: value})
|
return self.tk.call(self.stylename, 'cget', '-%s'%key, value)
|
return self.tk.call(self.stylename, 'cget', '-%s'%key)
|
def __getitem__(self,key): return self.tk.call(self.stylename, 'cget', '-%s'%key, value)
|
('a = 1,2,3', '((1, 2, 3))',), ('("a","b","c")', "(('a', 'b', 'c'))",), ('a,b,c = 1,2,3', '((1, 2, 3))',),
|
('a = 1,2,3', '((1, 2, 3))'), ('("a","b","c")', "(('a', 'b', 'c'))"), ('a,b,c = 1,2,3', '((1, 2, 3))'), ('(None, 1, None)', '((None, 1, None))'), ('((1, 2), 3, 4)', '(((1, 2), 3, 4))'),
|
def test_folding_of_tuples_of_constants(self): for line, elem in ( ('a = 1,2,3', '((1, 2, 3))',), ('("a","b","c")', "(('a', 'b', 'c'))",), ('a,b,c = 1,2,3', '((1, 2, 3))',), ): asm = dis_single(line) self.assert_(elem in asm) self.assert_('BUILD_TUPLE' not in asm)
|
filename = os.path.join(dir, testfile) fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break
|
filename = os.path.join(dir, testfile) if os.name == 'posix': try: fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700) except OSError: pass else: fp = os.fdopen(fd, 'w') fp.write('blat') fp.close() os.unlink(filename) del fp, fd tempdir = dir break else: fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break
|
def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/usr/tmp', '/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 1) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir
|
if not callable(callback): callback = print_line
|
if callback is None: callback = print_line
|
def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback.''' if not callable(callback): callback = print_line resp = self.sendcmd('TYPE A') conn = self.transfercmd(cmd) fp = conn.makefile('rb') while 1: line = fp.readline() if self.debugging > 2: print '*retr*', `line` if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) fp.close() conn.close() return self.voidresp()
|
verify(int(a) == 12345)
|
def __add__(self, other): return hexint(int.__add__(self, other))
|
|
verify(long(a) == 12345L)
|
def __add__(self, other): return self.__class__(super(octlong, self).__add__(other))
|
|
verify(float(a) == 12345.0)
|
def __repr__(self): return "%.*g" % (self.prec, self)
|
|
verify(str(s) == "12345")
|
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
|
|
verify(str(s) == "\x00" * 5)
|
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
|
|
if modargs: mf.import_hook(scriptfile) else: mf.load_file(scriptfile)
|
mf.load_file(scriptfile)
|
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] exclude = [] # settable with -x option addn_link = [] # settable with -l, but only honored under Windows. path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # default the exclude list for each platform if win: exclude = exclude + [ 'dos', 'dospath', 'mac', 'macpath', 'macfs', 'MACFS', 'posix', 'os2'] # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line by first replacing any "-i" options with the file contents. pos = 1 while pos < len(sys.argv)-1: # last option can not be "-i", so this ensures "pos+1" is in range! if sys.argv[pos] == '-i': try: options = string.split(open(sys.argv[pos+1]).read()) except IOError, why: usage("File name '%s' specified with the -i option can not be read - %s" % (sys.argv[pos+1], why) ) # Replace the '-i' and the filename with the read params. sys.argv[pos:pos+2] = options pos = pos + len(options) - 1 # Skip the name and the included args. pos = pos + 1 # Now parse the command line with the extras inserted. try: opts, args = getopt.getopt(sys.argv[1:], 'a:de:hmo:p:P:qs:wx:l:') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a if o == '-x': exclude.append(a) if o == '-l': addn_link.append(a) if o == '-a': apply(modulefinder.AddPackagePath, tuple(string.split(a,"=", 2))) # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c')) # locations derived from options version = sys.version[:3] if win: extensions_c = 'frozen_extensions.c' if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_h_dir = exec_prefix config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') if win: frozendllmain_c = os.path.join(exec_prefix, 'Pc\\frozen_dllmain.c') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_h_dir = os.path.join(exec_prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') frozendllmain_c = os.path.join(binlib, 'frozen_dllmain.c') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + config_h_dir] # sanity check of directories and files check_dirs = [prefix, exec_prefix, binlib, incldir] if not win: check_dirs = check_dirs + extensions # These are not directories on Windows. for dir in check_dirs: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources + extensions # extensions are files on Windows. else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that file arguments exist for arg in args: if arg == '-m': break # if user specified -m on the command line before _any_ # file names, then nothing should be checked (as the # very first file should be a module name) if modargs: break if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' if odir: base = os.path.join(odir, '') frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) if win: extensions_c = os.path.join(odir, extensions_c) # Handle special entry point requirements # (on Windows, some frozen programs do not use __main__, but # import the module directly. Eg, DLLs, Services, etc custom_entry_point = None # Currently only used on Windows python_entry_is_main = 1 # Is the entry point called __main__? # handle -s option on Windows if win: import winmakemakefile try: custom_entry_point, python_entry_is_main = \ winmakemakefile.get_custom_entry_point(subsystem) except ValueError, why: usage(why) # Actual work starts here... # collect all modules of the program dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug, exclude) if win and subsystem=='service': # If a Windows service, then add the "built-in" module. mod = mf.add_module("servicemanager") mod.__file__="dummy.pyd" # really built-in to the resulting EXE for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) # Add the main script as either __main__, or the actual module name. if python_entry_is_main: mf.run_script(scriptfile) else: if modargs: mf.import_hook(scriptfile) else: mf.load_file(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules files = makefreeze.makefreeze(base, dict, debug, custom_entry_point) # look for unfrozen modules (builtin and of unknown origin) builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) # search for unknown modules in extensions directories (not on Windows) addfiles = [] frozen_extensions = [] # Windows list of modules. if unknown or (not win and builtins): if not win: addfiles, addmods = \ checkextensions.checkextensions(unknown+builtins, extensions) for mod in addmods: if mod in unknown: unknown.remove(mod) builtins.append(mod) else: # Do the windows thang... import checkextensions_win32 # Get a list of CExtension instances, each describing a module # (including its source files) frozen_extensions = checkextensions_win32.checkextensions( unknown, extensions) for mod in frozen_extensions: unknown.remove(mod.name) # report unknown modules if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile, checkextensions_win32 checkextensions_win32.write_extension_table(extensions_c, frozen_extensions) # Create a module definition for the bootstrap C code. xtras = [frozenmain_c, os.path.basename(frozen_c), frozendllmain_c, os.path.basename(extensions_c)] + files maindefn = checkextensions_win32.CExtension( '__main__', xtras ) frozen_extensions.append( maindefn ) outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), frozen_extensions, os.path.basename(target)) finally: outfp.close() return # generate config.c and Makefile builtins.sort() infp = open(config_c_in) outfp = bkfile.open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ files + supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] outfp = bkfile.open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
|
if wid:
|
if KILLUNKNOWNWINDOWS and wid:
|
def do_updateEvt(self, event): (what, message, when, where, modifiers) = event wid = Win.WhichWindow(message) if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_rawupdate(wid, event) else: if wid: wid.HideWindow() import sys sys.stderr.write("XXX killed unknown (crashed?) Python window.\n") else: MacOS.HandleEvent(event)
|
newurl = '//' + host + selector return self.open_http(newurl)
|
newurl = 'http://' + host + selector return self.open(newurl)
|
def retry_http_basic_auth(self, url, realm): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = '//' + host + selector return self.open_http(newurl)
|
parts = msg.split(" ", 2)
|
parts = msg.split(" ", 1)
|
def _decode_msg(self, msg): seqno = self.decode_seqno(msg[:self.SEQNO_ENC_LEN]) msg = msg[self.SEQNO_ENC_LEN:] parts = msg.split(" ", 2) if len(parts) == 1: cmd = msg arg = '' else: cmd = parts[0] arg = parts[1] return cmd, arg, seqno
|
if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd]
|
_cleanup()
|
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
|
os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n')
|
os.dup2(p2cread, 0) os.dup2(c2pwrite, 1)
|
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
|
os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) os._exit(1)
|
os.dup2(errin, 2) self._run_child(cmd)
|
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
|
self.sts = -1
|
def __init__(self, cmd, capturestderr=0, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" if type(cmd) == type(''): cmd = ['/bin/sh', '-c', cmd] p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.close(0) os.close(1) if os.dup(p2cread) <> 0: sys.stderr.write('popen2: bad read dup\n') if os.dup(c2pwrite) <> 1: sys.stderr.write('popen2: bad write dup\n') if capturestderr: os.close(2) if os.dup(errin) <> 2: pass for i in range(3, MAXFD): try: os.close(i) except: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) # Shouldn't come here, I guess os._exit(1) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None self.sts = -1 # Child not completed yet _active.append(self)
|
|
def popen2(cmd, mode='t', bufsize=-1):
|
del Popen3, Popen4, _active, _cleanup def popen2(cmd, bufsize=-1, mode='t'):
|
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" w, r = os.popen2(cmd, mode, bufsize) return r, w
|
else: def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 0, bufsize) return inst.fromchild, inst.tochild
|
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" w, r = os.popen2(cmd, mode, bufsize) return r, w
|
|
if sys.platform[:3] == "win": def popen3(cmd, mode='t', bufsize=-1):
|
def popen3(cmd, bufsize=-1, mode='t'):
|
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 0, bufsize) return inst.fromchild, inst.tochild
|
else: def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 1, bufsize) return inst.fromchild, inst.tochild, inst.childerr
|
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" w, r, e = os.popen3(cmd, mode, bufsize) return r, w, e
|
|
if sys.platform[:3] == "win": def popen4(cmd, mode='t', bufsize=-1):
|
def popen4(cmd, bufsize=-1, mode='t'):
|
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 1, bufsize) return inst.fromchild, inst.tochild, inst.childerr
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.