Python re.purge() Examples

The following are code examples for showing how to use re.purge(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_locale_caching(self):
        # Issue #22410
        oldlocale = locale.setlocale(locale.LC_CTYPE)
        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
        for loc in 'en_US.iso88591', 'en_US.utf8':
            try:
                locale.setlocale(locale.LC_CTYPE, loc)
            except locale.Error:
                # Unsupported locale on this system
                self.skipTest('test needs %s locale' % loc)

        re.purge()
        self.check_en_US_iso88591()
        self.check_en_US_utf8()
        re.purge()
        self.check_en_US_utf8()
        self.check_en_US_iso88591() 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: test_re.py    GNU General Public License v3.0 6 votes vote down vote up
def test_other_escapes(self):
        self.checkPatternError("\\", 'bad escape (end of pattern)', 0)
        self.assertEqual(re.match(r"\(", '(').group(), '(')
        self.assertIsNone(re.match(r"\(", ')'))
        self.assertEqual(re.match(r"\\", '\\').group(), '\\')
        self.assertEqual(re.match(r"[\]]", ']').group(), ']')
        self.assertIsNone(re.match(r"[\]]", '['))
        self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
        self.assertIsNone(re.match(r"[a\-c]", 'b'))
        self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
        self.assertIsNone(re.match(r"[\^a]+", 'b'))
        re.purge()  # for warnings
        for c in 'ceghijklmopqyzCEFGHIJKLMNOPQRTVXY':
            with self.subTest(c):
                self.assertRaises(re.error, re.compile, '\\%c' % c)
        for c in 'ceghijklmopqyzABCEFGHIJKLMNOPQRTVXYZ':
            with self.subTest(c):
                self.assertRaises(re.error, re.compile, '[\\%c]' % c) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_re.py    GNU General Public License v3.0 6 votes vote down vote up
def test_locale_caching(self):
        # Issue #22410
        oldlocale = locale.setlocale(locale.LC_CTYPE)
        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
        for loc in 'en_US.iso88591', 'en_US.utf8':
            try:
                locale.setlocale(locale.LC_CTYPE, loc)
            except locale.Error:
                # Unsupported locale on this system
                self.skipTest('test needs %s locale' % loc)

        re.purge()
        self.check_en_US_iso88591()
        self.check_en_US_utf8()
        re.purge()
        self.check_en_US_utf8()
        self.check_en_US_iso88591() 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_re.py    GNU General Public License v3.0 6 votes vote down vote up
def test_pattern_compare_bytes(self):
        pattern1 = re.compile(b'abc')

        # equal: test bytes patterns
        re.purge()
        pattern2 = re.compile(b'abc')
        self.assertEqual(hash(pattern2), hash(pattern1))
        self.assertEqual(pattern2, pattern1)

        # not equal: pattern of a different types (str vs bytes),
        # comparison must not raise a BytesWarning
        re.purge()
        pattern3 = re.compile('abc')
        with warnings.catch_warnings():
            warnings.simplefilter('error', BytesWarning)
            self.assertNotEqual(pattern3, pattern1) 
Example 5
Project: ironpython2   Author: IronLanguages   File: test_re.py    Apache License 2.0 6 votes vote down vote up
def test_other_escapes(self):
        self.assertRaises(re.error, re.compile, "\\")
        self.assertEqual(re.match(r"\(", '(').group(), '(')
        self.assertIsNone(re.match(r"\(", ')'))
        self.assertEqual(re.match(r"\\", '\\').group(), '\\')
        self.assertEqual(re.match(r"[\]]", ']').group(), ']')
        self.assertIsNone(re.match(r"[\]]", '['))
        self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
        self.assertIsNone(re.match(r"[a\-c]", 'b'))
        self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
        self.assertIsNone(re.match(r"[\^a]+", 'b'))
        re.purge()  # for warnings
        for c in 'ceghijklmopquyzCEFGHIJKLMNOPQRTUVXY':
            warn = FutureWarning if c in 'Uu' else DeprecationWarning
            with check_py3k_warnings(('', warn)):
                self.assertEqual(re.match('\\%c$' % c, c).group(), c)
                self.assertIsNone(re.match('\\%c' % c, 'a'))
        for c in 'ceghijklmopquyzABCEFGHIJKLMNOPQRTUVXYZ':
            warn = FutureWarning if c in 'Uu' else DeprecationWarning
            with check_py3k_warnings(('', warn)):
                self.assertEqual(re.match('[\\%c]$' % c, c).group(), c)
                self.assertIsNone(re.match('[\\%c]' % c, 'a')) 
Example 6
Project: ironpython2   Author: IronLanguages   File: test_re.py    Apache License 2.0 6 votes vote down vote up
def test_locale_caching(self):
        # Issue #22410
        oldlocale = locale.setlocale(locale.LC_CTYPE)
        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
        for loc in 'en_US.iso88591', 'en_US.utf8':
            try:
                locale.setlocale(locale.LC_CTYPE, loc)
            except locale.Error:
                # Unsupported locale on this system
                self.skipTest('test needs %s locale' % loc)

        re.purge()
        self.check_en_US_iso88591()
        self.check_en_US_utf8()
        re.purge()
        self.check_en_US_utf8()
        self.check_en_US_iso88591() 
Example 7
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_re.py    GNU General Public License v2.0 6 votes vote down vote up
def test_other_escapes(self):
        self.checkPatternError("\\", 'bad escape (end of pattern)', 0)
        self.assertEqual(re.match(r"\(", '(').group(), '(')
        self.assertIsNone(re.match(r"\(", ')'))
        self.assertEqual(re.match(r"\\", '\\').group(), '\\')
        self.assertEqual(re.match(r"[\]]", ']').group(), ']')
        self.assertIsNone(re.match(r"[\]]", '['))
        self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
        self.assertIsNone(re.match(r"[a\-c]", 'b'))
        self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
        self.assertIsNone(re.match(r"[\^a]+", 'b'))
        re.purge()  # for warnings
        for c in 'ceghijklmopqyzCEFGHIJKLMNOPQRTVXY':
            with self.subTest(c):
                self.assertRaises(re.error, re.compile, '\\%c' % c)
        for c in 'ceghijklmopqyzABCEFGHIJKLMNOPQRTVXYZ':
            with self.subTest(c):
                self.assertRaises(re.error, re.compile, '[\\%c]' % c) 
Example 8
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_re.py    GNU General Public License v2.0 6 votes vote down vote up
def test_locale_caching(self):
        # Issue #22410
        oldlocale = locale.setlocale(locale.LC_CTYPE)
        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
        for loc in 'en_US.iso88591', 'en_US.utf8':
            try:
                locale.setlocale(locale.LC_CTYPE, loc)
            except locale.Error:
                # Unsupported locale on this system
                self.skipTest('test needs %s locale' % loc)

        re.purge()
        self.check_en_US_iso88591()
        self.check_en_US_utf8()
        re.purge()
        self.check_en_US_utf8()
        self.check_en_US_iso88591() 
Example 9
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_re.py    GNU General Public License v2.0 6 votes vote down vote up
def test_pattern_compare_bytes(self):
        pattern1 = re.compile(b'abc')

        # equal: test bytes patterns
        re.purge()
        pattern2 = re.compile(b'abc')
        self.assertEqual(hash(pattern2), hash(pattern1))
        self.assertEqual(pattern2, pattern1)

        # not equal: pattern of a different types (str vs bytes),
        # comparison must not raise a BytesWarning
        re.purge()
        pattern3 = re.compile('abc')
        with warnings.catch_warnings():
            warnings.simplefilter('error', BytesWarning)
            self.assertNotEqual(pattern3, pattern1) 
Example 10
Project: oss-ftp   Author: aliyun   File: test_re.py    MIT License 6 votes vote down vote up
def test_locale_caching(self):
        # Issue #22410
        oldlocale = locale.setlocale(locale.LC_CTYPE)
        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
        for loc in 'en_US.iso88591', 'en_US.utf8':
            try:
                locale.setlocale(locale.LC_CTYPE, loc)
            except locale.Error:
                # Unsupported locale on this system
                self.skipTest('test needs %s locale' % loc)

        re.purge()
        self.check_en_US_iso88591()
        self.check_en_US_utf8()
        re.purge()
        self.check_en_US_utf8()
        self.check_en_US_iso88591() 
Example 11
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_re.py    GNU General Public License v3.0 6 votes vote down vote up
def test_locale_caching(self):
        # Issue #22410
        oldlocale = locale.setlocale(locale.LC_CTYPE)
        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
        for loc in 'en_US.iso88591', 'en_US.utf8':
            try:
                locale.setlocale(locale.LC_CTYPE, loc)
            except locale.Error:
                # Unsupported locale on this system
                self.skipTest('test needs %s locale' % loc)

        re.purge()
        self.check_en_US_iso88591()
        self.check_en_US_utf8()
        re.purge()
        self.check_en_US_utf8()
        self.check_en_US_iso88591() 
Example 12
Project: cells   Author: AlesTsurko   File: test_re.py    MIT License 6 votes vote down vote up
def test_other_escapes(self):
        self.checkPatternError("\\", 'bad escape (end of pattern)', 0)
        self.assertEqual(re.match(r"\(", '(').group(), '(')
        self.assertIsNone(re.match(r"\(", ')'))
        self.assertEqual(re.match(r"\\", '\\').group(), '\\')
        self.assertEqual(re.match(r"[\]]", ']').group(), ']')
        self.assertIsNone(re.match(r"[\]]", '['))
        self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
        self.assertIsNone(re.match(r"[a\-c]", 'b'))
        self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
        self.assertIsNone(re.match(r"[\^a]+", 'b'))
        re.purge()  # for warnings
        for c in 'ceghijklmopqyzCEFGHIJKLMNOPQRTVXY':
            with self.subTest(c):
                self.assertRaises(re.error, re.compile, '\\%c' % c)
        for c in 'ceghijklmopqyzABCEFGHIJKLMNOPQRTVXYZ':
            with self.subTest(c):
                self.assertRaises(re.error, re.compile, '[\\%c]' % c) 
Example 13
Project: cells   Author: AlesTsurko   File: test_re.py    MIT License 6 votes vote down vote up
def test_locale_caching(self):
        # Issue #22410
        oldlocale = locale.setlocale(locale.LC_CTYPE)
        self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
        for loc in 'en_US.iso88591', 'en_US.utf8':
            try:
                locale.setlocale(locale.LC_CTYPE, loc)
            except locale.Error:
                # Unsupported locale on this system
                self.skipTest('test needs %s locale' % loc)

        re.purge()
        self.check_en_US_iso88591()
        self.check_en_US_utf8()
        re.purge()
        self.check_en_US_utf8()
        self.check_en_US_iso88591() 
Example 14
Project: cells   Author: AlesTsurko   File: test_re.py    MIT License 6 votes vote down vote up
def test_pattern_compare_bytes(self):
        pattern1 = re.compile(b'abc')

        # equal: test bytes patterns
        re.purge()
        pattern2 = re.compile(b'abc')
        self.assertEqual(hash(pattern2), hash(pattern1))
        self.assertEqual(pattern2, pattern1)

        # not equal: pattern of a different types (str vs bytes),
        # comparison must not raise a BytesWarning
        re.purge()
        pattern3 = re.compile('abc')
        with warnings.catch_warnings():
            warnings.simplefilter('error', BytesWarning)
            self.assertNotEqual(pattern3, pattern1) 
Example 15
Project: xstrings   Author: elicn   File: xstrings.py    The Unlicense 5 votes vote down vote up
def finditer(content, encodings, charset, min_size):
    '''Generator function that iterates over all string matches inside the given content which are at least
    min_size characters long.

    @param    content    Binary content to search in
    @param    encodings  Dictionary of encoding functions
    @param    charset    An interable object containing the characters to consider as part of a string
    @param    min_size   Minimal string size to consider as a string match

    @return A tuple containing the match offset in content, encoding name, encoding key and the deobfuscated
            string reconstructed from the blob found
    '''

    # iterate over available encoding fucntions
    for encoding_name, (encoding_function, encoding_range) in encodings.items():

        # iterate over all keys in range for that encoding function
        for key in encoding_range:
            encoded_charset = encoding_function(charset, key)

            pattern = '[%s]{%d,}' % (re.escape(encoded_charset), min_size)

            for match in re.finditer(pattern, content):
                # deobfuscation: reconstruct the original string
                deobf = ''.join(charset[encoded_charset.index(c)] for c in match.group(0))

                yield (match.start(0), encoding_name, key, deobf)

        # cleanup regex cache once in a while
        re.purge() 
Example 16
Project: robot-navigation   Author: ronaldahmed   File: CompoundAction.py    MIT License 5 votes vote down vote up
def __init__(self, frames, instructID='', index=0, subplan=False):
        self.CaughtError=None
        self.CaughtErrorTxt=''
        
        plan = []
        if not subplan:
            Thing.referenceCache = {}
            re.purge()
        
        for i,frame in enumerate(frames):
            j = 0
            try:
                subframes = grab(frame,'S')
                if not subframes:
                    frame2action(frame, plan, (i,j), index)
                    continue
                keys = [key for key in frame.feature_names()
                        if valCanonical(key) not in ('Then',',','Cond','Loc','Cc')]
                keys.sort()
                for key in keys:
                    subframe = frame[key]
                    applyConditions(frame, subframe)
                    #print i,j,key,repr(subframe)
                    plan.extend(Plan([subframe], index=len(plan)+index, subplan=True))
                    j += 1
            except (TypeError,AttributeError),e: #None
                self.CaughtError = e
                self.CaughtErrorTxt = "Can't interpret: "+`frame`+str(e)
                logger.error("%s",self.CaughtErrorTxt) 
Example 17
Project: NiujiaoDebugger   Author: MrSrc   File: test_re.py    GNU General Public License v3.0 5 votes vote down vote up
def test_pattern_compare(self):
        pattern1 = re.compile('abc', re.IGNORECASE)

        # equal to itself
        self.assertEqual(pattern1, pattern1)
        self.assertFalse(pattern1 != pattern1)

        # equal
        re.purge()
        pattern2 = re.compile('abc', re.IGNORECASE)
        self.assertEqual(hash(pattern2), hash(pattern1))
        self.assertEqual(pattern2, pattern1)

        # not equal: different pattern
        re.purge()
        pattern3 = re.compile('XYZ', re.IGNORECASE)
        # Don't test hash(pattern3) != hash(pattern1) because there is no
        # warranty that hash values are different
        self.assertNotEqual(pattern3, pattern1)

        # not equal: different flag (flags=0)
        re.purge()
        pattern4 = re.compile('abc')
        self.assertNotEqual(pattern4, pattern1)

        # only == and != comparison operators are supported
        with self.assertRaises(TypeError):
            pattern1 < pattern2 
Example 18
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_re.py    GNU General Public License v2.0 5 votes vote down vote up
def test_pattern_compare(self):
        pattern1 = re.compile('abc', re.IGNORECASE)

        # equal to itself
        self.assertEqual(pattern1, pattern1)
        self.assertFalse(pattern1 != pattern1)

        # equal
        re.purge()
        pattern2 = re.compile('abc', re.IGNORECASE)
        self.assertEqual(hash(pattern2), hash(pattern1))
        self.assertEqual(pattern2, pattern1)

        # not equal: different pattern
        re.purge()
        pattern3 = re.compile('XYZ', re.IGNORECASE)
        # Don't test hash(pattern3) != hash(pattern1) because there is no
        # warranty that hash values are different
        self.assertNotEqual(pattern3, pattern1)

        # not equal: different flag (flags=0)
        re.purge()
        pattern4 = re.compile('abc')
        self.assertNotEqual(pattern4, pattern1)

        # only == and != comparison operators are supported
        with self.assertRaises(TypeError):
            pattern1 < pattern2 
Example 19
Project: Hot   Author: dsolimando   File: regrtest.py    GNU General Public License v3.0 5 votes vote down vote up
def dash_R_cleanup(fs, ps, pic):
    import gc, copy_reg
    import _strptime, linecache, dircache
    import urlparse, urllib, urllib2, mimetypes, doctest
    import struct, filecmp
    from distutils.dir_util import _path_created

    # Restore some original values.
    warnings.filters[:] = fs
    copy_reg.dispatch_table.clear()
    copy_reg.dispatch_table.update(ps)
    sys.path_importer_cache.clear()
    sys.path_importer_cache.update(pic)

    # Clear assorted module caches.
    _path_created.clear()
    re.purge()
    _strptime._regex_cache.clear()
    urlparse.clear_cache()
    urllib.urlcleanup()
    urllib2.install_opener(None)
    dircache.reset()
    linecache.clearcache()
    mimetypes._default_mime_types()
    struct._cache.clear()
    filecmp._cache.clear()
    doctest.master = None

    # Collect cyclic trash.
    gc.collect() 
Example 20
Project: hubangl   Author: soonum   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def asciiconvert(user_input, enable_spechar=True):
    """
    Converts user-input string into ASCII.

    Returns a string with ASCII chars only
    """
    SPECHAR_RE = r'[\s.?!:;§*^¨%$\|\[\]\(\)\{\}+=`~\'\"\\&]*'
    accented_chars = [(r'[àäâ]*', 'a'),
                      (r'[éèëê]*', 'e'),
                      (r'[ìîï]*', 'i'),
                      (r'[òöô]*', 'o'),
                      (r'[ùûü]*', 'u'),
                      (r'[ÿŷỳ]*', 'y')]

    if not enable_spechar:
        spechar = re.compile(SPECHAR_RE)
        ans = spechar.findall(user_input)
        if ans:
            # Replacing all occurrences by an empty string
            user_input = spechar.sub('', user_input, count=0)
            re.purge()

    for pattern, repl in accented_chars:
        accented = re.compile(pattern)
        # Replacing all occurrences by a non-accented char
        user_input = accented.sub(repl, user_input, count=0)
        re.purge()

    return user_input 
Example 21
Project: WebScraping   Author: liinnux   File: performance.py    Apache License 2.0 5 votes vote down vote up
def main():
    times = {}
    html = urllib2.urlopen('http://example.webscraping.com/view/United-Kingdom-239').read()
    NUM_ITERATIONS = 1000 # number of times to test each scraper
    for name, scraper in ('Regular expressions', regex_scraper), ('Beautiful Soup', beautiful_soup_scraper), ('Lxml', lxml_scraper):
        times[name] = []
        # record start time of scrape
        start = time.time()
        for i in range(NUM_ITERATIONS):
            if scraper == regex_scraper:
                # the regular expression module will cache results
                # so need to purge this cache for meaningful timings
                re.purge() 
            result = scraper(html)

            # check scraped result is as expected
            assert(result['area'] == '244,820 square kilometres')
            times[name].append(time.time() - start)
        # record end time of scrape and output the total
        end = time.time()
        print '{}: {:.2f} seconds'.format(name, end - start)

    writer = csv.writer(open('times.csv', 'w'))
    header = sorted(times.keys())
    writer.writerow(header)
    for row in zip(*[times[scraper] for scraper in header]):
        writer.writerow(row) 
Example 22
Project: pyhow   Author: yoeo   File: re.py    MIT License 5 votes vote down vote up
def purge():
    """re.purge: Purge internal regular expressions cache."""

    def _cache_empty():
        return not getattr(re, '_cache')

    re.match('', '')
    cache_created = not _cache_empty()
    re.purge()
    return cache_created and _cache_empty() and "empty cache"


# category: expressions 
Example 23
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_re.py    GNU General Public License v3.0 5 votes vote down vote up
def test_other_escapes(self):
        self.checkPatternError("\\", 'bad escape (end of pattern)', 0)
        self.assertEqual(re.match(r"\(", '(').group(), '(')
        self.assertIsNone(re.match(r"\(", ')'))
        self.assertEqual(re.match(r"\\", '\\').group(), '\\')
        self.assertEqual(re.match(r"[\]]", ']').group(), ']')
        self.assertIsNone(re.match(r"[\]]", '['))
        self.assertEqual(re.match(r"[a\-c]", '-').group(), '-')
        self.assertIsNone(re.match(r"[a\-c]", 'b'))
        self.assertEqual(re.match(r"[\^a]+", 'a^').group(), 'a^')
        self.assertIsNone(re.match(r"[\^a]+", 'b'))
        re.purge()  # for warnings
        for c in 'ceghijklmopqyzCEFGHIJKLMNOPQRTVXY':
            with self.subTest(c):
                with self.assertWarns(DeprecationWarning) as warns:
                    self.assertEqual(re.fullmatch('\\%c' % c, c).group(), c)
                    self.assertIsNone(re.match('\\%c' % c, 'a'))
                self.assertRegex(str(warns.warnings[0].message), 'bad escape')
                self.assertEqual(warns.warnings[0].filename, __file__)
        for c in 'ceghijklmopqyzABCEFGHIJKLMNOPQRTVXYZ':
            with self.subTest(c):
                with self.assertWarns(DeprecationWarning) as warns:
                    self.assertEqual(re.fullmatch('[\\%c]' % c, c).group(), c)
                    self.assertIsNone(re.match('[\\%c]' % c, 'a'))
                self.assertRegex(str(warns.warnings[0].message), 'bad escape')
                self.assertEqual(warns.warnings[0].filename, __file__) 
Example 24
Project: cells   Author: AlesTsurko   File: test_re.py    MIT License 5 votes vote down vote up
def test_pattern_compare(self):
        pattern1 = re.compile('abc', re.IGNORECASE)

        # equal to itself
        self.assertEqual(pattern1, pattern1)
        self.assertFalse(pattern1 != pattern1)

        # equal
        re.purge()
        pattern2 = re.compile('abc', re.IGNORECASE)
        self.assertEqual(hash(pattern2), hash(pattern1))
        self.assertEqual(pattern2, pattern1)

        # not equal: different pattern
        re.purge()
        pattern3 = re.compile('XYZ', re.IGNORECASE)
        # Don't test hash(pattern3) != hash(pattern1) because there is no
        # warranty that hash values are different
        self.assertNotEqual(pattern3, pattern1)

        # not equal: different flag (flags=0)
        re.purge()
        pattern4 = re.compile('abc')
        self.assertNotEqual(pattern4, pattern1)

        # only == and != comparison operators are supported
        with self.assertRaises(TypeError):
            pattern1 < pattern2 
Example 25
Project: sublime-backrefs   Author: facelessuser   File: bre.py    MIT License 5 votes vote down vote up
def purge():
    """Purge caches."""

    _purge_cache()
    _re.purge() 
Example 26
Project: pyblish-win   Author: pyblish   File: regrtest.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def dash_R_cleanup(fs, ps, pic, zdc, abcs):
    import gc, copy_reg
    import _strptime, linecache
    dircache = test_support.import_module('dircache', deprecated=True)
    import urlparse, urllib, urllib2, mimetypes, doctest
    import struct, filecmp
    from distutils.dir_util import _path_created

    # Clear the warnings registry, so they can be displayed again
    for mod in sys.modules.values():
        if hasattr(mod, '__warningregistry__'):
            del mod.__warningregistry__

    # Restore some original values.
    warnings.filters[:] = fs
    copy_reg.dispatch_table.clear()
    copy_reg.dispatch_table.update(ps)
    sys.path_importer_cache.clear()
    sys.path_importer_cache.update(pic)
    try:
        import zipimport
    except ImportError:
        pass # Run unmodified on platforms without zipimport support
    else:
        zipimport._zip_directory_cache.clear()
        zipimport._zip_directory_cache.update(zdc)

    # clear type cache
    sys._clear_type_cache()

    # Clear ABC registries, restoring previously saved ABC registries.
    for abc, registry in abcs.items():
        abc._abc_registry = registry.copy()
        abc._abc_cache.clear()
        abc._abc_negative_cache.clear()

    # Clear assorted module caches.
    _path_created.clear()
    re.purge()
    _strptime._regex_cache.clear()
    urlparse.clear_cache()
    urllib.urlcleanup()
    urllib2.install_opener(None)
    dircache.reset()
    linecache.clearcache()
    mimetypes._default_mime_types()
    filecmp._cache.clear()
    struct._clearcache()
    doctest.master = None
    try:
        import ctypes
    except ImportError:
        # Don't worry about resetting the cache if ctypes is not supported
        pass
    else:
        ctypes._reset_cache()

    # Collect cyclic trash.
    gc.collect() 
Example 27
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_catalog.py    GNU General Public License v3.0 4 votes vote down vote up
def test_add_function_ordered(self):
        backup_dir = clear_temp_catalog()
        q = catalog.catalog()

        q.add_function('f',string.upper)
        q.add_function('f',string.lower)
        q.add_function('ff',string.find)
        q.add_function('ff',string.replace)
        q.add_function('fff',string.atof)
        q.add_function('fff',string.atoi)
        del q

        # now we're gonna make a new catalog with same code
        # but different functions in a specified module directory
        env_dir = empty_temp_dir()
        r = catalog.catalog(env_dir)
        r.add_function('ff',os.abort)
        r.add_function('ff',os.chdir)
        r.add_function('fff',os.access)
        r.add_function('fff',os.open)
        del r
        # now we're gonna make a new catalog with same code
        # but different functions in a user specified directory
        user_dir = empty_temp_dir()
        s = catalog.catalog(user_dir)
        s.add_function('fff',re.match)
        s.add_function('fff',re.purge)
        del s

        # open new catalog and make sure it retreives the functions
        # from d catalog instead of the temp catalog (made by q)
        os.environ['PYTHONCOMPILED'] = env_dir
        t = catalog.catalog(user_dir)
        funcs1 = t.get_functions('f')
        funcs2 = t.get_functions('ff')
        funcs3 = t.get_functions('fff')
        restore_temp_catalog(backup_dir)
        # make sure everything is read back in the correct order
        # a little cheating... I'm ignoring any functions that might have
        # been read in from a prior catalog file (such as the defualt one).
        # the test should really be made so that these aren't read in, but
        # until I get this figured out...
        #assert_(funcs1 == [string.lower,string.upper])
        #assert_(funcs2 == [os.chdir,os.abort,string.replace,string.find])
        #assert_(funcs3 == [re.purge,re.match,os.open,
        #                  os.access,string.atoi,string.atof])
        assert_(funcs1[:2] == [string.lower,string.upper]),repr(funcs1)
        assert_(funcs2[:4] == [os.chdir,os.abort,string.replace,string.find])
        assert_(funcs3[:6] == [re.purge,re.match,os.open,
                          os.access,string.atoi,string.atof])
        cleanup_temp_dir(user_dir)
        cleanup_temp_dir(env_dir) 
Example 28
Project: ironpython2   Author: IronLanguages   File: test_re.py    Apache License 2.0 4 votes vote down vote up
def test_inline_flags(self):
        # Bug #1700
        upper_char = unichr(0x1ea0) # Latin Capital Letter A with Dot Bellow
        lower_char = unichr(0x1ea1) # Latin Small Letter A with Dot Bellow

        p = re.compile(upper_char, re.I | re.U)
        q = p.match(lower_char)
        self.assertTrue(q)

        p = re.compile(lower_char, re.I | re.U)
        q = p.match(upper_char)
        self.assertTrue(q)

        p = re.compile('(?i)' + upper_char, re.U)
        q = p.match(lower_char)
        self.assertTrue(q)

        p = re.compile('(?i)' + lower_char, re.U)
        q = p.match(upper_char)
        self.assertTrue(q)

        p = re.compile('(?iu)' + upper_char)
        q = p.match(lower_char)
        self.assertTrue(q)

        p = re.compile('(?iu)' + lower_char)
        q = p.match(upper_char)
        self.assertTrue(q)

        self.assertTrue(re.match('(?ixu) ' + upper_char, lower_char))
        self.assertTrue(re.match('(?ixu) ' + lower_char, upper_char))

        # Incompatibilities
        re.purge()
        with check_py3k_warnings():
            re.compile('', re.LOCALE|re.UNICODE)
        with check_py3k_warnings():
            re.compile('(?L)', re.UNICODE)
        with check_py3k_warnings():
            re.compile('(?u)', re.LOCALE)
        with check_py3k_warnings():
            re.compile('(?Lu)')
        with check_py3k_warnings():
            re.compile('(?uL)') 
Example 29
Project: oss-ftp   Author: aliyun   File: regrtest.py    MIT License 4 votes vote down vote up
def dash_R_cleanup(fs, ps, pic, zdc, abcs):
    import gc, copy_reg
    import _strptime, linecache
    dircache = test_support.import_module('dircache', deprecated=True)
    import urlparse, urllib, urllib2, mimetypes, doctest
    import struct, filecmp
    from distutils.dir_util import _path_created

    # Clear the warnings registry, so they can be displayed again
    for mod in sys.modules.values():
        if hasattr(mod, '__warningregistry__'):
            del mod.__warningregistry__

    # Restore some original values.
    warnings.filters[:] = fs
    copy_reg.dispatch_table.clear()
    copy_reg.dispatch_table.update(ps)
    sys.path_importer_cache.clear()
    sys.path_importer_cache.update(pic)
    try:
        import zipimport
    except ImportError:
        pass # Run unmodified on platforms without zipimport support
    else:
        zipimport._zip_directory_cache.clear()
        zipimport._zip_directory_cache.update(zdc)

    # clear type cache
    sys._clear_type_cache()

    # Clear ABC registries, restoring previously saved ABC registries.
    for abc, registry in abcs.items():
        abc._abc_registry = registry.copy()
        abc._abc_cache.clear()
        abc._abc_negative_cache.clear()

    # Clear assorted module caches.
    _path_created.clear()
    re.purge()
    _strptime._regex_cache.clear()
    urlparse.clear_cache()
    urllib.urlcleanup()
    urllib2.install_opener(None)
    dircache.reset()
    linecache.clearcache()
    mimetypes._default_mime_types()
    filecmp._cache.clear()
    struct._clearcache()
    doctest.master = None
    try:
        import ctypes
    except ImportError:
        # Don't worry about resetting the cache if ctypes is not supported
        pass
    else:
        ctypes._reset_cache()

    # Collect cyclic trash.
    gc.collect() 
Example 30
Project: poker   Author: surgebiswas   File: test_catalog.py    MIT License 4 votes vote down vote up
def test_add_function_ordered(self):
        backup_dir = clear_temp_catalog()
        q = catalog.catalog()

        q.add_function('f',string.upper)
        q.add_function('f',string.lower)
        q.add_function('ff',string.find)
        q.add_function('ff',string.replace)
        q.add_function('fff',string.atof)
        q.add_function('fff',string.atoi)
        del q

        # now we're gonna make a new catalog with same code
        # but different functions in a specified module directory
        env_dir = empty_temp_dir()
        r = catalog.catalog(env_dir)
        r.add_function('ff',os.abort)
        r.add_function('ff',os.chdir)
        r.add_function('fff',os.access)
        r.add_function('fff',os.open)
        del r
        # now we're gonna make a new catalog with same code
        # but different functions in a user specified directory
        user_dir = empty_temp_dir()
        s = catalog.catalog(user_dir)
        s.add_function('fff',re.match)
        s.add_function('fff',re.purge)
        del s

        # open new catalog and make sure it retreives the functions
        # from d catalog instead of the temp catalog (made by q)
        os.environ['PYTHONCOMPILED'] = env_dir
        t = catalog.catalog(user_dir)
        funcs1 = t.get_functions('f')
        funcs2 = t.get_functions('ff')
        funcs3 = t.get_functions('fff')
        restore_temp_catalog(backup_dir)
        # make sure everything is read back in the correct order
        # a little cheating... I'm ignoring any functions that might have
        # been read in from a prior catalog file (such as the defualt one).
        # the test should really be made so that these aren't read in, but
        # until I get this figured out...
        #assert_(funcs1 == [string.lower,string.upper])
        #assert_(funcs2 == [os.chdir,os.abort,string.replace,string.find])
        #assert_(funcs3 == [re.purge,re.match,os.open,
        #                  os.access,string.atoi,string.atof])
        assert_(funcs1[:2] == [string.lower,string.upper]),repr(funcs1)
        assert_(funcs2[:4] == [os.chdir,os.abort,string.replace,string.find])
        assert_(funcs3[:6] == [re.purge,re.match,os.open,
                          os.access,string.atoi,string.atof])
        cleanup_temp_dir(user_dir)
        cleanup_temp_dir(env_dir) 
Example 31
Project: linux-cross-gcc   Author: nmercier   File: regrtest.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def dash_R_cleanup(fs, ps, pic, zdc, abcs):
    import gc, copy_reg
    import _strptime, linecache
    dircache = test_support.import_module('dircache', deprecated=True)
    import urlparse, urllib, urllib2, mimetypes, doctest
    import struct, filecmp
    from distutils.dir_util import _path_created

    # Clear the warnings registry, so they can be displayed again
    for mod in sys.modules.values():
        if hasattr(mod, '__warningregistry__'):
            del mod.__warningregistry__

    # Restore some original values.
    warnings.filters[:] = fs
    copy_reg.dispatch_table.clear()
    copy_reg.dispatch_table.update(ps)
    sys.path_importer_cache.clear()
    sys.path_importer_cache.update(pic)
    try:
        import zipimport
    except ImportError:
        pass # Run unmodified on platforms without zipimport support
    else:
        zipimport._zip_directory_cache.clear()
        zipimport._zip_directory_cache.update(zdc)

    # clear type cache
    sys._clear_type_cache()

    # Clear ABC registries, restoring previously saved ABC registries.
    for abc, registry in abcs.items():
        abc._abc_registry = registry.copy()
        abc._abc_cache.clear()
        abc._abc_negative_cache.clear()

    # Clear assorted module caches.
    _path_created.clear()
    re.purge()
    _strptime._regex_cache.clear()
    urlparse.clear_cache()
    urllib.urlcleanup()
    urllib2.install_opener(None)
    dircache.reset()
    linecache.clearcache()
    mimetypes._default_mime_types()
    filecmp._cache.clear()
    struct._clearcache()
    doctest.master = None
    try:
        import ctypes
    except ImportError:
        # Don't worry about resetting the cache if ctypes is not supported
        pass
    else:
        ctypes._reset_cache()

    # Collect cyclic trash.
    gc.collect() 
Example 32
Project: namestack   Author: proxeIO   File: auto.py    GNU General Public License v3.0 4 votes vote down vote up
def process(self, context, collection):
    '''
        Process collection, send names to rename and shared sort.
    '''

    # compare
    compare = []

    # clean
    clean = []

    # clean duplicates
    for name in collection:

        # remove duplicates
        if name[3][0] not in compare:

            # append
            compare.append(name[3][0])
            clean.append(name)

    # done with collection
    collection.clear()

    # name
    for i, name in enumerate(clean):
        rename(self, context, name, i)

    # randomize names (prevents conflicts)
    for name in clean:

        # randomize name
        name[3][0].name = str(random())

    # is shared sort or shared count
    if context.window_manager.BatchShared.sort or context.window_manager.BatchShared.count:

        # sort
        shared.main(self, context, clean, context.window_manager.BatchShared)

    # isnt shared sort or shared count
    else:

        # apply names
        for name in clean:
            name[3][0].name = name[1]

            # count
            if name[1] != name[2]:
                self.count += 1

    # purge re
    re.purge()

# object