本文整理汇总了Python中docutils.core.Publisher.publish方法的典型用法代码示例。如果您正苦于以下问题:Python Publisher.publish方法的具体用法?Python Publisher.publish怎么用?Python Publisher.publish使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类docutils.core.Publisher
的用法示例。
在下文中一共展示了Publisher.publish方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_doc
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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
示例2: main
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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,
)
示例3: publish
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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)
示例4: from_file
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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
示例5: render
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
def render(self):
key = 'cia.apps.blog.%d' % self.id
parts = cache.get(key)
if not parts:
# Convert the reST markup to a document tree
document = publish_doctree(source = self.content)
visitor = ImageTranslator(document)
document.walkabout(visitor)
#
# Publish that document tree as HTML. We can't use any of
# the simpler methods in docutils.core, since we need
# access to writer.parts
#
reader = doctree.Reader(parser_name='null')
pub = Publisher(reader, None, None,
source = DocTreeInput(document),
destination_class = StringOutput)
pub.set_writer('html4css1')
pub.process_programmatic_settings(None, {
'cloak_email_addresses': True,
'initial_header_level': 2,
}, None)
pub.publish()
parts = pub.writer.parts
cache.set(key, parts)
return parts
示例6: render_rst
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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)
示例7: pypi_render
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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']
示例8: process_description
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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
示例9: convert
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
def convert(infilename, outfilename):
print "converting %s to %s" % (infilename, outfilename)
pub = Publisher()
pub.set_components('standalone', # reader
'restructuredtext', # parser
'latex') # writer (arg, will be discarded)
pub.reader = StandaloneReader()
pub.writer = VerseLaTeXWriter()
pub.process_programmatic_settings(None, None, None)
pub.set_source(source_path=infilename)
pub.set_destination(destination_path=outfilename)
pub.publish()
示例10: render_readme_like_pypi
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
def render_readme_like_pypi(source, output_encoding='unicode'):
"""
Render a ReST document just like PyPI does.
"""
# 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
示例11: _get_publisher
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
def _get_publisher(self, source_path):
extra_params = {'initial_header_level': '2',
'syntax_highlight': 'short',
'input_encoding': 'utf-8'}
user_params = self.settings.get('DOCUTILS_SETTINGS')
if user_params:
extra_params.update(user_params)
pub = Publisher(destination_class=StringOutput)
pub.set_components('standalone', 'restructuredtext', 'html')
pub.writer.translator_class = HTMLTranslator
pub.process_programmatic_settings(None, extra_params, None)
pub.set_source(source_path=source_path)
pub.publish()
return pub
示例12: parse_docstring
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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()
示例13: publish_cmdline_to_binary
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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
示例14: zotero_odf_scan_publish_cmdline_to_binary
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
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)
示例15: read_doc
# 需要导入模块: from docutils.core import Publisher [as 别名]
# 或者: from docutils.core.Publisher import publish [as 别名]
def read_doc(app, env, filename):
# type: (Sphinx, BuildEnvironment, unicode) -> nodes.document
"""Parse a document and convert to doctree."""
reader = SphinxStandaloneReader(app, parsers=app.registry.get_source_parsers())
source = SphinxFileInput(app, env, source=None, source_path=filename,
encoding=env.config.source_encoding)
pub = Publisher(reader=reader,
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