當前位置: 首頁>>代碼示例>>Python>>正文


Python re.MULTILINE屬性代碼示例

本文整理匯總了Python中re.MULTILINE屬性的典型用法代碼示例。如果您正苦於以下問題:Python re.MULTILINE屬性的具體用法?Python re.MULTILINE怎麽用?Python re.MULTILINE使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在re的用法示例。


在下文中一共展示了re.MULTILINE屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: ssh_edit_file

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def ssh_edit_file(adress, user, passw, remotefile, regex, replace):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        trans = paramiko.Transport((adress, 22))
        trans.connect(username=user, password=passw)
        sftp = paramiko.SFTPClient.from_transport(trans)
        f_in = sftp.file(remotefile, "r")
        c_in = f_in.read()
        pattern = re.compile(regex, re.MULTILINE | re.DOTALL)
        c_out = pattern.sub(replace, c_in)
        f_out = sftp.file(remotefile, "w")
        f_out.write(c_out)
        f_in.close()
        f_out.close()
        sftp.close()
        trans.close() 
開發者ID:dsp-jetpack,項目名稱:JetPack,代碼行數:19,代碼來源:ssh.py

示例2: tweak

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def tweak(self, content):
        tweaked = self.legacy_tweak(content)
        if tweaked:
            return tweaked
        apply_persistence_to_all_lines = \
            0 < self.setup_params.persistence_size and \
            not self.config_is_persistence_aware(content)
        matching_re = r'^(\s*(%s)\s*)(.*)$' % self.BOOT_PARAMS_STARTER
        kernel_parameter_line_pattern = re.compile(
            matching_re,
            flags = re.I | re.MULTILINE)
        out = self.tweak_first_match(
            content,
            kernel_parameter_line_pattern,
            apply_persistence_to_all_lines,
            self.param_operations(),
            self.param_operations_for_persistence())
        
        return self.post_process(out) 
開發者ID:mbusb,項目名稱:multibootusb,代碼行數:21,代碼來源:update_cfg_file.py

示例3: substitute

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def substitute(self,*args):
        for color in colors:
            self.txt.tag_remove(color,"1.0","end")
            self.txt.tag_remove("emph"+color,"1.0","end")
        self.rex = re.compile("") # default value in case of misformed regexp
        self.rex = re.compile(self.fld.get("1.0","end")[:-1],re.MULTILINE)
        try:
            re.compile("(?P<emph>%s)" % self.fld.get(tk.SEL_FIRST,
                                                      tk.SEL_LAST))
            self.rexSel = re.compile("%s(?P<emph>%s)%s" % (
                self.fld.get("1.0",tk.SEL_FIRST),
                self.fld.get(tk.SEL_FIRST,tk.SEL_LAST),
                self.fld.get(tk.SEL_LAST,"end")[:-1],
            ),re.MULTILINE)
        except:
            self.rexSel = self.rex
        self.rexSel.sub(self.addTags,self.txt.get("1.0","end")) 
開發者ID:rafasashi,項目名稱:razzy-spinner,代碼行數:19,代碼來源:nemo_app.py

示例4: _make_boundary

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def _make_boundary(cls, text=None):
        # Craft a random boundary.  If text is given, ensure that the chosen
        # boundary doesn't appear in the text.
        token = random.randrange(sys.maxsize)
        boundary = ('=' * 15) + (_fmt % token) + '=='
        if text is None:
            return boundary
        b = boundary
        counter = 0
        while True:
            cre = cls._compile_re('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
            if not cre.search(text):
                break
            b = boundary + '.' + str(counter)
            counter += 1
        return b 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:18,代碼來源:generator.py

示例5: check_juniper_rift_in_path

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def check_juniper_rift_in_path():
    if shutil.which("rift-environ") is None:
        fatal_error("Cannot find Juniper RIFT (rift-environ) in PATH")

    # run it and check version
    output = subprocess.check_output(["rift-environ",
                                      "--version"], universal_newlines=True)
    # print (output)
    regex = re.compile(r"^.hrift encoding schema: *(\d+)\.(\d+).*",
                       re.IGNORECASE  | re.MULTILINE)
    major = re.search(regex, output)

    if not major or not major.group(1):
        fatal_error("Cannot detect major version of Juniper RIFT")

    minor = major.group(2)
    major = major.group(1)

    expected_minor = protocol_minor_version
    expected_major = protocol_major_version

    if int(major) != expected_major or int(minor) != expected_minor:
        fatal_error("Wrong Major/Minor version of Juniper RIFT: (expected {}.{}, got {}.{})"
                    .format(expected_major, expected_minor, major, minor)) 
開發者ID:brunorijsman,項目名稱:rift-python,代碼行數:26,代碼來源:interop.py

示例6: render_re

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def render_re(regex):
  """Renders a repr()-style value for a compiled regular expression."""
  actual_flags = []
  if regex.flags:
    flags = [
      (re.IGNORECASE, 'IGNORECASE'),
      (re.LOCALE, 'LOCALE'),
      (re.UNICODE, 'UNICODE'),
      (re.MULTILINE, 'MULTILINE'),
      (re.DOTALL, 'DOTALL'),
      (re.VERBOSE, 'VERBOSE'),
    ]
    for val, name in flags:
      if regex.flags & val:
        actual_flags.append(name)
  if actual_flags:
    return 're.compile(%r, %s)' % (regex.pattern, '|'.join(actual_flags))
  else:
    return 're.compile(%r)' % regex.pattern 
開發者ID:luci,項目名稱:recipes-py,代碼行數:21,代碼來源:magic_check_fn.py

示例7: _pdfjs_version

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def _pdfjs_version() -> str:
    """Get the pdf.js version.

    Return:
        A string with the version number.
    """
    try:
        pdfjs_file, file_path = pdfjs.get_pdfjs_res_and_path('build/pdf.js')
    except pdfjs.PDFJSNotFound:
        return 'no'
    else:
        pdfjs_file = pdfjs_file.decode('utf-8')
        version_re = re.compile(
            r"^ *(PDFJS\.version|var pdfjsVersion) = '([^']+)';$",
            re.MULTILINE)

        match = version_re.search(pdfjs_file)
        if not match:
            pdfjs_version = 'unknown'
        else:
            pdfjs_version = match.group(2)
        if file_path is None:
            file_path = 'bundled'
        return '{} ({})'.format(pdfjs_version, file_path) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:26,代碼來源:version.py

示例8: package

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def package(self):
        self.copy("LICENSE", dst="licenses", src=self._source_subfolder)
        if self.settings.compiler == "Visual Studio":
            cmake = self._configure_cmake()
            cmake.install()
        else:
            autotools = self._configure_autotools()
            autotools.install()

            os.unlink(os.path.join(self.package_folder, "lib", "libapr-1.la"))
            tools.rmdir(os.path.join(self.package_folder, "build-1"))
            tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig"))

            apr_rules_mk = os.path.join(self.package_folder, "bin", "build-1", "apr_rules.mk")
            apr_rules_cnt = open(apr_rules_mk).read()
            for key in ("apr_builddir", "apr_builders", "top_builddir"):
                apr_rules_cnt, nb = re.subn("^{}=[^\n]*\n".format(key), "{}=$(_APR_BUILDDIR)\n".format(key), apr_rules_cnt, flags=re.MULTILINE)
                if nb == 0:
                    raise ConanException("Could not find/replace {} in {}".format(key, apr_rules_mk))
            open(apr_rules_mk, "w").write(apr_rules_cnt) 
開發者ID:conan-io,項目名稱:conan-center-index,代碼行數:22,代碼來源:conanfile.py

示例9: setup

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def setup(self, config):
    """
    Load name model (word list) and compile regexes for stop characters.

    :param config: Configuration object.
    :type config: ``dict``
    """
    reference_model = os.path.join(
        config[helper.CODE_ROOT], config[helper.NAME_MODEL])

    self.stopper = regex.compile(('(%s)' % '|'.join([
        'and', 'or', 'og', 'eller', r'\?', '&', '<', '>', '@', ':', ';', '/',
        r'\(', r'\)', 'i', 'of', 'from', 'to', r'\n', '!'])),
        regex.I | regex.MULTILINE)

    self.semistop = regex.compile(
        ('(%s)' % '|'.join([','])), regex.I | regex.MULTILINE)
    self.size_probability = [0.000, 0.000, 0.435, 0.489, 0.472, 0.004, 0.000]
    self.threshold = 0.25
    self.candidates = defaultdict(int)

    with gzip.open(reference_model, 'rb') as inp:
      self.model = json.loads(inp.read().decode('utf-8'))

    self.tokenizer = regex.compile(r'\w{2,20}') 
開發者ID:pcbje,項目名稱:gransk,代碼行數:27,代碼來源:find_names_brute.py

示例10: parse_from_string

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def parse_from_string(full_string):
    """
    separate a Radiance file string into multiple strings for each object.

    Args:
        rad_fileString: Radiance data as a single string. The string can be multiline.

    Returns:
        A list of strings. Each string represents a different Radiance Object
    """
    raw_rad_objects = re.findall(
        r'^\s*([^0-9].*(\s*[\d.-]+.*)*)',
        full_string,
        re.MULTILINE)

    rad_objects = (' '.join(radiance_object[0].split())
                   for radiance_object in raw_rad_objects)

    filtered_objects = tuple(rad_object for rad_object in rad_objects
                             if rad_object and rad_object[0] not in ['#', '!'])

    return filtered_objects 
開發者ID:ladybug-tools,項目名稱:honeybee,代碼行數:24,代碼來源:radparser.py

示例11: get_pr_title

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def get_pr_title(commit, pr_num):
    bors_message_regex = re.compile(
        rf"^{pr_num}: (?P<message>.*)( [ra]=[^ ]*){{2,}}$", re.MULTILINE
    )
    green_button_message_regex = re.compile(
        rf"^Merge pull request #{pr_num} from.*\n\n(?P<message>.*)$", re.MULTILINE
    )

    match = bors_message_regex.search(commit.msg)
    if not match:
        match = green_button_message_regex.search(commit.msg)
        if match:
            log.warning(
                f"Green-button style merge found for PR {pr_num}, expected bors-style merge"
            )

    if not match:
        log.error(f"Could not determine title for PR {pr_num}. Bailing.")
        raise ValueError(f"Could not determine PR title for {pr_num}")
    return match.group("message") 
開發者ID:mozilla,項目名稱:normandy,代碼行數:22,代碼來源:generate_deploy_bug.py

示例12: testExportGroundtruthToCOCO

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def testExportGroundtruthToCOCO(self):
    image_ids = ['first', 'second']
    groundtruth_boxes = [np.array([[100, 100, 200, 200]], np.float),
                         np.array([[50, 50, 100, 100]], np.float)]
    groundtruth_classes = [np.array([1], np.int32), np.array([1], np.int32)]
    categories = [{'id': 0, 'name': 'person'},
                  {'id': 1, 'name': 'cat'},
                  {'id': 2, 'name': 'dog'}]
    output_path = os.path.join(tf.test.get_temp_dir(), 'groundtruth.json')
    result = coco_tools.ExportGroundtruthToCOCO(
        image_ids,
        groundtruth_boxes,
        groundtruth_classes,
        categories,
        output_path=output_path)
    self.assertDictEqual(result, self._groundtruth_dict)
    with tf.gfile.GFile(output_path, 'r') as f:
      written_result = f.read()
      # The json output should have floats written to 4 digits of precision.
      matcher = re.compile(r'"bbox":\s+\[\n\s+\d+.\d\d\d\d,', re.MULTILINE)
      self.assertTrue(matcher.findall(written_result))
      written_result = json.loads(written_result)
      self.assertAlmostEqual(result, written_result) 
開發者ID:ahmetozlu,項目名稱:vehicle_counting_tensorflow,代碼行數:25,代碼來源:coco_tools_test.py

示例13: testExportDetectionsToCOCO

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def testExportDetectionsToCOCO(self):
    image_ids = ['first', 'second']
    detections_boxes = [np.array([[100, 100, 200, 200]], np.float),
                        np.array([[50, 50, 100, 100]], np.float)]
    detections_scores = [np.array([.8], np.float), np.array([.7], np.float)]
    detections_classes = [np.array([1], np.int32), np.array([1], np.int32)]
    categories = [{'id': 0, 'name': 'person'},
                  {'id': 1, 'name': 'cat'},
                  {'id': 2, 'name': 'dog'}]
    output_path = os.path.join(tf.test.get_temp_dir(), 'detections.json')
    result = coco_tools.ExportDetectionsToCOCO(
        image_ids,
        detections_boxes,
        detections_scores,
        detections_classes,
        categories,
        output_path=output_path)
    self.assertListEqual(result, self._detections_list)
    with tf.gfile.GFile(output_path, 'r') as f:
      written_result = f.read()
      # The json output should have floats written to 4 digits of precision.
      matcher = re.compile(r'"bbox":\s+\[\n\s+\d+.\d\d\d\d,', re.MULTILINE)
      self.assertTrue(matcher.findall(written_result))
      written_result = json.loads(written_result)
      self.assertAlmostEqual(result, written_result) 
開發者ID:ahmetozlu,項目名稱:vehicle_counting_tensorflow,代碼行數:27,代碼來源:coco_tools_test.py

示例14: scanner

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def scanner(cls):
        if not getattr(cls, '_scanner', None):
            def h(tpe):
                return lambda sc, tk: cls.Token(tpe, tk)

            cls._scanner = re.Scanner([
                (r"(--|//).*?$",               h(cls.LINE_COMMENT)),
                (r"\/\*.+?\*\/",               h(cls.BLOCK_COMMENT)),
                (r'"(?:[^"\\]|\\.)*"',         h(cls.STRING)),
                (r"'(?:[^'\\]|\\.)*'",         h(cls.STRING)),
                (r"\$\$(?:[^\$\\]|\\.)*\$\$",  h(cls.STRING)),
                (r";",                         h(cls.SEMICOLON)),
                (r"\s+",                       h(cls.WHITESPACE)),
                (r".",                         h(cls.OTHER))
            ], re.MULTILINE | re.DOTALL)
        return cls._scanner 
開發者ID:Cobliteam,項目名稱:cassandra-migrate,代碼行數:18,代碼來源:cql.py

示例15: data_received

# 需要導入模塊: import re [as 別名]
# 或者: from re import MULTILINE [as 別名]
def data_received(self, data, recv_time):
        """
        Await initial prompt of started shell command.

        After that - do real forward
        """
        if not self._shell_operable.done():
            decoded_data = self.moler_connection.decode(data)
            self.logger.debug("<|{}".format(data))
            assert isinstance(decoded_data, str)
            self.read_buffer += decoded_data
            if re.search(self.prompt, self.read_buffer, re.MULTILINE):
                self._notify_on_connect()
                self._shell_operable.set_result(True)  # makes Future done
                # TODO: should we remove initial prompt as it is inside raw.terminal?
                # TODO: that way (maybe) we won't see it in logs
                data_str = re.sub(self.prompt, '', self.read_buffer, re.MULTILINE)
                data = self.moler_connection.encode(data_str)
            else:
                return
        self.logger.debug("<|{}".format(data))
        super(AsyncioTerminal, self).data_received(data) 
開發者ID:nokia,項目名稱:moler,代碼行數:24,代碼來源:terminal.py


注:本文中的re.MULTILINE屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。