我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.getrecursionlimit()。
def test_timer_recursion(nsproxy): """ This bug occured with the first implementation of the timer. After some iterations the timer would throw an exception when the recursion limit was exceeded. Timers should never reach a recursion limit. """ def inc(agent): agent.count += 1 agent = run_agent('a0') agent.set_attr(count=0) agent.each(0.0, inc) limit = sys.getrecursionlimit() assert wait_agent_condition(agent, lambda agent: agent.count > limit, timeout=10)
def setUp(self): if sys.getrecursionlimit() < 1000: sys.setrecursionlimit(1000) self.addr = 'vJmtjxSDxNPXL4RNapp9ARdqKz3uJyf1EDGjr1Fgqs9c8mYsVH82h8wvnA4i5rtJ57mr3kor1EVJrd4e5upACJd588xe52yXtzumxj' self.scan_pub = '025e58a31122b38c86abc119b9379fe247410aee87a533f9c07b189aef6c3c1f52' self.scan_priv = '3e49e7257cb31db997edb1cf8299af0f37e2663e2260e4b8033e49d39a6d02f2' self.spend_pub = '03616562c98e7d7b74be409a787cec3a912122f3fb331a9bee9b0b73ce7b9f50af' self.spend_priv = 'aa3db0cfb3edc94de4d10f873f8190843f2a17484f6021a95a7742302c744748' self.ephem_pub = '03403d306ec35238384c7e340393335f9bc9bb4a2e574eb4e419452c4ea19f14b0' self.ephem_priv = '9e63abaf8dcd5ea3919e6de0b6c544e00bf51bf92496113a01d6e369944dc091' self.shared_secret = 'a4047ee231f4121e3a99a3a3378542e34a384b865a9917789920e1f13ffd91c6' self.pay_pub = '02726112ad39cb6bf848b1b1ef30b88e35286bf99f746c2be575f96c0e02a9357c' self.pay_priv = '4e422fb1e5e1db6c1f6ab32a7706d368ceb385e7fab098e633c5c5949c3b97cd' self.testnet_addr = 'waPUuLLykSnY3itzf1AyrQZm42F7KyB7SR5zpfqmnzPXWhx9kXLzV3EcyqzDdpTwngiyCCMUqztS9S1d7XJs3JMt3MsHPDpBCudvx9'
def deepcopy(obj, recursion=100000): """ Perform a deep copy of obj using cPickle. Faster than copy.deepcopy() for large objects. @param obj: the object to copy @return: a deep copy of obj @param recursion: maximum recursion limit @type recursion: int """ from csb.io import Pickle current = sys.getrecursionlimit() sys.setrecursionlimit(recursion) tmp = Pickle.dumps(obj, Pickle.HIGHEST_PROTOCOL) copy = Pickle.loads(tmp) sys.setrecursionlimit(current) return copy
def test_very_long_words(): import sys length = int(sys.getrecursionlimit() * 1.5) strings1 = [u(chr(i) * length) for i in range(65, 70)] strings2 = [u(chr(i) * length) for i in range(71, 75)] ana = analysis.StemmingAnalyzer() schema = fields.Schema(text=fields.TEXT(analyzer=ana, spelling=True)) ix = RamStorage().create_index(schema) with ix.writer() as w: for string in strings1: w.add_document(text=string) with ix.writer() as w: for string in strings2: w.add_document(text=string) w.optimize = True
def test_recursionlimit_recovery(self): # NOTE: this test is slightly fragile in that it depends on the current # recursion count when executing the test being low enough so as to # trigger the recursion recovery detection in the _Py_MakeEndRecCheck # macro (see ceval.h). oldlimit = sys.getrecursionlimit() def f(): f() try: for i in (50, 1000): # Issue #5392: stack overflow after hitting recursion limit twice sys.setrecursionlimit(i) self.assertRaises(RuntimeError, f) self.assertRaises(RuntimeError, f) finally: sys.setrecursionlimit(oldlimit)
def run_test_for_event(self, event): """Tests that an exception raised in response to the given event is handled OK.""" self.raiseOnEvent = event try: for i in range(sys.getrecursionlimit() + 1): sys.settrace(self.trace) try: self.f() except ValueError: pass else: self.fail("exception not thrown!") except RuntimeError: self.fail("recursion counter not reset") # Test the handling of exceptions raised by each kind of trace event.
def test_repr(self): l0 = [] l2 = [0, 1, 2] a0 = self.type2test(l0) a2 = self.type2test(l2) self.assertEqual(str(a0), str(l0)) self.assertEqual(repr(a0), repr(l0)) self.assertEqual(repr(a2), repr(l2)) self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]") a2.append(a2) a2.append(3) self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") l0 = [] for i in range(sys.getrecursionlimit() + 10000): l0 = [l0] self.assertRaises(RuntimeError, repr, l0)
def test_recursionlimit(self): self.assertRaises(TypeError, sys.getrecursionlimit, 42) oldlimit = sys.getrecursionlimit() self.assertRaises(TypeError, sys.setrecursionlimit) self.assertRaises(ValueError, sys.setrecursionlimit, -42) sys.setrecursionlimit(10000) self.assertEqual(sys.getrecursionlimit(), 10000) sys.setrecursionlimit(oldlimit) self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31) try: sys.setrecursionlimit((1 << 31) - 5) try: # issue13546: isinstance(e, ValueError) used to fail # when the recursion limit is close to 1<<31 raise ValueError() except ValueError, e: pass finally: sys.setrecursionlimit(oldlimit)
def run_test_for_event(self, event): """Tests that an exception raised in response to the given event is handled OK.""" self.raiseOnEvent = event try: for i in xrange(sys.getrecursionlimit() + 1): sys.settrace(self.trace) try: self.f() except ValueError: pass else: self.fail("exception not raised!") except RuntimeError: self.fail("recursion counter not reset") # Test the handling of exceptions raised by each kind of trace event.
def test_repr(self): l0 = [] l2 = [0, 1, 2] a0 = self.type2test(l0) a2 = self.type2test(l2) self.assertEqual(str(a0), str(l0)) self.assertEqual(repr(a0), repr(l0)) self.assertEqual(repr(a2), repr(l2)) self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]") a2.append(a2) a2.append(3) self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") l0 = [] for i in xrange(sys.getrecursionlimit() + 100): l0 = [l0] self.assertRaises(RuntimeError, repr, l0)
def _objs_opts(objs, all=None, **opts): '''Return given or 'all' objects and the remaining options. ''' if objs: # given objects t = objs elif all in (False, None): t = () elif all is True: # 'all' objects ... # ... modules first, globals and stack # (may contain duplicate objects) t = tuple(_values(sys.modules)) + ( globals(), stack(sys.getrecursionlimit())[2:]) else: raise ValueError('invalid option: %s=%r' % ('all', all)) return t, opts
def test_compiler_recursion_limit(self): # Expected limit is sys.getrecursionlimit() * the scaling factor # in symtable.c (currently 3) # We expect to fail *at* that limit, because we use up some of # the stack depth limit in the test suite code # So we check the expected limit and 75% of that # XXX (ncoghlan): duplicating the scaling factor here is a little # ugly. Perhaps it should be exposed somewhere... fail_depth = sys.getrecursionlimit() * 3 success_depth = int(fail_depth * 0.75) def check_limit(prefix, repeated): expect_ok = prefix + repeated * success_depth self.compile_single(expect_ok) broken = prefix + repeated * fail_depth details = "Compiling ({!r} + {!r} * {})".format( prefix, repeated, fail_depth) with self.assertRaises(RuntimeError, msg=details): self.compile_single(broken) check_limit("a", "()") check_limit("a", ".b") check_limit("a", "[0]") check_limit("a", "*a")
def test_repr(self): l0 = [] l2 = [0, 1, 2] a0 = self.type2test(l0) a2 = self.type2test(l2) self.assertEqual(str(a0), str(l0)) self.assertEqual(repr(a0), repr(l0)) self.assertEqual(repr(a2), repr(l2)) self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]") a2.append(a2) a2.append(3) self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") l0 = [] for i in range(sys.getrecursionlimit() + 100): l0 = [l0] self.assertRaises(RuntimeError, repr, l0)
def save(s): # increasing recursion depth to avoid pickle: maximum recursion depth error, see: # http://stackoverflow.com/q/2134706/1030312 current_limit = sys.getrecursionlimit() if current_limit < fypickling_recursion_limit: sys.setrecursionlimit(fypickling_recursion_limit) dump( s, open(s.url.pickle, 'wb'), protocol = HIGHEST_PROTOCOL, ) if current_limit < fypickling_recursion_limit: sys.setrecursionlimit(current_limit)
def blowstack(fxn, arg, compare_to): # Make sure that calling isinstance with a deeply nested tuple for its # argument will raise RuntimeError eventually. tuple_arg = (compare_to,) if test_support.check_impl_detail(cpython=True): RECURSION_LIMIT = sys.getrecursionlimit() else: # on non-CPython implementations, the maximum # actual recursion limit might be higher, but # probably not higher than 99999 # RECURSION_LIMIT = 99999 for cnt in xrange(RECURSION_LIMIT+5): tuple_arg = (tuple_arg,) fxn(arg, tuple_arg)
def test_repr(self): l0 = [] l2 = [0, 1, 2] a0 = self.type2test(l0) a2 = self.type2test(l2) self.assertEqual(str(a0), str(l0)) self.assertEqual(repr(a0), repr(l0)) self.assertEqual(repr(a2), repr(l2)) self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]") a2.append(a2) a2.append(3) self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") if test_support.check_impl_detail(): depth = sys.getrecursionlimit() + 100 else: depth = 1000 * 1000 # should be enough to exhaust the stack l0 = [] for i in xrange(depth): l0 = [l0] self.assertRaises(RuntimeError, repr, l0)
def test_recursionlimit_recovery(self): if hasattr(sys, 'gettrace') and sys.gettrace(): self.skipTest('fatal error if run with a trace function') # NOTE: this test is slightly fragile in that it depends on the current # recursion count when executing the test being low enough so as to # trigger the recursion recovery detection in the _Py_MakeEndRecCheck # macro (see ceval.h). oldlimit = sys.getrecursionlimit() def f(): f() try: for i in (50, 1000): # Issue #5392: stack overflow after hitting recursion limit twice sys.setrecursionlimit(i) self.assertRaises(RuntimeError, f) self.assertRaises(RuntimeError, f) finally: sys.setrecursionlimit(oldlimit)
def test_getWorkerArguments(self): """ C{_getWorkerArguments} discards options like C{random} as they only matter in the manager, and forwards options like C{recursionlimit} or C{disablegc}. """ self.addCleanup(sys.setrecursionlimit, sys.getrecursionlimit()) if gc.isenabled(): self.addCleanup(gc.enable) self.options.parseOptions(["--recursionlimit", "2000", "--random", "4", "--disablegc"]) args = self.options._getWorkerArguments() self.assertIn("--disablegc", args) args.remove("--disablegc") self.assertEqual(["--recursionlimit", "2000"], args)
def __init__(self, **kwargs): self.highlight = kwargs.get('highlight', True) self.force_moves = kwargs.get('force_moves', False) self.disp_coords = kwargs.get('disp_coords', False) self.coord_mode = kwargs.get('coord_mode', 'chess') self.move_limit = kwargs.get('move_limit', 50) self.disp_sqrs = kwargs.get('disp_sqrs', True) self.disp_pieces = kwargs.get('disp_pieces', True) self.do_checkmate = kwargs.get('do_checkmate', False) self.use_unicode = kwargs.get('use_unicode', use_unicode) self.recur_limit = kwargs.get('recur_limit', sys.getrecursionlimit()) self.disp_turn = kwargs.get('disp_turn', True) self.disp_timers = kwargs.get('disp_timers', False) self.board = None self.game = None self.has_gui = False
def pickle_model( path, model, word2index_x, word2index_y, index2word_x, index2word_y): import sys import cPickle as pickle modifier=10 tmp = sys.getrecursionlimit() sys.setrecursionlimit(tmp*modifier) with open(path, 'wb') as f: p_dict = {'model':model, 'word2index_x':word2index_x, 'word2index_y':word2index_y, 'index2word_x':index2word_x, 'index2word_y':index2word_y} pickle.dump(p_dict, f, protocol=2) sys.setrecursionlimit(tmp)
def __call__(self, *args): ## Start by extending recursion depth just a bit. ## If the error we are catching is due to recursion, we don't want to generate another one here. recursionLimit = sys.getrecursionlimit() try: sys.setrecursionlimit(recursionLimit+100) ## call original exception handler first (prints exception) global original_excepthook, callbacks, clear_tracebacks try: print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time())))) except Exception: sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n") sys.stdout = sys.stderr ret = original_excepthook(*args) for cb in callbacks: try: cb(*args) except Exception: print(" --------------------------------------------------------------") print(" Error occurred during exception callback %s" % str(cb)) print(" --------------------------------------------------------------") traceback.print_exception(*sys.exc_info()) ## Clear long-term storage of last traceback to prevent memory-hogging. ## (If an exception occurs while a lot of data is present on the stack, ## such as when loading large files, the data would ordinarily be kept ## until the next exception occurs. We would rather release this memory ## as soon as possible.) if clear_tracebacks is True: sys.last_traceback = None finally: sys.setrecursionlimit(recursionLimit)
def test_recursion_limited(self): """ Verify that recursion is controlled when raise_on_first_error=False and something is wrong with the query. PYTHON-585 """ max_recursion = sys.getrecursionlimit() s = Session(Cluster(), [Host("127.0.0.1", SimpleConvictionPolicy)]) self.assertRaises(TypeError, execute_concurrent_with_args, s, "doesn't matter", [('param',)] * max_recursion, raise_on_first_error=True) results = execute_concurrent_with_args(s, "doesn't matter", [('param',)] * max_recursion, raise_on_first_error=False) # previously self.assertEqual(len(results), max_recursion) for r in results: self.assertFalse(r[0]) self.assertIsInstance(r[1], TypeError)
def _getobjects(): # modules first, globals and stack # objects (may contain duplicates) return tuple(_values(sys.modules)) + ( globals(), stack(sys.getrecursionlimit())[2:])
def GenerateBSP(self, vertices, indices, max_face_count): resurs_limit = sys.getrecursionlimit() sys.setrecursionlimit(100000) faces = [] for iFace in range(len(indices) // 3): faces.append(iFace) box = calculate_bounding_box(vertices) self.add_node(box, faces, vertices, indices, max_face_count) sys.setrecursionlimit(resurs_limit)
def test_allow_recursion_deeper_than_the_recursion_limit(self): limit = 2 * sys.getrecursionlimit() rule = Match("a", "b") for _ in xrange(limit): rule = No(rule) self.assertEqual(format(rule), "no " * limit + "a=b")
def test_allow_recursion_deeper_than_the_recursion_limit(self): expr = parsing.forward_ref() expr.set( parsing.union( parsing.seq(parsing.txt("("), expr, parsing.txt(")"), pick=1), parsing.txt("a") ) ) limit = 2 * sys.getrecursionlimit() string = (limit * "(") + "a" + (limit * ")") self.assertEqual(expr.parse(string), ('a', ''))
def _GetCallingModuleObjectAndName(): """Returns the module that's calling into this module. We generally use this function to get the name of the module calling a DEFINE_foo... function. """ # Walk down the stack to find the first globals dict that's not ours. for depth in range(1, sys.getrecursionlimit()): if not sys._getframe(depth).f_globals is globals(): globals_for_frame = sys._getframe(depth).f_globals module, module_name = _GetModuleObjectAndName(globals_for_frame) if module_name is not None: return module, module_name raise AssertionError("No module was found")
def test_copy(self): current = sys.getrecursionlimit() self.addCleanup(sys.setrecursionlimit, current) # can't use sys.maxint as this doesn't exist in Python 3 sys.setrecursionlimit(int(10e8)) # this segfaults without the fix in place copy.copy(Mock())
def serialize(self, file_name): """ Serialize this HMM to a file. @param file_name: target file name @type file_name: str """ rec = sys.getrecursionlimit() sys.setrecursionlimit(10000) csb.io.Pickle.dump(self, open(file_name, 'wb')) sys.setrecursionlimit(rec)
def deserialize(file_name): """ De-serialize an HMM from a file. @param file_name: source file name (pickle) @type file_name: str """ rec = sys.getrecursionlimit() sys.setrecursionlimit(10000) try: return csb.io.Pickle.load(open(file_name, 'rb')) finally: sys.setrecursionlimit(rec)
def runTest(self): rec = sys.getrecursionlimit() obj = ['X'] copy = utils.deepcopy(obj, recursion=(rec + 1)) self.assertEqual(obj, copy) self.assertNotEquals(id(obj), id(copy))
def limited_recursion(recursion_limit): """ Prevent unlimited recursion. """ old_limit = sys.getrecursionlimit() sys.setrecursionlimit(recursion_limit) try: yield finally: sys.setrecursionlimit(old_limit)
def get_recursion_limit(): return sys.getrecursionlimit()
def test_accessibility_on_very_deep_graph(): gr = graph() gr.add_nodes(range(0,311)) # 2001 for i in range(0,310): #2000 gr.add_edge((i,i+1)) recursionlimit = getrecursionlimit() accessibility(gr) assert getrecursionlimit() == recursionlimit
def main(gr, n): recursionlimit = getrecursionlimit() for i in range(n): accessibility(gr) assert getrecursionlimit() == recursionlimit