Python re.search() Examples

The following are code examples for showing how to use re.search(). 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: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def parse_hostname(sitename):
    parsed_url = urllib.parse.urlparse(sitename)
    hostname = parsed_url.netloc
    if hostname == '':
        # If you pass in 'facebook.com/foo' urlparse treats it all as the path
        match = re.match(r'[^/]+', parsed_url.path)
        if match == None:
            print('ERROR: Unable to make the provided sitename into a hostname: ' + parsed_url.path)
            sys.exit(1)
        hostname = match.group(0)

    www_matcher = r'^www\.(.+)'
    if re.search(www_matcher, hostname) != None:
        hostname = re.sub(www_matcher, r'\1', hostname)

    return hostname 
Example 2
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def nullify_site(sitename):
    hostname = parse_hostname(sitename)

    hostfile = ManagedHostfile()
    managed = hostfile.current_body()

    null_matcher = HOST_MATCHER.format(hostname)
    neuter_matcher = COMMENTED_MATCHER.format(hostname)
    if re.search(null_matcher, managed, flags=re.MULTILINE) != None:
        # if it's not commented, we ignore it
        print(hostname + ' has already been sent to webnull')
        sys.exit(0)
    elif re.search(neuter_matcher, managed, flags=re.MULTILINE) != None:
        # if it's commented, we replace it
        hostfile.transform_body(neuter_matcher, r'\1')
    else:
        # if it's not there, we write it.
        ip5null = '127.0.0.1\t'
        ip6null = '::1\t\t'

        for null in [ip5null, ip6null]:
            for www in ['', 'www.']:
                managed += (null + www + hostname + '\n')

        hostfile.write_body(managed) 
Example 3
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def test_string_boundaries(self):
        # See http://bugs.python.org/issue10713
        self.assertEqual(re.search(r"\b(abc)\b", "abc").group(1),
                         "abc")
        # There's a word boundary at the start of a string.
        self.assertTrue(re.match(r"\b", "abc"))
        # A non-empty string includes a non-boundary zero-length match.
        self.assertTrue(re.search(r"\B", "abc"))
        # There is no non-boundary match at the start of a string.
        self.assertFalse(re.match(r"\B", "abc"))
        # However, an empty string contains no word boundaries, and also no
        # non-boundaries.
        self.assertIsNone(re.search(r"\B", ""))
        # This one is questionable and different from the perlre behaviour,
        # but describes current behavior.
        self.assertIsNone(re.search(r"\b", ""))
        # A single word-character string has two boundaries, but no
        # non-boundary gaps.
        self.assertEqual(len(re.findall(r"\b", "a")), 2)
        self.assertEqual(len(re.findall(r"\B", "a")), 0)
        # If there are no words, there are no boundaries
        self.assertEqual(len(re.findall(r"\b", " ")), 0)
        self.assertEqual(len(re.findall(r"\b", "   ")), 0)
        # Can match around the whitespace.
        self.assertEqual(len(re.findall(r"\B", " ")), 2) 
Example 4
Project: leapp-repository   Author: oamg   File: lib_spamc.py    Apache License 2.0 6 votes vote down vote up
def _rewrite_spamc_config(content):
    res_lines = []
    read_ssl_option = False
    for line in content.split('\n'):
        if line.startswith('#'):
            res_lines.append(line)
            continue
        if read_ssl_option:
            line = re.sub(r'^\s*(sslv3|tlsv1)', '', line)
            read_ssl_option = False
        if re.search(r'(?<!\S)--ssl\s*$', line):
            read_ssl_option = True
        line = re.sub(r'(?<!\S)--ssl(\s+|=)(sslv3|tlsv1)(?!\S)', '--ssl', line)
        res_lines.append(line)
    res = '\n'.join(res_lines)
    return res 
Example 5
Project: pyblish-win   Author: pyblish   File: _osx_support.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _check_for_unavailable_sdk(_config_vars):
    """Remove references to any SDKs not available"""
    # If we're on OSX 10.5 or later and the user tries to
    # compile an extension using an SDK that is not present
    # on the current machine it is better to not use an SDK
    # than to fail.  This is particularly important with
    # the standalone Command Line Tools alternative to a
    # full-blown Xcode install since the CLT packages do not
    # provide SDKs.  If the SDK is not present, it is assumed
    # that the header files and dev libs have been installed
    # to /usr and /System/Library by either a standalone CLT
    # package or the CLT component within Xcode.
    cflags = _config_vars.get('CFLAGS', '')
    m = re.search(r'-isysroot\s+(\S+)', cflags)
    if m is not None:
        sdk = m.group(1)
        if not os.path.exists(sdk):
            for cv in _UNIVERSAL_CONFIG_VARS:
                # Do not alter a config var explicitly overriden by env var
                if cv in _config_vars and cv not in os.environ:
                    flags = _config_vars[cv]
                    flags = re.sub(r'-isysroot\s+\S+(?:\s|$)', ' ', flags)
                    _save_modified_value(_config_vars, cv, flags)

    return _config_vars 
Example 6
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def join_header_words(lists):
    """Do the inverse (almost) of the conversion done by split_header_words.

    Takes a list of lists of (key, value) pairs and produces a single header
    value.  Attribute values are quoted if needed.

    >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]])
    'text/plain; charset="iso-8859/1"'
    >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]])
    'text/plain, charset="iso-8859/1"'

    """
    headers = []
    for pairs in lists:
        attr = []
        for k, v in pairs:
            if v is not None:
                if not re.search(r"^\w+$", v):
                    v = HEADER_JOIN_ESCAPE_RE.sub(r"\\\1", v)  # escape " and \
                    v = '"%s"' % v
                k = "%s=%s" % (k, v)
            attr.append(k)
        if attr: headers.append("; ".join(attr))
    return ", ".join(headers) 
Example 7
Project: pyblish-win   Author: pyblish   File: pipes.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def append(self, cmd, kind):
        """t.append(cmd, kind) adds a new step at the end."""
        if type(cmd) is not type(''):
            raise TypeError, \
                  'Template.append: cmd must be a string'
        if kind not in stepkinds:
            raise ValueError, \
                  'Template.append: bad kind %r' % (kind,)
        if kind == SOURCE:
            raise ValueError, \
                  'Template.append: SOURCE can only be prepended'
        if self.steps and self.steps[-1][1] == SINK:
            raise ValueError, \
                  'Template.append: already ends with SINK'
        if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
            raise ValueError, \
                  'Template.append: missing $IN in cmd'
        if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
            raise ValueError, \
                  'Template.append: missing $OUT in cmd'
        self.steps.append((cmd, kind)) 
Example 8
Project: pyblish-win   Author: pyblish   File: pipes.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def prepend(self, cmd, kind):
        """t.prepend(cmd, kind) adds a new step at the front."""
        if type(cmd) is not type(''):
            raise TypeError, \
                  'Template.prepend: cmd must be a string'
        if kind not in stepkinds:
            raise ValueError, \
                  'Template.prepend: bad kind %r' % (kind,)
        if kind == SINK:
            raise ValueError, \
                  'Template.prepend: SINK can only be appended'
        if self.steps and self.steps[0][1] == SOURCE:
            raise ValueError, \
                  'Template.prepend: already begins with SOURCE'
        if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
            raise ValueError, \
                  'Template.prepend: missing $IN in cmd'
        if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
            raise ValueError, \
                  'Template.prepend: missing $OUT in cmd'
        self.steps.insert(0, (cmd, kind)) 
Example 9
Project: pyblish-win   Author: pyblish   File: msvc9compiler.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """
        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in os.environ['Path'].split(';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 10
Project: pyblish-win   Author: pyblish   File: base64.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def b16decode(s, casefold=False):
    """Decode a Base16 encoded string.

    s is the string to decode.  Optional casefold is a flag specifying whether
    a lowercase alphabet is acceptable as input.  For security purposes, the
    default is False.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if casefold:
        s = s.upper()
    if re.search('[^0-9A-F]', s):
        raise TypeError('Non-base16 digit found')
    return binascii.unhexlify(s)



# Legacy interface.  This code could be cleaned up since I don't believe
# binascii has any line length limitations.  It just doesn't seem worth it
# though. 
Example 11
Project: pyblish-win   Author: pyblish   File: test_syntax.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _check_error(self, code, errtext,
                     filename="<testcase>", mode="exec", subclass=None):
        """Check that compiling code raises SyntaxError with errtext.

        errtest is a regular expression that must be present in the
        test of the exception raised.  If subclass is specified it
        is the expected subclass of SyntaxError (e.g. IndentationError).
        """
        try:
            compile(code, filename, mode)
        except SyntaxError, err:
            if subclass and not isinstance(err, subclass):
                self.fail("SyntaxError is not a %s" % subclass.__name__)
            mo = re.search(errtext, str(err))
            if mo is None:
                self.fail("%s did not contain '%r'" % (err, errtext,)) 
Example 12
Project: pyblish-win   Author: pyblish   File: PyShell.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def recall(self, s, event):
        # remove leading and trailing empty or whitespace lines
        s = re.sub(r'^\s*\n', '' , s)
        s = re.sub(r'\n\s*$', '', s)
        lines = s.split('\n')
        self.text.undo_block_start()
        try:
            self.text.tag_remove("sel", "1.0", "end")
            self.text.mark_set("insert", "end-1c")
            prefix = self.text.get("insert linestart", "insert")
            if prefix.rstrip().endswith(':'):
                self.newline_and_indent_event(event)
                prefix = self.text.get("insert linestart", "insert")
            self.text.insert("insert", lines[0].strip())
            if len(lines) > 1:
                orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
                new_base_indent  = re.search(r'^([ \t]*)', prefix).group(0)
                for line in lines[1:]:
                    if line.startswith(orig_base_indent):
                        # replace orig base indentation with new indentation
                        line = new_base_indent + line[len(orig_base_indent):]
                    self.text.insert('insert', '\n'+line.rstrip())
        finally:
            self.text.see("insert")
            self.text.undo_block_stop() 
Example 13
Project: backtrader-cn   Author: pandalibin   File: sina.py    GNU General Public License v3.0 6 votes vote down vote up
def get_stock_price(self, symbol):
        """
        获取股票当前价格
        :param symbol:
        :return:
        """
        url = "http://hq.sinajs.cn/list=s_%s" % symbol
        r = self.session.get(url)
        m = re.search(r'"(.*)"', r.text)
        if m and m.groups()[0]:
            name, price, _, _, _, _ = m.groups()[0].split(',')
            logger.info("股票[%s](%s)当前价格为: %s" % (name, symbol, price))
            return price
        else:
            logger.error("获取股票%s当前价格失败" % symbol)
            raise StockMatchError()

    # fixme: 该方法暂时只支持买入A股,不支持操作美股和港股 
Example 14
Project: BERT-Classification-Tutorial   Author: Socialbird-AILab   File: optimization.py    Apache License 2.0 5 votes vote down vote up
def _do_use_weight_decay(self, param_name):
        """Whether to use L2 weight decay for `param_name`."""
        if not self.weight_decay_rate:
            return False
        if self.exclude_from_weight_decay:
            for r in self.exclude_from_weight_decay:
                if re.search(r, param_name) is not None:
                    return False
        return True 
Example 15
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def step_detect_sssd_features(self, profile):
        if profile != "sssd":
            return []

        # sudoers: sss
        result = re.search(
            "^[ \t]*sudoers[ \t]*:.*sss.*$",
            self.nsswitch,
            re.MULTILINE
        )

        features = []

        if result is not None:
            features.append("with-sudo")

        # SSSD Smartcard support
        # We enable smartcard support only if it was not handled by pam_pkcs11.
        # Otherwise pam_pkcs11 configuration must be converted manually.
        if not self.pam.has('pam_pkcs11'):
            if self.ac.get_bool('USESMARTCARD'):
                features.append("with-smartcard")

            if self.ac.get_bool('FORCESMARTCARD'):
                features.append("with-smartcard-required")

            if self.dconf.get_string(
                'org/gnome/settings-daemon/peripherals/smartcard',
                'removal-action'
            ) == 'lock-screen':
                features.append("with-smartcard-lock-on-removal")

        return features 
Example 16
Project: leapp-repository   Author: oamg   File: lib_spamd.py    Apache License 2.0 5 votes vote down vote up
def _drop_ssl_version(value):
    regex = r'(?<![\w-])--ssl-version(=|\s+)(sslv3|tlsv1)(?![\w-])'
    if not re.search(r'(?<![\w-])--ssl(?![\w-])', value):
        value = re.sub(regex, '--ssl', value, count=1)
    return re.sub(regex, '', value) 
Example 17
Project: leapp-repository   Author: oamg   File: scanner.py    Apache License 2.0 5 votes vote down vote up
def detect_config_error(conf_file):
    '''
    Check grub configuration for syntax error in GRUB_CMDLINE_LINUX value.

    :return: Function returns True if error was detected, otherwise False.
    '''
    with open(conf_file, 'r') as f:
        config = f.read()

    pattern = r'GRUB_CMDLINE_LINUX="[^"]+"(?!(\s*$)|(\s+GRUB))'
    return re.search(pattern, config) is not None 
Example 18
Project: leapp-repository   Author: oamg   File: lib_spamd.py    Apache License 2.0 5 votes vote down vote up
def _parse_ssl_version(content):
    _, assignment, _ = lib.parse_sysconfig_spamassassin(content)
    if re.search(r'(?<![\w-])--ssl-version(=|\s+)sslv3(?![\w-])', assignment):
        return 'sslv3'
    elif re.search(r'(?<![\w-])--ssl-version(=|\s+)tlsv1(?![\w-])', assignment):
        return 'tlsv1'
    return None 
Example 19
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def fix_grub_config_error(conf_file):
    with open(conf_file, 'r') as f:
        config = f.read()

    # move misplaced '"' to the end
    pattern = r'GRUB_CMDLINE_LINUX=.+?(?=GRUB|\Z)'
    original_value = re.search(pattern, config, re.DOTALL).group()
    parsed_value = original_value.split('"')
    new_value = '{KEY}"{VALUE}"{END}'.format(KEY=parsed_value[0], VALUE=''.join(parsed_value[1:]).rstrip(),
                                             END=original_value[-1])

    config = config.replace(original_value, new_value)

    write_to_file(conf_file, config) 
Example 20
Project: leapp-repository   Author: oamg   File: actor.py    Apache License 2.0 5 votes vote down vote up
def process(self):
        rhel7_ifaces = next(self.consume(PersistentNetNamesFacts)).interfaces
        rhel8_ifaces = next(self.consume(PersistentNetNamesFactsInitramfs)).interfaces

        rhel7_ifaces_map = {iface.mac: iface for iface in rhel7_ifaces}
        rhel8_ifaces_map = {iface.mac: iface for iface in rhel8_ifaces}

        renamed_interfaces = []

        if rhel7_ifaces != rhel8_ifaces:
            for iface in rhel7_ifaces:
                rhel7_name = rhel7_ifaces_map[iface.mac].name
                rhel8_name = rhel8_ifaces_map[iface.mac].name

                if rhel7_name != rhel8_name:
                    self.log.warning('Detected interface rename {} -> {}.'.format(rhel7_name, rhel8_name))

                    if re.search('eth[0-9]+', iface.name) is not None:
                        self.log.warning('Interface named using eth prefix, refusing to generate link file')
                        renamed_interfaces.append(RenamedInterface(**{'rhel7_name': rhel7_name,
                                                                      'rhel8_name': rhel8_name}))
                        continue
                    else:
                        # TODO(msekleta): we need to introduce another actor which will
                        # # install generated link files to RHEL-8 initrd image
                        self.generate_link_file(iface)

        self.produce(RenamedInterfaces(renamed=renamed_interfaces))
        self.produce(InitrdIncludes(files=self.initrd_files)) 
Example 21
Project: leapp-repository   Author: oamg   File: unit_test.py    Apache License 2.0 5 votes vote down vote up
def test_migration(monkeypatch):
    for packages, services, migrate in [
                (['ntp'], ['ntpd'], ['ntpd']),
                (['ntp', 'ntpdate'], ['ntpd'], ['ntpd']),
                (['ntpdate'], ['ntpdate'], ['ntpdate']),
                (['ntp', 'ntpdate'], ['ntpdate'], ['ntpdate']),
                (['ntp', 'ntpdate'], ['ntpd', 'ntpdate'], ['ntpd', 'ntpdate']),
                (['ntp', 'ntpdate', 'ntp-perl'], ['ntpd', 'ntpdate'], ['ntpd', 'ntpdate']),
                (['ntp', 'ntpdate'], ['ntpd', 'ntpdate', 'ntp-wait'], ['ntpd', 'ntpdate']),
                (['ntp', 'ntpdate', 'ntp-perl'], ['ntpd', 'ntpdate', 'ntp-wait'], ['ntpd', 'ntpdate', 'ntp-wait']),
            ]:
        monkeypatch.setattr(reporting, 'create_report', create_report_mocked())
        monkeypatch.setattr(library, 'check_service',
                                     lambda service: service[:-8] in services)
        monkeypatch.setattr(library, 'is_file', lambda _: True)
        monkeypatch.setattr(library, 'get_tgz64', lambda _: '')

        decision = library.check_ntp(set(packages))

        assert reporting.create_report.called == 1
        assert 'configuration will be migrated' in reporting.create_report.report_fields['title']
        for service in ['ntpd', 'ntpdate']:
            migrated = re.search(r'\b{}\b'.format(service),
                                 reporting.create_report.report_fields['title']) is not None
            assert migrated == (service in migrate)

        assert decision.migrate_services == migrate 
Example 22
Project: mutatest   Author: EvanKepner   File: conf.py    MIT License 5 votes vote down vote up
def find_meta(meta):
    """
    Extract __*meta*__ from META_FILE.
    """
    meta_match = re.search(r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M)
    if meta_match:
        return meta_match.group(1)
    raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))


# -- Project information ----------------------------------------------------- 
Example 23
Project: mutatest   Author: EvanKepner   File: setup.py    MIT License 5 votes vote down vote up
def find_meta(meta):
    """
    Extract __*meta*__ from META_FILE.
    """
    meta_match = re.search(r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M)
    if meta_match:
        return meta_match.group(1)
    raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) 
Example 24
Project: f5go   Author: f5devcentral   File: go.py    MIT License 5 votes vote down vote up
def canonicalUrl(url):
    if url:
        m = re.search(r'href="(.*)"', jinja2.utils.urlize(url))
        if m:
            return m.group(1)

    return url 
Example 25
Project: autofff   Author: ChiefGokhlayeh   File: scanner.py    MIT License 5 votes vote down vote up
def _read_symbols(self, pathToObj: str) -> SymbolTable:
        path_list = ['objdump', '-t']
        path_list += [pathToObj]

        try:
            pipe = subprocess.Popen(path_list,
                                    stdout=subprocess.PIPE,
                                    universal_newlines=True)
            text = pipe.communicate()[0]
            matches = re.finditer(
                r"(?P<object>.*):\s+file format.*\s+SYMBOL TABLE:\n(?P<symbols>(?:.+(\n|$))*)", text, re.MULTILINE)
            tables = list()
            for match in matches:
                print(match)
                objectFile = match.group('object') or pathToObj
                symbols = match.group('symbols')
                symMatch = re.search(
                    r"\*ABS\*\s+[0-9a-fA-F]*\s+(?P<source>.*)", symbols, re.MULTILINE)
                sourceFile = symMatch.group('source')
                fuNMatches = re.finditer(r"", symbols, re.MULTILINE)

                tables.append(SymbolTable(objectFile, None))
                print(objectFile)
                print(sourceFile)
                print(symbols)
        except OSError as e:
            raise RuntimeError("Unable to invoke 'readelf'.  " +
                               'Make sure its path was passed correctly\n' +
                               ('Original error: %s' % e)) 
Example 26
Project: alfred-yubikey-otp   Author: robertoriv   File: yubi.py    MIT License 5 votes vote down vote up
def get_all_codes():
    formatted_codes = []
    codes = execute(['ykman', 'oath', 'code']).splitlines()
    for code in codes:
        log.info(code)
        code_search = re.search('(.*)((\d{6,8})|(\[Touch))', code, re.IGNORECASE)
        if code_search:
            entry = {
                "name": code_search.group(1).strip(),
                "code": code_search.group(2).strip()
            }
            formatted_codes.append(entry)
    log.info(formatted_codes)
    return formatted_codes 
Example 27
Project: alfred-yubikey-otp   Author: robertoriv   File: yubi.py    MIT License 5 votes vote down vote up
def touch(name):
    new_env = os.environ.copy()
    new_env['PATH'] = '/usr/local/bin:%s' % new_env['PATH']
    process = subprocess.Popen(['ykman', 'oath', 'code', name], stdout=subprocess.PIPE, env=new_env)
    counter = 0
    for i in iter(process.stdout.readline,'b'):
        code_search = re.search('(.*)((\d{6,8}))', i, re.IGNORECASE)
        if code_search:
            wf.add_item(
                name,
                'Copy %s to clipboard' % code_search.group(2).strip(),
                arg=code_search.group(2).strip(),
                icon=get_icon_for_service(name), 
                valid=True,
            )
            wf.send_feedback()
            break
        counter += 1
        if counter == 3:
            wf.add_item(
                name,
                'Timeout',
                arg=name,
                icon=get_icon_for_service(name), 
                valid=True,
            )
            wf.send_feedback()
            break
    process.kill() 
Example 28
Project: alfred-yubikey-otp   Author: robertoriv   File: workflow.py    MIT License 5 votes vote down vote up
def _search_for_query(self, query):
        if query in self._search_pattern_cache:
            return self._search_pattern_cache[query]

        # Build pattern: include all characters
        pattern = []
        for c in query:
            # pattern.append('[^{0}]*{0}'.format(re.escape(c)))
            pattern.append('.*?{0}'.format(re.escape(c)))
        pattern = ''.join(pattern)
        search = re.compile(pattern, re.IGNORECASE).search

        self._search_pattern_cache[query] = search
        return search 
Example 29
Project: alfred-yubikey-otp   Author: robertoriv   File: workflow.py    MIT License 5 votes vote down vote up
def get_password(self, account, service=None):
        """Retrieve the password saved at ``service/account``.

        Raise :class:`PasswordNotFound` exception if password doesn't exist.

        :param account: name of the account the password is for, e.g.
            "Pinboard"
        :type account: ``unicode``
        :param service: Name of the service. By default, this is the workflow's
                        bundle ID
        :type service: ``unicode``
        :returns: account password
        :rtype: ``unicode``

        """
        if not service:
            service = self.bundleid

        output = self._call_security('find-generic-password', service,
                                     account, '-g')

        # Parsing of `security` output is adapted from python-keyring
        # by Jason R. Coombs
        # https://pypi.python.org/pypi/keyring
        m = re.search(
            r'password:\s*(?:0x(?P<hex>[0-9A-F]+)\s*)?(?:"(?P<pw>.*)")?',
            output)

        if m:
            groups = m.groupdict()
            h = groups.get('hex')
            password = groups.get('pw')
            if h:
                password = unicode(binascii.unhexlify(h), 'utf-8')

        self.logger.debug('got password : %s:%s', service, account)

        return password 
Example 30
Project: phrydy   Author: Josef-Friedrich   File: versioneer.py    MIT License 5 votes vote down vote up
def git_get_keywords(versionfile_abs):
    """Extract version information from the given file."""
    # the code embedded in _version.py can just fetch the value of these
    # keywords. When used from setup.py, we don't want to import _version.py,
    # so we do it with a regexp instead. This function is not used from
    # _version.py.
    keywords = {}
    try:
        f = open(versionfile_abs, "r")
        for line in f.readlines():
            if line.strip().startswith("git_refnames ="):
                mo = re.search(r'=\s*"(.*)"', line)
                if mo:
                    keywords["refnames"] = mo.group(1)
            if line.strip().startswith("git_full ="):
                mo = re.search(r'=\s*"(.*)"', line)
                if mo:
                    keywords["full"] = mo.group(1)
            if line.strip().startswith("git_date ="):
                mo = re.search(r'=\s*"(.*)"', line)
                if mo:
                    keywords["date"] = mo.group(1)
        f.close()
    except EnvironmentError:
        pass
    return keywords 
Example 31
Project: phrydy   Author: Josef-Friedrich   File: versioneer.py    MIT License 5 votes vote down vote up
def versions_from_file(filename):
    """Try to determine the version from _version.py if present."""
    try:
        with open(filename) as f:
            contents = f.read()
    except EnvironmentError:
        raise NotThisMethod("unable to read _version.py")
    mo = re.search(r"version_json = '''\n(.*)'''  # END VERSION_JSON",
                   contents, re.M | re.S)
    if not mo:
        mo = re.search(r"version_json = '''\r\n(.*)'''  # END VERSION_JSON",
                       contents, re.M | re.S)
    if not mo:
        raise NotThisMethod("no version_json in _version.py")
    return json.loads(mo.group(1)) 
Example 32
Project: phrydy   Author: Josef-Friedrich   File: _version.py    MIT License 5 votes vote down vote up
def git_get_keywords(versionfile_abs):
    """Extract version information from the given file."""
    # the code embedded in _version.py can just fetch the value of these
    # keywords. When used from setup.py, we don't want to import _version.py,
    # so we do it with a regexp instead. This function is not used from
    # _version.py.
    keywords = {}
    try:
        f = open(versionfile_abs, "r")
        for line in f.readlines():
            if line.strip().startswith("git_refnames ="):
                mo = re.search(r'=\s*"(.*)"', line)
                if mo:
                    keywords["refnames"] = mo.group(1)
            if line.strip().startswith("git_full ="):
                mo = re.search(r'=\s*"(.*)"', line)
                if mo:
                    keywords["full"] = mo.group(1)
            if line.strip().startswith("git_date ="):
                mo = re.search(r'=\s*"(.*)"', line)
                if mo:
                    keywords["date"] = mo.group(1)
        f.close()
    except EnvironmentError:
        pass
    return keywords 
Example 33
Project: WazeRouteCalculator   Author: kovacsbalu   File: WazeRouteCalculator.py    GNU General Public License v3.0 5 votes vote down vote up
def already_coords(self, address):
        """test used to see if we have coordinates or address"""

        m = re.search(self.COORD_MATCH, address)
        return (m is not None) 
Example 34
Project: pyblish-win   Author: pyblish   File: _osx_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_system_version():
    """Return the OS X system version as a string"""
    # Reading this plist is a documented way to get the system
    # version (see the documentation for the Gestalt Manager)
    # We avoid using platform.mac_ver to avoid possible bootstrap issues during
    # the build of Python itself (distutils is used to build standard library
    # extensions).

    global _SYSTEM_VERSION

    if _SYSTEM_VERSION is None:
        _SYSTEM_VERSION = ''
        try:
            f = open('/System/Library/CoreServices/SystemVersion.plist')
        except IOError:
            # We're on a plain darwin box, fall back to the default
            # behaviour.
            pass
        else:
            try:
                m = re.search(r'<key>ProductUserVisibleVersion</key>\s*'
                              r'<string>(.*?)</string>', f.read())
            finally:
                f.close()
            if m is not None:
                _SYSTEM_VERSION = '.'.join(m.group(1).split('.')[:2])
            # else: fall back to the default behaviour

    return _SYSTEM_VERSION 
Example 35
Project: pyblish-win   Author: pyblish   File: _osx_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _remove_unsupported_archs(_config_vars):
    """Remove any unsupported archs from config vars"""
    # Different Xcode releases support different sets for '-arch'
    # flags. In particular, Xcode 4.x no longer supports the
    # PPC architectures.
    #
    # This code automatically removes '-arch ppc' and '-arch ppc64'
    # when these are not supported. That makes it possible to
    # build extensions on OSX 10.7 and later with the prebuilt
    # 32-bit installer on the python.org website.

    # skip checks if the compiler was overriden with a CC env variable
    if 'CC' in os.environ:
        return _config_vars

    if re.search('-arch\s+ppc', _config_vars['CFLAGS']) is not None:
        # NOTE: Cannot use subprocess here because of bootstrap
        # issues when building Python itself
        status = os.system(
            """echo 'int main{};' | """
            """'%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null"""
            %(_config_vars['CC'].replace("'", "'\"'\"'"),))
        if status:
            # The compile failed for some reason.  Because of differences
            # across Xcode and compiler versions, there is no reliable way
            # to be sure why it failed.  Assume here it was due to lack of
            # PPC support and remove the related '-arch' flags from each
            # config variables not explicitly overriden by an environment
            # variable.  If the error was for some other reason, we hope the
            # failure will show up again when trying to compile an extension
            # module.
            for cv in _UNIVERSAL_CONFIG_VARS:
                if cv in _config_vars and cv not in os.environ:
                    flags = _config_vars[cv]
                    flags = re.sub('-arch\s+ppc\w*\s', ' ', flags)
                    _save_modified_value(_config_vars, cv, flags)

    return _config_vars 
Example 36
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def offset_from_tz_string(tz):
    offset = None
    if tz in UTC_ZONES:
        offset = 0
    else:
        m = TIMEZONE_RE.search(tz)
        if m:
            offset = 3600 * int(m.group(2))
            if m.group(3):
                offset = offset + 60 * int(m.group(3))
            if m.group(1) == '-':
                offset = -offset
    return offset 
Example 37
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def iso2time(text):
    """
    As for http2time, but parses the ISO 8601 formats:

    1994-02-03 14:15:29 -0100    -- ISO 8601 format
    1994-02-03 14:15:29          -- zone is optional
    1994-02-03                   -- only date
    1994-02-03T14:15:29          -- Use T as separator
    19940203T141529Z             -- ISO 8601 compact format
    19940203                     -- only date

    """
    # clean up
    text = text.lstrip()

    # tz is time zone specifier string
    day, mon, yr, hr, min, sec, tz = [None]*7

    # loose regexp parse
    m = ISO_DATE_RE.search(text)
    if m is not None:
        # XXX there's an extra bit of the timezone I'm ignoring here: is
        #   this the right thing to do?
        yr, mon, day, hr, min, sec, tz, _ = m.groups()
    else:
        return None  # bad format

    return _str2time(day, mon, yr, hr, min, sec, tz)


# Header parsing
# ----------------------------------------------------------------------------- 
Example 38
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_HDN(text):
    """Return True if text is a host domain name."""
    # XXX
    # This may well be wrong.  Which RFC is HDN defined in, if any (for
    #  the purposes of RFC 2965)?
    # For the current implementation, what about IPv6?  Remember to look
    #  at other uses of IPV4_RE also, if change this.
    if IPV4_RE.search(text):
        return False
    if text == "":
        return False
    if text[0] == "." or text[-1] == ".":
        return False
    return True 
Example 39
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def liberal_is_HDN(text):
    """Return True if text is a sort-of-like a host domain name.

    For accepting/blocking domains.

    """
    if IPV4_RE.search(text):
        return False
    return True 
Example 40
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def eff_request_host(request):
    """Return a tuple (request-host, effective request-host name).

    As defined by RFC 2965, except both are lowercased.

    """
    erhn = req_host = request_host(request)
    if req_host.find(".") == -1 and not IPV4_RE.search(req_host):
        erhn = req_host + ".local"
    return req_host, erhn 
Example 41
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def find_library(name):
        if name in ('c', 'm'):
            return find_msvcrt()
        # See MSDN for the REAL search order.
        for directory in os.environ['PATH'].split(os.pathsep):
            fname = os.path.join(directory, name)
            if os.path.isfile(fname):
                return fname
            if fname.lower().endswith(".dll"):
                continue
            fname = fname + ".dll"
            if os.path.isfile(fname):
                return fname
        return None 
Example 42
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_soname(f):
            if not f:
                return None
            cmd = "/usr/ccs/bin/dump -Lpv 2>/dev/null " + f
            f = os.popen(cmd)
            try:
                data = f.read()
            finally:
                f.close()
            res = re.search(r'\[.*\]\sSONAME\s+([^\s]+)', data)
            if not res:
                return None
            return res.group(1) 
Example 43
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _findSoname_ldconfig(name):
            import struct
            if struct.calcsize('l') == 4:
                machine = os.uname()[4] + '-32'
            else:
                machine = os.uname()[4] + '-64'
            mach_map = {
                'x86_64-64': 'libc6,x86-64',
                'ppc64-64': 'libc6,64bit',
                'sparc64-64': 'libc6,64bit',
                's390x-64': 'libc6,64bit',
                'ia64-64': 'libc6,IA-64',
                }
            abi_type = mach_map.get(machine, 'libc6')

            # XXX assuming GLIBC's ldconfig (with option -p)
            expr = r'\s+(lib%s\.[^\s]+)\s+\(%s' % (re.escape(name), abi_type)
            f = os.popen('/sbin/ldconfig -p 2>/dev/null')
            try:
                data = f.read()
            finally:
                f.close()
            res = re.search(expr, data)
            if not res:
                return None
            return res.group(1) 
Example 44
Project: pyblish-win   Author: pyblish   File: emxccompiler.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def find_library_file(self, dirs, lib, debug=0):
        shortlib = '%s.lib' % lib
        longlib = 'lib%s.lib' % lib    # this form very rare

        # get EMX's default library directory search path
        try:
            emx_dirs = os.environ['LIBRARY_PATH'].split(';')
        except KeyError:
            emx_dirs = []

        for dir in dirs + emx_dirs:
            shortlibp = os.path.join(dir, shortlib)
            longlibp = os.path.join(dir, longlib)
            if os.path.exists(shortlibp):
                return shortlibp
            elif os.path.exists(longlibp):
                return longlibp

        # Oops, didn't find it in *any* of 'dirs'
        return None

# class EMXCCompiler


# Because these compilers aren't configured in Python's pyconfig.h file by
# default, we should at least warn the user if he is using a unmodified
# version. 
Example 45
Project: pyblish-win   Author: pyblish   File: emxccompiler.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_versions():
    """ Try to find out the versions of gcc and ld.
        If not possible it returns None for it.
    """
    from distutils.version import StrictVersion
    from distutils.spawn import find_executable
    import re

    gcc_exe = find_executable('gcc')
    if gcc_exe:
        out = os.popen(gcc_exe + ' -dumpversion','r')
        try:
            out_string = out.read()
        finally:
            out.close()
        result = re.search('(\d+\.\d+\.\d+)',out_string)
        if result:
            gcc_version = StrictVersion(result.group(1))
        else:
            gcc_version = None
    else:
        gcc_version = None
    # EMX ld has no way of reporting version number, and we use GCC
    # anyway - so we can link OMF DLLs
    ld_version = None
    return (gcc_version, ld_version) 
Example 46
Project: pyblish-win   Author: pyblish   File: msvc9compiler.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def runtime_library_dir_option(self, dir):
        raise DistutilsPlatformError(
              "don't know how to set runtime library search path for MSVC++") 
Example 47
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_short(self, file):
        oldfile = file
        file = file.replace('+', '_')
        file = ''.join(c for c in file if not c in ' "/\[]:;=,')
        parts = file.split(".")
        if len(parts) > 1:
            prefix = "".join(parts[:-1]).upper()
            suffix = parts[-1].upper()
            if not prefix:
                prefix = suffix
                suffix = None
        else:
            prefix = file.upper()
            suffix = None
        if len(parts) < 3 and len(prefix) <= 8 and file == oldfile and (
                                                not suffix or len(suffix) <= 3):
            if suffix:
                file = prefix+"."+suffix
            else:
                file = prefix
        else:
            file = None
        if file is None or file in self.short_names:
            prefix = prefix[:6]
            if suffix:
                suffix = suffix[:3]
            pos = 1
            while 1:
                if suffix:
                    file = "%s~%d.%s" % (prefix, pos, suffix)
                else:
                    file = "%s~%d" % (prefix, pos)
                if file not in self.short_names: break
                pos += 1
                assert pos < 10000
                if pos in (10, 100, 1000):
                    prefix = prefix[:-1]
        self.short_names.add(file)
        assert not re.search(r'[\?|><:/*"+,;=\[\]]', file) # restrictions on short names
        return file 
Example 48
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_search_star_plus(self):
        self.assertEqual(re.search('x*', 'axx').span(0), (0, 0))
        self.assertEqual(re.search('x*', 'axx').span(), (0, 0))
        self.assertEqual(re.search('x+', 'axx').span(0), (1, 3))
        self.assertEqual(re.search('x+', 'axx').span(), (1, 3))
        self.assertIsNone(re.search('x', 'aaa'))
        self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0))
        self.assertEqual(re.match('a*', 'xxx').span(), (0, 0))
        self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3))
        self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3))
        self.assertIsNone(re.match('a+', 'xxx')) 
Example 49
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bug_1661(self):
        # Verify that flags do not get silently ignored with compiled patterns
        pattern = re.compile('.')
        self.assertRaises(ValueError, re.match, pattern, 'A', re.I)
        self.assertRaises(ValueError, re.search, pattern, 'A', re.I)
        self.assertRaises(ValueError, re.findall, pattern, 'A', re.I)
        self.assertRaises(ValueError, re.compile, pattern, re.I) 
Example 50
Project: pyblish-win   Author: pyblish   File: test_re.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_special_escapes(self):
        self.assertEqual(re.search(r"\b(b.)\b",
                                   "abcd abc bcd bx").group(1), "bx")
        self.assertEqual(re.search(r"\B(b.)\B",
                                   "abc bcd bc abxd").group(1), "bx")
        self.assertEqual(re.search(r"\b(b.)\b",
                                   "abcd abc bcd bx", re.LOCALE).group(1), "bx")
        self.assertEqual(re.search(r"\B(b.)\B",
                                   "abc bcd bc abxd", re.LOCALE).group(1), "bx")
        if have_unicode:
            self.assertEqual(re.search(r"\b(b.)\b",
                                       "abcd abc bcd bx", re.UNICODE).group(1), "bx")
            self.assertEqual(re.search(r"\B(b.)\B",
                                       "abc bcd bc abxd", re.UNICODE).group(1), "bx")
        self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
        self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
        self.assertIsNone(re.search(r"^\Aabc\Z$", "\nabc\n", re.M))
        self.assertEqual(re.search(r"\b(b.)\b",
                                   u"abcd abc bcd bx").group(1), "bx")
        self.assertEqual(re.search(r"\B(b.)\B",
                                   u"abc bcd bc abxd").group(1), "bx")
        self.assertEqual(re.search(r"^abc$", u"\nabc\n", re.M).group(0), "abc")
        self.assertEqual(re.search(r"^\Aabc\Z$", u"abc", re.M).group(0), "abc")
        self.assertIsNone(re.search(r"^\Aabc\Z$", u"\nabc\n", re.M))
        self.assertEqual(re.search(r"\d\D\w\W\s\S",
                                   "1aa! a").group(0), "1aa! a")
        self.assertEqual(re.search(r"\d\D\w\W\s\S",
                                   "1aa! a", re.LOCALE).group(0), "1aa! a")
        if have_unicode:
            self.assertEqual(re.search(r"\d\D\w\W\s\S",
                                       "1aa! a", re.UNICODE).group(0), "1aa! a")