• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python extract.extract_from_dir函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中babel.messages.extract.extract_from_dir函数的典型用法代码示例。如果您正苦于以下问题:Python extract_from_dir函数的具体用法?Python extract_from_dir怎么用?Python extract_from_dir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了extract_from_dir函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: extract_messages

def extract_messages(dirs):
    catalog = Catalog(
        project='Open Library',
        copyright_holder='Internet Archive'
    )
    METHODS = [
        ("**.py", "python"),
        ("**.html", "openlibrary.i18n:extract_templetor")
    ]
    COMMENT_TAGS = ["NOTE:"]

    for d in dirs:
        if '.html' in d:
            extracted = [(d,) + extract for extract in extract_from_file("openlibrary.i18n:extract_templetor", d)]
        else:
            extracted = extract_from_dir(d, METHODS, comment_tags=COMMENT_TAGS, strip_comment_tags=True)
        for filename, lineno, message, comments, context in extracted:
            catalog.add(message, None, [(filename, lineno)], auto_comments=comments)

    path = os.path.join(root, 'messages.pot')
    f = open(path, 'w')
    write_po(f, catalog)
    f.close()

    print('wrote template to', path)
开发者ID:hornc,项目名称:openlibrary-1,代码行数:25,代码来源:__init__.py


示例2: extract

 def extract(self, force=False):
     """
     Extract translation strings from sources directory with extract rules then 
     create the template catalog with finded translation strings
     
     Only proceed if the template catalog does not exists yet or if 
     ``force`` argument is ``True`` (this will overwrite previous existing 
     POT file)
     
     TODO: actually from the CLI usage this only update POT file when he does not 
     exist, else it keeps untouched, even if there changes or adds in translations
     """
     if force or not self.check_template_path():
         self.logger.info('Proceeding to extraction to update the template catalog (POT)')
         self._catalog_template = Catalog(project=self.settings.SITE_NAME, header_comment=self.header_comment)
         # Follow all paths to search for pattern to extract
         for extract_path in self.settings.I18N_EXTRACT_SOURCES:
             self.logger.debug('Searching for pattern to extract in : {0}'.format(extract_path))
             extracted = extract_from_dir(dirname=extract_path, method_map=self.settings.I18N_EXTRACT_MAP, options_map=self.settings.I18N_EXTRACT_OPTIONS)
             # Proceed to extract from given path
             for filename, lineno, message, comments, context in extracted:
                 filepath = os.path.normpath(os.path.join(os.path.basename(self.settings.SOURCES_DIR), filename))
                 self._catalog_template.add(message, None, [(filepath, lineno)], auto_comments=comments, context=context)
         
         outfile = open(self.get_template_path(), 'wb')
         write_po(outfile, self._catalog_template)
         outfile.close()
         
     return self._catalog_template
开发者ID:simbha,项目名称:Optimus,代码行数:29,代码来源:i18n.py


示例3: extract_to_catalog

def extract_to_catalog(catalog, data_iterator, keywords, comment_tags,
                       strip_comment_tags, log=log):

    for dirname, method_map, options_map in data_iterator:
        if not os.path.isdir(dirname):
            raise ConfigureError('%r is not a directory' % dirname)

        def callback(filename, method, options):
            if method == 'ignore':
                return
            filepath = _gen_filepath(dirname, filename)
            optstr = _gen_optstr(options)
            log.info('extracting messages from %s%s', filepath, optstr)

        extracted = extract_from_dir(dirname, method_map, options_map,
                                     keywords=keywords,
                                     comment_tags=comment_tags,
                                     callback=callback,
                                     strip_comment_tags=strip_comment_tags)

        # Add extracted strings to catalog
        for filename, lineno, message, comments, context in extracted:
            filepath = _gen_filepath(dirname, filename)
            catalog.add(message, None, [(filepath, lineno)],
                        auto_comments=comments, context=context)
开发者ID:bacher09,项目名称:babel,代码行数:25,代码来源:operations.py


示例4: run

    def run(self):
        mappings = self._get_mappings()
        with open(self.output_file, 'wb') as outfile:
            catalog = Catalog(project=self.project,
                              version=self.version,
                              msgid_bugs_address=self.msgid_bugs_address,
                              copyright_holder=self.copyright_holder,
                              charset=self.charset)

            for path, method_map, options_map in mappings:
                def callback(filename, method, options):
                    if method == 'ignore':
                        return

                    # If we explicitly provide a full filepath, just use that.
                    # Otherwise, path will be the directory path and filename
                    # is the relative path from that dir to the file.
                    # So we can join those to get the full filepath.
                    if os.path.isfile(path):
                        filepath = path
                    else:
                        filepath = os.path.normpath(os.path.join(path, filename))

                    optstr = ''
                    if options:
                        optstr = ' (%s)' % ', '.join(['%s="%s"' % (k, v) for
                                                      k, v in options.items()])
                    self.log.info('extracting messages from %s%s', filepath, optstr)

                if os.path.isfile(path):
                    current_dir = os.getcwd()
                    extracted = check_and_call_extract_file(
                        path, method_map, options_map,
                        callback, self.keywords, self.add_comments,
                        self.strip_comments, current_dir
                    )
                else:
                    extracted = extract_from_dir(
                        path, method_map, options_map,
                        keywords=self.keywords,
                        comment_tags=self.add_comments,
                        callback=callback,
                        strip_comment_tags=self.strip_comments
                    )
                for fname, lineno, msg, comments, context, flags in extracted:
                    if os.path.isfile(path):
                        filepath = fname  # already normalized
                    else:
                        filepath = os.path.normpath(os.path.join(path, fname))

                    catalog.add(msg, None, [(filepath, lineno)], flags=flags,
                                auto_comments=comments, context=context)

            self.log.info('writing PO template file to %s', self.output_file)
            write_po(outfile, catalog, width=self.width,
                     no_location=self.no_location,
                     omit_header=self.omit_header,
                     sort_output=self.sort_output,
                     sort_by_file=self.sort_by_file,
                     include_lineno=self.include_lineno)
开发者ID:JonathanRRogers,项目名称:babel,代码行数:60,代码来源:frontend.py


示例5: extract

    def extract(self, src_path='.', charset='utf-8', locale=None, **kwargs):
        """Extracts translatable messages from sources. This function is based
        on the extract function of the `pybabel` command, which is not part of
        the public API of `babel`. Only the public API of `babel` is used here.

        :param src_path: base path of the source tree, default is the current
                         path.
        :param charset: see the `babel.messages.catalog.Catalog` docs. Default
                        is `utf-8`.
        :param locale: see the `babel.messages.catalog.Catalog` docs. Default
                        is `None`.

        Other optional keyword parameters are passed to
        `babel.messages.extract.extract_from_dir` see `babel` public API docs.
        """
        #: This is the babel.messages.catalog.Catalog to contain the
        #: extracted messages
        self.catalog = Catalog(charset=charset, locale=locale)

        if not pth.isdir(src_path):
            raise IOError('{} is not a directory'.format(src_path))

        #: Extracts the data from source in a low level format. This is
        #: the only way present in babel's public API.
        extracted = extract_from_dir(src_path, **kwargs)

        #: Constructs the catalog from the raw extracted data.
        #: Based on the source code of pybabel:
        #: babel.messages.frontend.extract_messages.run
        for filename, lineno, message, comments, context in extracted:
            self.catalog.add(message, None, [(filename, lineno)],
                             auto_comments=comments, context=context)
开发者ID:TIMMYD3,项目名称:sagenb,代码行数:32,代码来源:translations.py


示例6: run_gettext

def run_gettext(dirname, for_js):
    catalog = Catalog()
    for filename, lineno, message, comments, context in extract_from_dir(
        dirname,
        method_map=[('**.js', 'javascript')] if for_js else [('**.py', 'python')]
    ):
        catalog.add(message, None, [(filename, lineno)],
                    auto_comments=comments, context=context)

    sio = cStringIO.StringIO()
    write_po(sio, catalog)

    return sio.getvalue()
开发者ID:jgriffiths,项目名称:GreenAddressWebFiles,代码行数:13,代码来源:gettext_finder.py


示例7: main

def main():
    print "Extracting messages"
    root = path.abspath(path.join(path.dirname(__file__), '..'))
    catalog = Catalog(msgid_bugs_address=BUGS_ADDRESS,
                      copyright_holder=COPYRIGHT,
                      charset="utf-8")

    def callback(filename, method, options):
        if method != "ignore":
            print strip_path(filename, root)

    extracted_py = extract_from_dir(root, PY_METHODS, {}, PY_KEYWORDS,
                                    COMMENT_TAGS, callback=callback,
                                    strip_comment_tags=True)

    extracted_js = extract_from_dir(root, [("static/js/**.js", "javascript")],
                                    {}, JS_KEYWORDS,
                                    COMMENT_TAGS, callback=callback,
                                    strip_comment_tags=True)

    for filename, lineno, message, comments in chain(extracted_py,
                                                     extracted_js):
        catalog.add(message, None, [(strip_path(filename, root), lineno)],
                    auto_comments=comments)

    output_path = path.join(root, "i18n")
    if not path.isdir(output_path):
        makedirs(output_path)

    f = file(path.join(output_path, "messages.pot"), "w")
    try:
        write_po(f, catalog, width=79)
    finally:
        f.close()

    print "All done."
开发者ID:w0rm,项目名称:pre-stonegarden-dev,代码行数:36,代码来源:extract-messages.py


示例8: set_nereid

    def set_nereid(self):
        """
        There are messages within the tryton code used in flash messages,
        returned responses etc. This is spread over the codebase and this
        function extracts the translation strings from code of installed
        modules.
        """
        pool = Pool()
        Translation = pool.get('ir.translation')
        to_create = []

        for module, directory in self._get_installed_module_directories():
            # skip messages from test files
            if 'tests' in directory:
                continue
            for (filename, lineno, messages, comments, context) in \
                    extract_from_dir(directory,):

                if isinstance(messages, basestring):
                    # messages could be a tuple if the function is ngettext
                    # where the messages for singular and plural are given as
                    # a tuple.
                    #
                    # So convert basestrings to tuples
                    messages = (messages, )

                for message in messages:
                    translations = Translation.search([
                        ('lang', '=', 'en_US'),
                        ('type', '=', 'nereid'),
                        ('name', '=', filename),
                        ('src', '=', message),
                        ('module', '=', module),
                    ], limit=1)
                    if translations:
                        continue
                    to_create.append({
                        'name': filename,
                        'res_id': lineno,
                        'lang': 'en_US',
                        'src': message,
                        'type': 'nereid',
                        'module': module,
                        'comments': comments and '\n'.join(comments) or None,
                    })
        if to_create:
            Translation.create(to_create)
开发者ID:priyankajain18,项目名称:nereid,代码行数:47,代码来源:translation.py


示例9: build_pot

    def build_pot(self, force=False):
        """
        Extract translation strings and create Portable Object Template (POT)
        from enabled source directories using defined extract rules.

        Note:
            May only work on internal '_pot' to return without touching
            'self._pot'.

        Keyword Arguments:
            force (boolean): Default behavior is to proceed only if POT file
                does not allready exists except if this argument is ``True``.

        Returns:
            babel.messages.catalog.Catalog: Catalog template object.
        """
        if force or not self.check_template_path():
            self.logger.info(("Proceeding to extraction to update the "
                              "template catalog (POT)"))
            self._pot = Catalog(project=self.settings.SITE_NAME,
                                header_comment=self.header_comment)
            # Follow all paths to search for pattern to extract
            for extract_path in self.settings.I18N_EXTRACT_SOURCES:
                msg = "Searching for pattern to extract in : {0}"
                self.logger.debug(msg.format(extract_path))
                extracted = extract_from_dir(
                    dirname=extract_path,
                    method_map=self.settings.I18N_EXTRACT_MAP,
                    options_map=self.settings.I18N_EXTRACT_OPTIONS
                )
                # Proceed to extract from given path
                for filename, lineno, message, comments, context in extracted:
                    filepath = os.path.normpath(
                        os.path.join(
                            os.path.basename(self.settings.SOURCES_DIR),
                            filename
                        )
                    )
                    self._pot.add(message, None, [(filepath, lineno)],
                                  auto_comments=comments, context=context)

            with io.open(self.get_template_path(), 'wb') as fp:
                write_po(fp, self._pot)

        return self._pot
开发者ID:sveetch,项目名称:Optimus,代码行数:45,代码来源:manager.py


示例10: extract_python_strings

def extract_python_strings(dirname, outfile, domain=None):
    """Extract translatable strings from all Python files in `dir`.

    Writes a PO template to `outfile`. Recognises `_` and `l_`. Needs babel!
    """
    from babel.messages.catalog import Catalog
    from babel.messages.extract import extract_from_dir
    from babel.messages.pofile import write_po
    base_dir = os.path.abspath(os.path.dirname(outfile))
    msgs = extract_from_dir(dirname, keywords={'_': None, 'l_': None},
                            comment_tags=['l10n:'])
    cat = Catalog(domain=domain, charset='utf-8')
    for fname, lineno, message, comments, context in msgs:
        filepath = os.path.join(dirname, fname)
        cat.add(message, None, [(os.path.relpath(filepath, base_dir), lineno)],
                auto_comments=comments, context=context)
    with open(outfile, 'wb') as f:
        write_po(f, cat)
开发者ID:Tey,项目名称:speedcrunch-nightlies,代码行数:18,代码来源:doc-tool.py


示例11: handle

    def handle(self, *args, **options):
        domains = options.get('domain')

        if domains == "all":
            domains = settings.DOMAIN_METHODS.keys()
        else:
            domains = [domains]

        root = settings.ROOT

        def callback(filename, method, options):
            if method != 'ignore':
                print "  %s" % filename

        for domain in domains:

            print "Extracting all strings in domain %s..." % (domain)

            methods = settings.DOMAIN_METHODS[domain]
            extracted = extract_from_dir(root,
                                         method_map=methods,
                                         keywords=DEFAULT_KEYWORDS,
                                         comment_tags=COMMENT_TAGS,
                                         callback=callback,
                                         options_map=OPTIONS_MAP,
                                         )
            catalog = create_pofile_from_babel(extracted)
            catalog.savefile(os.path.join(root, 'locale', 'z-%s.pot' % domain))

        if len(domains) > 1:
            print "Concatenating all domains..."
            pot_files = []
            for i in domains:
                pot_files.append(os.path.join(root, 'locale', 'z-%s.pot' % i))
            z_keys = open(os.path.join(root, 'locale', 'z-keys.pot'), 'w+t')
            z_keys.truncate()
            command = ["msgcat"] + pot_files
            p1 = Popen(command, stdout=z_keys)
            p1.communicate()
            z_keys.close()
            for i in domains:
                os.remove(os.path.join(root, 'locale', 'z-%s.pot' % i))

        print 'done'
开发者ID:mccammos,项目名称:zamboni,代码行数:44,代码来源:extract.py


示例12: set_wtforms

    def set_wtforms(self):
        """
        There are some messages in WTForms which are provided by the framework,
        namely default validator messages and errors occuring during the
        processing (data coercion) stage. For example, in the case of the
        IntegerField, if someone entered a value which was not valid as
        an integer, then a message like “Not a valid integer value” would be
        displayed.
        """
        pool = Pool()
        Translation = pool.get('ir.translation')
        to_create = []
        for (filename, lineno, messages, comments, context) in \
                extract_from_dir(os.path.dirname(wtforms.__file__)):

            if isinstance(messages, basestring):
                # messages could be a tuple if the function is ngettext
                # where the messages for singular and plural are given as
                # a tuple.
                #
                # So convert basestrings to tuples
                messages = (messages, )

            for message in messages:
                translations = Translation.search([
                    ('lang', '=', 'en_US'),
                    ('type', '=', 'wtforms'),
                    ('name', '=', filename),
                    ('src', '=', message),
                    ('module', '=', 'nereid'),
                ], limit=1)
                if translations:
                    continue
                to_create.append({
                    'name': filename,
                    'res_id': lineno,
                    'lang': 'en_US',
                    'src': message,
                    'type': 'wtforms',
                    'module': 'nereid',
                    'comments': comments and '\n'.join(comments) or None,
                })
        if to_create:
            Translation.create(to_create)
开发者ID:priyankajain18,项目名称:nereid,代码行数:44,代码来源:translation.py


示例13: extract_messages

        def extract_messages(   # noqa
                dirname, project=app.name, version=app.cfg.get('VERSION', ''),
                charset='utf-8', domain=self.cfg.domain, locale=self.cfg.default_locale):
            """Extract messages from source code.

            :param charset: charset to use in the output
            :param domain:  set domain name for locales
            :param project: set project name in output
            :param version: set project version in output
            """
            Locale.parse(locale)

            if not os.path.isdir(dirname):
                raise SystemExit('%r is not a directory' % dirname)

            catalog = Catalog(locale=locale, project=project, version=version, charset=charset)
            for filename, lineno, message, comments, context in extract_from_dir(
                    dirname, method_map=self.cfg.sources_map, options_map=self.cfg.options_map):
                filepath = os.path.normpath(os.path.join(dirname, filename))
                catalog.add(message, None, [(filepath, lineno)],
                            auto_comments=comments, context=context)

            locales_dir = self.cfg.locales_dirs[0]
            output = os.path.join(locales_dir, locale, 'LC_MESSAGES', '%s.po' % domain)

            if os.path.exists(output):
                with open(output, 'rb') as f:
                    template = read_po(f, locale=locale, charset=charset)
                    template.update(catalog)
                    catalog = template

            if not os.path.exists(os.path.dirname(output)):
                os.makedirs(os.path.dirname(output))

            logger.info('writing PO template file to %s', output)
            outfile = open(output, 'wb')

            try:
                write_po(outfile, catalog, include_previous=True)
            finally:
                outfile.close()
开发者ID:klen,项目名称:muffin-babel,代码行数:41,代码来源:muffin_babel.py


示例14: run

    def run(self):
        mappings = self._get_mappings()
        outfile = open(self.output_file, 'wb')
        try:
            catalog = Catalog(project=self.distribution.get_name(),
                              version=self.distribution.get_version(),
                              msgid_bugs_address=self.msgid_bugs_address,
                              copyright_holder=self.copyright_holder,
                              charset=self.charset)

            for dirname, (method_map, options_map) in mappings.items():
                def callback(filename, method, options):
                    if method == 'ignore':
                        return
                    filepath = os.path.normpath(os.path.join(dirname, filename))
                    optstr = ''
                    if options:
                        optstr = ' (%s)' % ', '.join(['%s="%s"' % (k, v) for
                                                      k, v in options.items()])
                    log.info('extracting messages from %s%s', filepath, optstr)

                extracted = extract_from_dir(dirname, method_map, options_map,
                                             keywords=self._keywords,
                                             comment_tags=self._add_comments,
                                             callback=callback,
                                             strip_comment_tags=
                                                self.strip_comments)
                for filename, lineno, message, comments, context in extracted:
                    filepath = os.path.normpath(os.path.join(dirname, filename))
                    catalog.add(message, None, [(filepath, lineno)],
                                auto_comments=comments, context=context)

            log.info('writing PO template file to %s' % self.output_file)
            write_po(outfile, catalog, width=self.width,
                     no_location=self.no_location,
                     omit_header=self.omit_header,
                     sort_output=self.sort_output,
                     sort_by_file=self.sort_by_file)
        finally:
            outfile.close()
开发者ID:Lukas-Stuehrk,项目名称:Babel3,代码行数:40,代码来源:frontend.py


示例15: extract

 def extract(self, force=False):
     """
     Extract translation strings from sources directory with extract rules then 
     create the template catalog with finded translation strings
     
     Only proceed if the template catalog does not exists yet or if 
     ``force`` argument is ``True`` (this will overwrite previous existing 
     POT file)
     """
     if force or not self.check_template_path():
         self.logger.warning('Template catalog (POT) does not exists, extracting it')
         self._catalog_template = Catalog(project=self.settings.SITE_NAME, header_comment=self.header_comment)
         extracted = extract_from_dir(dirname=self.settings.SOURCES_DIR, method_map=self.settings.I18N_EXTRACT_MAP, options_map=self.settings.I18N_EXTRACT_OPTIONS)
         
         for filename, lineno, message, comments, context in extracted:
             filepath = os.path.normpath(os.path.join(os.path.basename(self.settings.SOURCES_DIR), filename))
             self._catalog_template.add(message, None, [(filepath, lineno)], auto_comments=comments, context=context)
         
         outfile = open(self.get_template_path(), 'wb')
         write_po(outfile, self._catalog_template)
         outfile.close()
         
     return self._catalog_template
开发者ID:Meodudlye,项目名称:Optimus,代码行数:23,代码来源:i18n.py


示例16: handle

    def handle(self, *args, **options):
        domains = options.get('domain')
        outputdir = os.path.abspath(options.get('outputdir'))

        if not os.path.isdir(outputdir):
            if not options.get('create'):
                print ('Output directory must exist (%s) unless -c option is '
                       'given. Specify one with --output-dir' % outputdir)
                return 'FAILURE\n'

            os.makedirs(outputdir)

        if domains == 'all':
            domains = settings.DOMAIN_METHODS.keys()
        else:
            domains = [domains]

        root = settings.ROOT

        def callback(filename, method, options):
            if method != 'ignore':
                print '  %s' % filename

        for domain in domains:
            print 'Extracting all strings in domain %s...' % (domain)

            methods = settings.DOMAIN_METHODS[domain]
            extracted = extract_from_dir(root,
                                         method_map=methods,
                                         keywords=TOWER_KEYWORDS,
                                         comment_tags=COMMENT_TAGS,
                                         callback=callback,
                                         options_map=OPTIONS_MAP,
                                         )
            catalog = create_pofile_from_babel(extracted)
            if not os.path.exists(outputdir):
                raise Exception('Expected %s to exist... BAILING' % outputdir)

            catalog.savefile(os.path.join(outputdir, '%s.pot' % domain))

        pot_files = []
        for i in [x for x in domains if x not in standalone_domains]:
            pot_files.append(os.path.join(outputdir, '%s.pot' % i))

        if len(pot_files) > 1:
            print ('Concatenating the non-standalone domains into %s.pot' %
                   TEXT_DOMAIN)

            final_out = os.path.join(outputdir, '%s.pot' % TEXT_DOMAIN)

            # We add final_out back on because msgcat will combine all
            # specified files.  We'll redirect everything back in to
            # final_out in a minute.
            pot_files.append(final_out)

            meltingpot = tempfile.TemporaryFile()
            command = ['msgcat'] + pot_files
            p1 = Popen(command, stdout=meltingpot)
            p1.communicate()
            meltingpot.seek(0)

            # w+ truncates the file first
            with open(final_out, 'w+') as final:
                final.write(meltingpot.read())

            meltingpot.close()

            for i in [x for x in domains if x not in standalone_domains]:
                os.remove(os.path.join(outputdir, '%s.pot' % i))

        print 'Done'
开发者ID:Ritsyy,项目名称:fjord,代码行数:71,代码来源:extract.py


示例17: handle

    def handle(self, *args, **options):
        # Must monkeypatch first to fix InternationalizationExtension
        # stomping issues! See docstring for details.
        monkeypatch_i18n()

        # Get all the settings we need; we uppercase them so they're
        # obviously setings
        DOMAIN_METHODS = get_setting("DOMAIN_METHODS")
        STANDALONE_DOMAINS = get_setting("STANDALONE_DOMAINS")
        KEYWORDS = get_setting("KEYWORDS")
        COMMENT_TAGS = get_setting("COMMENT_TAGS")
        ROOT = get_setting("ROOT")

        keywords_dict = dict([(keyword, None) for keyword in KEYWORDS])

        domains = options.get("domain")
        outputdir = os.path.abspath(options.get("outputdir"))

        if not os.path.isdir(outputdir):
            if not options.get("create"):
                print (
                    "Output directory must exist (%s) unless -c option is "
                    "given. Specify one with --output-dir" % outputdir
                )
                # FIXME: This should return a non-zero exit code and
                # print to stderr however that works in Django.
                return "FAILURE\n"

            os.makedirs(outputdir)

        if domains == DEFAULT_DOMAIN_VALUE:
            domains = DOMAIN_METHODS.keys()
        else:
            domains = [domains]

        def callback(filename, method, options):
            if method != "ignore":
                print "  %s" % filename

        for domain in domains:
            print "Extracting all strings in domain %s..." % (domain)

            methods = DOMAIN_METHODS[domain]
            extracted = extract_from_dir(
                ROOT,
                method_map=methods,
                keywords=keywords_dict,
                comment_tags=COMMENT_TAGS,
                callback=callback,
                options_map=generate_options_map(),
            )
            catalog = create_pofile_from_babel(extracted)
            if not os.path.exists(outputdir):
                # FIXME: This should return a non-zero exit code and
                # print to stderr and be consistent
                raise Exception("Expected %s to exist... BAILING" % outputdir)

            catalog.savefile(os.path.join(outputdir, "%s.pot" % domain))

        not_standalone_domains = [dom for dom in domains if dom not in STANDALONE_DOMAINS]

        pot_files = []
        for dom in not_standalone_domains:
            pot_files.append(os.path.join(outputdir, "%s.pot" % dom))

        if len(pot_files) > 1:
            pot_file = get_setting("TEXT_DOMAIN") + ".pot"
            print ("Concatenating the non-standalone domains into %s" % pot_file)

            final_out = os.path.join(outputdir, pot_file)

            # We add final_out back on because msgcat will combine all
            # specified files.  We'll redirect everything back in to
            # final_out in a minute.
            pot_files.append(final_out)

            meltingpot = tempfile.TemporaryFile()
            p1 = Popen(["msgcat"] + pot_files, stdout=meltingpot)
            p1.communicate()
            meltingpot.seek(0)

            # w+ truncates the file first
            with open(final_out, "w+") as final:
                final.write(meltingpot.read())

            meltingpot.close()

            for dom in not_standalone_domains:
                os.remove(os.path.join(outputdir, "%s.pot" % dom))

        print "Done"
开发者ID:robhudson,项目名称:puente,代码行数:91,代码来源:extract.py


示例18: callback

output_file = "mb_server.pot"


def callback(filename, method, options):
    if method == "ignore":
        return
    filepath = os.path.normpath(os.path.join(dirname, filename))
    optstr = ""
    if options:
        optstr = " (%s)" % ", ".join(['%s="%s"' % (k, v) for k, v in options.items()])
    print("extracting messages from %s%s" % (filepath, optstr))


outfile = open(output_file, "w")

try:
    catalog = Catalog(project=project, version=version, charset="UTF-8")

    extracted = extract_from_dir(dirname, method_map, options_map, keywords=keywords, callback=callback)

    for filename, lineno, message, comments in extracted:
        filepath = os.path.normpath(os.path.join(dirname, filename))
        catalog.add(message, None, [(filepath, lineno)], auto_comments=comments)

    print("writing PO template file to %s" % output_file)
    write_po(outfile, catalog, sort_by_file=True)

finally:
    outfile.close()
开发者ID:mayhem,项目名称:musicbrainz-server,代码行数:29,代码来源:update-messages.py


示例19: extract_command

def extract_command(outputdir, domain_methods, text_domain, keywords,
                    comment_tags, base_dir, project, version,
                    msgid_bugs_address):
    """Extracts strings into .pot files

    :arg domain: domains to generate strings for or 'all' for all domains
    :arg outputdir: output dir for .pot files; usually
        locale/templates/LC_MESSAGES/
    :arg domain_methods: DOMAIN_METHODS setting
    :arg text_domain: TEXT_DOMAIN settings
    :arg keywords: KEYWORDS setting
    :arg comment_tags: COMMENT_TAGS setting
    :arg base_dir: BASE_DIR setting
    :arg project: PROJECT setting
    :arg version: VERSION setting
    :arg msgid_bugs_address: MSGID_BUGS_ADDRESS setting

    """
    # Must monkeypatch first to fix i18n extensions stomping issues!
    monkeypatch_i18n()

    # Create the outputdir if it doesn't exist
    outputdir = os.path.abspath(outputdir)
    if not os.path.isdir(outputdir):
        print('Creating output dir %s ...' % outputdir)
        os.makedirs(outputdir)

    domains = domain_methods.keys()

    def callback(filename, method, options):
        if method != 'ignore':
            print('  %s' % filename)

    # Extract string for each domain
    for domain in domains:
        print('Extracting all strings in domain %s...' % domain)

        methods = domain_methods[domain]

        catalog = Catalog(
            header_comment='',
            project=project,
            version=version,
            msgid_bugs_address=msgid_bugs_address,
            charset='utf-8',
        )
        extracted = extract_from_dir(
            base_dir,
            method_map=methods,
            options_map=generate_options_map(),
            keywords=keywords,
            comment_tags=comment_tags,
            callback=callback,
        )

        for filename, lineno, msg, cmts, ctxt in extracted:
            catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts,
                        context=ctxt)

        with open(os.path.join(outputdir, '%s.pot' % domain), 'wb') as fp:
            write_po(fp, catalog, width=80)

    print('Done')
开发者ID:vericant,项目名称:puente,代码行数:63,代码来源:commands.py


示例20: extract_command

def extract_command(domain, outputdir, domain_methods, standalone_domains,
                    text_domain, keywords, comment_tags, base_dir):
    """Extracts strings into .pot files

    :arg domain: domains to generate strings for or 'all' for all domains
    :arg outputdir: output dir for .pot files; usually
        locale/templates/LC_MESSAGES/
    :arg domain_methods: DOMAIN_METHODS setting
    :arg standalone_domains: STANDALONE_DOMAINS setting
    :arg text_domain: TEXT_DOMAIN settings
    :arg keywords: KEYWORDS setting
    :arg comment_tags: COMMENT_TAGS setting
    :arg base_dir: BASE_DIR setting

    """
    # Must monkeypatch first to fix i18n extensions stomping issues!
    monkeypatch_i18n()

    # Create the outputdir if it doesn't exist
    outputdir = os.path.abspath(outputdir)
    if not os.path.isdir(outputdir):
        print 'Creating output dir %s ...' % outputdir
        os.makedirs(outputdir)

    # Figure out what domains to extract
    if domain == DEFAULT_DOMAIN_VALUE:
        domains = domain_methods.keys()
    else:
        domains = [domain]

    def callback(filename, method, options):
        if method != 'ignore':
            print '  %s' % filename

    # Extract string for each domain
    for domain in domains:
        print 'Extracting all strings in domain %s...' % (domain)

        methods = domain_methods[domain]

        catalog = Catalog(charset='utf-8', header_comment='')
        extracted = extract_from_dir(
            base_dir,
            method_map=methods,
            options_map=generate_options_map(),
            keywords=keywords,
            comment_tags=comment_tags,
            callback=callback,
        )

        for filename, lineno, msg, cmts, ctxt in extracted:
            catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts,
                        context=ctxt)

        with open(os.path.join(outputdir, '%s.pot' % domain), 'w') as fp:
            write_po(fp, catalog, width=80)

    not_standalone_domains = [
        dom for dom in domains
        if dom not in standalone_domains
    ]

    pot_files = []
    for dom in not_standalone_domains:
        pot_files.append(os.path.join(outputdir, '%s.pot' % dom))

    if len(pot_files) > 1:
        pot_file = text_domain + '.pot'
        print ('Concatenating the non-standalone domains into %s' %
               pot_file)

        final_out = os.path.join(outputdir, pot_file)

        # We add final_out back on because msgcat will combine all
        # specified files.  We'll redirect everything back in to
        # final_out in a minute.
        pot_files.append(final_out)

        meltingpot = tempfile.TemporaryFile()
        p1 = Popen(['msgcat'] + pot_files, stdout=meltingpot)
        p1.communicate()
        meltingpot.seek(0)

        # w+ truncates the file first
        with open(final_out, 'w+') as final:
            final.write(meltingpot.read())

        meltingp 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python extract.extract_javascript函数代码示例发布时间:2022-05-24
下一篇:
Python extract.extract函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap