当前位置: 首页>>代码示例>>Python>>正文


Python core.Publisher类代码示例

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


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

示例1: publish

def publish(writer_name):

    reader=None
    reader_name='standalone'
    parser=None
    parser_name='restructuredtext'
    writer=None
    settings=None
    settings_spec=None
    settings_overrides=options[writer_name]
    config_section=None
    enable_exit=1
    argv=[]
    usage=default_usage

    pub = Publisher(reader, parser, writer, settings=settings)
    pub.set_components(reader_name, parser_name, writer_name)
    settings = pub.get_settings(settings_spec=settings_spec,
                                config_section=config_section)
    if settings_overrides:
        settings._update(settings_overrides, 'loose')
    source = file(source_path)
    pub.set_source(source, source_path)
    destination_path = 'pg1.' + extensions[writer_name]
    destination = file(destination_path, 'w')
    pub.set_destination(destination, destination_path)
    pub.publish(argv, usage, description, settings_spec, settings_overrides,
                config_section=config_section, enable_exit=enable_exit)
开发者ID:scanlime,项目名称:picogui,代码行数:28,代码来源:build.py

示例2: from_file

    def from_file(cls, filename):
        """
        Loads a file from disk, parses it and constructs a new BlogPost.

        This method reflects a bit of the insanity of docutils. Basically
        this is just the docutils.core.publish_doctree function with some
        modifications to use an html writer and to load a file instead of
        a string.
        """
        pub = Publisher(destination_class=NullOutput,
                        source=FileInput(source_path=filename),
                        reader=BlogPostReader(), writer=HTMLWriter(),
                        parser=RSTParser())

        pub.get_settings() # This is not sane.
        pub.settings.traceback = True # Damnit
        pub.publish()

        meta = pub.document.blog_meta
        post = cls(meta['title'], meta['post_date'], meta['author'],
                   meta['tags'], pub.writer.parts['html_body'])

        post.filename = filename

        return post
开发者ID:mcrute,项目名称:ventriloquy,代码行数:25,代码来源:blog.py

示例3: publish_cmdline_to_binary

def publish_cmdline_to_binary(reader=None, reader_name='standalone',
                    parser=None, parser_name='restructuredtext',
                    writer=None, writer_name='pseudoxml',
                    settings=None, settings_spec=None,
                    settings_overrides=None, config_section=None,
                    enable_exit_status=1, argv=None,
                    usage=default_usage, description=default_description,
                    destination=None, destination_class=BinaryFileOutput
                    ):
    """
    Set up & run a `Publisher` for command-line-based file I/O (input and
    output file paths taken automatically from the command line).  Return the
    encoded string output also.

    This is just like publish_cmdline, except that it uses
    io.BinaryFileOutput instead of io.FileOutput.

    Parameters: see `publish_programmatically` for the remainder.

    - `argv`: Command-line argument list to use instead of ``sys.argv[1:]``.
    - `usage`: Usage string, output if there's a problem parsing the command
      line.
    - `description`: Program description, output for the "--help" option
      (along with command-line option descriptions).
    """
    pub = Publisher(reader, parser, writer, settings=settings,
        destination_class=destination_class)
    pub.set_components(reader_name, parser_name, writer_name)
    output = pub.publish(
        argv, usage, description, settings_spec, settings_overrides,
        config_section=config_section, enable_exit_status=enable_exit_status)
    return output
开发者ID:igemsoftware,项目名称:Michigan15,代码行数:32,代码来源:rst2odt.py

示例4: zotero_odf_scan_publish_cmdline_to_binary

def zotero_odf_scan_publish_cmdline_to_binary(reader=None, reader_name='standalone',
                    parser=None, parser_name='restructuredtext',
                    writer=None, writer_name='pseudoxml',
                    settings=None, settings_spec=None,
                    settings_overrides=None, config_section=None,
                    enable_exit_status=True, argv=None,
                    usage=default_usage, description=description,
                    destination=None, destination_class=io.BinaryFileOutput
                    ):
    # Tried to get internal conversion working, but using the big hammer is so much simpler.
    ofh = NamedTemporaryFile(mode='w+', delete=False)
    if len(sys.argv) > 1:
        txt = open(sys.argv[1]).read()
        oldtxt = txt
        txt = re.sub("{([^|}]*)\|([^|}]*)\|([^|}]*)\|([^|}]*)\|([^|}]*)}", "{\\1\\|\\2\\|\\3\\|\\4\\|\\5}", txt,re.S|re.M)
        ofh.write(txt)
        sys.argv[1] = ofh.name
        ofh.close()
    
    pub = Publisher(reader=reader, parser=parser, writer=writer, settings=settings,
                    destination_class=destination_class)
    output = pub.publish(
        argv, usage, description, settings_spec, settings_overrides,
        config_section=config_section, enable_exit_status=enable_exit_status)
    # See above.
    os.unlink(ofh.name)
开发者ID:Zotero-ODF-Scan,项目名称:zotero-odf-scan,代码行数:26,代码来源:zoteroODFScan.py

示例5: _to_odp_content

    def _to_odp_content(self, rst, xml_filename, odp_name='/tmp/out'):
        reader = standalone.Reader()
        reader_name = 'standalone'
        writer = rst2odp.Writer()
        writer_name = 'pseudoxml'
        parser = None
        parser_name = 'restructuredtext'
        settings = None
        settings_spec = None
        settings_overrides = None
        config_section = None
        enable_exit_status = 1
        usage = default_usage
        publisher = Publisher(reader, parser, writer,# source=StringIO(rst),
                              settings=settings,
                              destination_class=rst2odp.BinaryFileOutput)
        publisher.set_components(reader_name, parser_name, writer_name)
        description = ('Generates OpenDocument/OpenOffice/ODF slides from '
                       'standalone reStructuredText sources.  ' + default_description)

        fin = open('/tmp/in.rst', 'w')
        fin.write(rst)
        fin.close()
        argv = ['--traceback', '/tmp/in.rst', odp_name]
        output = publisher.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status)
        # pull content.xml out of /tmp/out
        z = zipwrap.Zippier(odp_name)
        fout = open(xml_filename, 'w')
        content = preso.pretty_xml(z.cat('content.xml'))
        fout.write(content)
        fout.close()
        return content
开发者ID:mkohler,项目名称:rst2odp,代码行数:32,代码来源:regressions.py

示例6: main

def main(args=sys.argv):
    argv = None
    reader = standalone.Reader()
    reader_name = "standalone"
    writer = EpubWriter()
    writer_name = "epub2"
    parser = Parser()
    parser_name = "restructuredtext"
    settings = None
    settings_spec = None
    settings_overrides = None
    config_section = None
    enable_exit_status = 1
    usage = default_usage
    publisher = Publisher(
        reader, parser, writer, settings, destination_class=EpubFileOutput
    )
    publisher.set_components(reader_name, parser_name, writer_name)
    description = (
        "Generates epub books from reStructuredText sources.  " + default_description
    )

    publisher.publish(
        argv,
        usage,
        description,
        settings_spec,
        settings_overrides,
        config_section=config_section,
        enable_exit_status=enable_exit_status,
    )
开发者ID:mattharrison,项目名称:rst2epub2,代码行数:31,代码来源:rst2epub.py

示例7: render_rst

def render_rst(directory, name, meta_parser, template):
    # check if that file actually exists
    path = safe_join(directory, name + '.rst')
    if not os.path.exists(path):
        abort(404)

    # read file
    with codecs.open(path, encoding='utf-8') as fd:
        content = fd.read()

    if not template:
        # Strip out RST
        content = content.replace('.. meta::\n', '')
        content = content.replace('.. contents::\n\n', '')
        content = content.replace('.. raw:: html\n\n', '')
        content = content.replace('\n.. [', '\n[')
        content = content.replace(']_.', '].')
        content = content.replace(']_,', '],')
        content = content.replace(']_', '] ')
        # Change highlight formatter
        content = content.replace('{% highlight', "{% highlight formatter='textspec'")
        # Metatags
        for (metatag, label) in METATAG_LABELS.items():
            content = content.replace('    :%s' % metatag, label)

    # render the post with Jinja2 to handle URLs etc.
    rendered_content = render_template_string(content)
    rendered_content = rendered_content.replace('</pre></div>', '  </pre></div>')

    if not template:
        # Send response
        r = make_response(rendered_content)
        r.mimetype = 'text/plain'
        return r

    # Render the ToC
    doctree = publish_doctree(source=rendered_content)
    bullet_list = doctree[1][1]
    doctree.clear()
    doctree.append(bullet_list)
    reader = Reader(parser_name='null')
    pub = Publisher(reader, None, None,
                    source=io.DocTreeInput(doctree),
                    destination_class=io.StringOutput)
    pub.set_writer('html')
    pub.publish()
    toc = pub.writer.parts['fragment']

    # Remove the ToC from the main document
    rendered_content = rendered_content.replace('.. contents::\n', '')

    # publish the spec with docutils
    parts = publish_parts(source=rendered_content, source_path=directory, writer_name="html")
    meta = meta_parser(parts['meta'])

    if (directory == PROPOSAL_DIR):
        meta['num'] = int(name[:3])

    return render_template(template, title=parts['title'], toc=toc, body=parts['fragment'], name=name, meta=meta)
开发者ID:i2p,项目名称:i2p.www,代码行数:59,代码来源:views.py

示例8: read_doc

def read_doc(app, env, filename):
    # type: (Sphinx, BuildEnvironment, unicode) -> nodes.document
    """Parse a document and convert to doctree."""
    filetype = get_filetype(app.config.source_suffix, filename)
    input_class = app.registry.get_source_input(filetype)
    reader = SphinxStandaloneReader(app)
    source = input_class(app, env, source=None, source_path=filename,
                         encoding=env.config.source_encoding)
    parser = app.registry.create_source_parser(app, filetype)
    if parser.__class__.__name__ == 'CommonMarkParser' and parser.settings_spec == ():
        # a workaround for recommonmark
        #   If recommonmark.AutoStrictify is enabled, the parser invokes reST parser
        #   internally.  But recommonmark-0.4.0 does not provide settings_spec for reST
        #   parser.  As a workaround, this copies settings_spec for RSTParser to the
        #   CommonMarkParser.
        parser.settings_spec = RSTParser.settings_spec

    pub = Publisher(reader=reader,
                    parser=parser,
                    writer=SphinxDummyWriter(),
                    source_class=SphinxDummySourceClass,
                    destination=NullOutput())
    pub.set_components(None, 'restructuredtext', None)
    pub.process_programmatic_settings(None, env.settings, None)
    pub.set_source(source, filename)
    pub.publish()
    return pub.document
开发者ID:mgeier,项目名称:sphinx,代码行数:27,代码来源:io.py

示例9: parse_docstring

def parse_docstring(doc):
    p = Publisher(source=doc, source_class=io.StringInput)
    p.set_reader('standalone', p.parser, 'restructuredtext')
    p.writer = Writer()
    p.process_programmatic_settings(None, None, None)
    p.set_source(doc, None)
    return p.publish()
开发者ID:waipeng,项目名称:hivemind,代码行数:7,代码来源:common.py

示例10: __init__

    def __init__(self):
        """
        Defer to Publisher init.
        """
        Publisher.__init__(self)

        self.extractors = [] # list of (transform, storage) type pairs
        """
        Transforms that are run during `process`. See Nabu for their interface.
        The stores may be left uninitialized until `prepare_extractors`.
        """
        self.source_class = None
开发者ID:,项目名称:,代码行数:12,代码来源:

示例11: pypi_render

def pypi_render(source):
    """
    Copied (and slightly adapted) from pypi.description_tools
    """
    ALLOWED_SCHEMES = '''file ftp gopher hdl http https imap mailto mms news
        nntp prospero rsync rtsp rtspu sftp shttp sip sips snews svn svn+ssh
        telnet wais irc'''.split()

    settings_overrides = {
        "raw_enabled": 0,  # no raw HTML code
        "file_insertion_enabled": 0,  # no file/URL access
        "halt_level": 2,  # at warnings or errors, raise an exception
        "report_level": 5,  # never report problems with the reST code
    }

    # capture publishing errors, they go to stderr
    old_stderr = sys.stderr
    sys.stderr = s = StringIO.StringIO()
    parts = None

    try:
        # Convert reStructuredText to HTML using Docutils.
        document = publish_doctree(source=source,
            settings_overrides=settings_overrides)

        for node in document.traverse():
            if node.tagname == '#text':
                continue
            if node.hasattr('refuri'):
                uri = node['refuri']
            elif node.hasattr('uri'):
                uri = node['uri']
            else:
                continue
            o = urlparse.urlparse(uri)
            if o.scheme not in ALLOWED_SCHEMES:
                raise TransformError('link scheme not allowed')

        # now turn the transformed document into HTML
        reader = readers.doctree.Reader(parser_name='null')
        pub = Publisher(reader, source=io.DocTreeInput(document),
            destination_class=io.StringOutput)
        pub.set_writer('html')
        pub.process_programmatic_settings(None, settings_overrides, None)
        pub.set_destination(None, None)
        pub.publish()
        parts = pub.writer.parts

    except:
        pass

    sys.stderr = old_stderr

    # original text if publishing errors occur
    if parts is None or len(s.getvalue()) > 0:
        return None
    else:
        return parts['body']
开发者ID:dstufft,项目名称:recliner,代码行数:58,代码来源:check_render.py

示例12: get_html

    def get_html(self, body_only=True, content_only=False, noclasses=False):
        import sys
        import pygments_rest
        from docutils.core import Publisher
        from docutils.io import StringInput, StringOutput
        from cStringIO import StringIO
        
        settings = {'doctitle_xform'     : 1,
                    'pep_references'     : 1,
                    'rfc_references'     : 1,
                    'footnote_references': 'superscript',
                    'output_encoding'    : 'unicode',
                    'report_level'       : 2, # 2=show warnings, 3=show only errors, 5=off (docutils.utils
                    }

        if content_only:
            post_rst = self.get_rst(noclasses=noclasses)
        else:
            post_rst = render_to('post_single.rst', 
                                 post=self, 
                                 noclasses=noclasses)
                             
        pub = Publisher(reader=None, 
                        parser=None, 
                        writer=None, 
                        settings=None,
                        source_class=StringInput,
                        destination_class=StringOutput)

        pub.set_components(reader_name='standalone',
                           parser_name='restructuredtext',
                           writer_name='html')
        pub.process_programmatic_settings(settings_spec=None,
                                          settings_overrides=settings,
                                          config_section=None)
        pub.set_source(post_rst,source_path=self.module_path)
        pub.set_destination(None, None)

        errors_io = StringIO()
        real_stderr = sys.stderr
        sys.stderr = errors_io
        try:
            html_full = pub.publish(enable_exit_status=False)
            html_body = ''.join(pub.writer.html_body)
        finally:
            sys.stderr = real_stderr
        errors = errors_io.getvalue()
        self._process_rest_errors(errors)

        errors_io.close()

        return html_body if body_only else html_full
开发者ID:mahmoud,项目名称:PythonDoesBlog,代码行数:52,代码来源:post.py

示例13: process_description

def process_description(source, output_encoding='unicode'):
    """Given an source string, returns an HTML fragment as a string.

    The return value is the contents of the <body> tag.

    Parameters:

    - `source`: A multi-line text string; required.
    - `output_encoding`: The desired encoding of the output.  If a Unicode
      string is desired, use the default value of "unicode" .
    """
    # Dedent all lines of `source`.
    source = trim_docstring(source)

    settings_overrides = {
        'raw_enabled': 0,  # no raw HTML code
        'file_insertion_enabled': 0,  # no file/URL access
        'halt_level': 2,  # at warnings or errors, raise an exception
        'report_level': 5,  # never report problems with the reST code
        }

    parts = None

    # Convert reStructuredText to HTML using Docutils.
    document = publish_doctree(source=source,
        settings_overrides=settings_overrides)

    for node in document.traverse():
        if node.tagname == '#text':
            continue
        if node.hasattr('refuri'):
            uri = node['refuri']
        elif node.hasattr('uri'):
            uri = node['uri']
        else:
            continue
        o = urlparse(uri)
        if o.scheme not in ALLOWED_SCHEMES:
            raise TransformError('link scheme not allowed: {0}'.format(uri))

    # now turn the transformed document into HTML
    reader = readers.doctree.Reader(parser_name='null')
    pub = Publisher(reader, source=io.DocTreeInput(document),
        destination_class=io.StringOutput)
    pub.set_writer('html')
    pub.process_programmatic_settings(None, settings_overrides, None)
    pub.set_destination(None, None)
    pub.publish()
    parts = pub.writer.parts

    output = parts['body']

    if output_encoding != 'unicode':
        output = output.encode(output_encoding)

    return output
开发者ID:jfinkels,项目名称:sphinxcontrib-issuetracker,代码行数:56,代码来源:pypi.py

示例14: inspect

def inspect(filename, source_path=None):
    "returns the document object before any transforms)"
    from docutils.core import Publisher

    pub = Publisher(source_class=io.FileInput)
    pub.set_reader("standalone", None, "restructuredtext")
    pub.process_programmatic_settings(None, None, None)
    pub.set_source(source_path=source_path)
    pub.set_io()
    return pub.reader.read(pub.source, pub.parser, pub.settings)
开发者ID:BackupTheBerlios,项目名称:lino-svn,代码行数:10,代码来源:restify.py

示例15: check_rst

 def check_rst(self, rst):
     pub = Publisher(reader=None, parser=None, writer=None, settings=None,
                     source_class=io.StringInput,
                     destination_class=io.StringOutput)
     pub.set_components(reader_name='standalone',
                        parser_name='restructuredtext',
                        writer_name='pseudoxml')
     pub.process_programmatic_settings(
         settings_spec=None,
         settings_overrides={'output_encoding': 'unicode'},
         config_section=None,
     )
     pub.set_source(rst, source_path=None)
     pub.set_destination(destination=None, destination_path=None)
     output = pub.publish(enable_exit_status=False)
     self.assertLess(pub.document.reporter.max_level, 0)
     return output, pub
开发者ID:miyakogi,项目名称:m2r,代码行数:17,代码来源:test_renderer.py


注:本文中的docutils.core.Publisher类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。