本文整理汇总了Python中sphinx.util.ensuredir函数的典型用法代码示例。如果您正苦于以下问题:Python ensuredir函数的具体用法?Python ensuredir怎么用?Python ensuredir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ensuredir函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self):
self.assert_has_content()
text = '\n'.join(self.content)
parsed = highlight(text, PythonLexer(), HtmlFormatter())
result = [nodes.raw('', parsed, format='html')]
if True: # If we want a snapshot - this should check the 'snapshot argument'#
fn = '{}.png'.format(sha(text).hexdigest())
env = self.state.document.settings.env
rel_filename, filename = env.relfn2path(fn)
outfn = os.path.join(env.app.builder.outdir, '_static', rel_filename)
ensuredir(os.path.dirname(outfn))
script_to_render = BOT_HEADER + text
try:
subprocess.call(['sbot', '-o', '%s' % outfn, script_to_render])
except Exception, e:
raise ShoebotError(str(e))
# TODO - Support other output formats
image_node = nodes.raw('', html_img_tag(rel_filename), format='html')
result.insert(0,image_node)
示例2: handle_page
def handle_page(self, pagename, addctx, templatename='page.html',
outfilename=None, event_arg=None):
ctx = self.globalcontext.copy()
# current_page_name is backwards compatibility
ctx['pagename'] = ctx['current_page_name'] = pagename
def pathto(otheruri, resource=False,
baseuri=self.get_target_uri(pagename)):
if not resource:
otheruri = self.get_target_uri(otheruri)
return relative_uri(baseuri, otheruri)
ctx['pathto'] = pathto
ctx['hasdoc'] = lambda name: name in self.env.all_docs
ctx['customsidebar'] = self.config.html_sidebars.get(pagename)
ctx['toctree'] = lambda **kw: self._get_local_toctree(pagename, **kw)
ctx.update(addctx)
self.app.emit('html-page-context', pagename, templatename,
ctx, event_arg)
output = self.templates.render(templatename, ctx)
if not outfilename:
outfilename = self.get_outfilename(pagename)
# outfilename's path is in general different from self.outdir
ensuredir(path.dirname(outfilename))
try:
f = codecs.open(outfilename, 'w', 'utf-8')
try:
f.write(output)
finally:
f.close()
except (IOError, OSError), err:
self.warn("error writing file %s: %s" % (outfilename, err))
示例3: render_aafigure
def render_aafigure(app, text, options):
"""
Render an ASCII art figure into the requested format output file.
"""
_id = None
if aafigure is None:
raise AafigError('aafigure module not installed')
fname = '%s.%s' % (get_basename(text, options), options['format'])
if app.builder.format == 'html':
# HTML
imgpath = relative_uri(app.builder.env.docname, '_images')
relfn = posixpath.join(imgpath, fname)
outfn = path.join(app.builder.outdir, '_images', fname)
else:
# Non-HTML
if app.builder.format != 'latex':
app.builder.warn('aafig: the builder format %s is not officially '
'supported, aafigure images could not work. Please report '
'problems and working builder to avoid this warning in '
'the future' % app.builder.format)
relfn = fname
outfn = path.join(app.builder.outdir, fname)
metadata_fname = '%s.aafig' % outfn
try:
if path.isfile(outfn):
extra = None
if options['format'].lower() == 'svg':
f = None
try:
try:
with open(metadata_fname, 'r') as f:
extra = f.read()
except Exception:
raise AafigError()
finally:
if f is not None:
f.close()
return relfn, outfn, _id, extra
except AafigError:
pass
ensuredir(path.dirname(outfn))
try:
(visitor, output) = aafigure.render(text, outfn, options)
output.close()
except aafigure.UnsupportedFormatError as e:
raise AafigError(str(e))
extra = None
if options['format'].lower() == 'svg':
extra = visitor.get_size_attrs()
with open(metadata_fname, 'w') as f:
f.write(extra)
return relfn, outfn, _id, extra
示例4: render_yuml
def render_yuml(app, uri, text, options):
"""
Render yuml into a image file.
"""
format_map = DEFAULT_FORMATS.copy()
format_map.update(app.builder.config.yuml_format)
option_map = DEFAULT_OPTIONS.copy()
option_map.update(options)
term = format_map[app.builder.format]
fname = get_filename(text, options, term)
if app.builder.format == 'html':
# HTML
imgpath = relative_uri(app.builder.env.docname,'_images')
relfn = posixpath.join(imgpath, fname)
outfn = path.join(app.builder.outdir, '_images', fname)
else:
# Non-HTML
if app.builder.format != 'latex':
log_warn(app, 'yuml: the builder format %s is not supported.' % app.builder.format)
relfn = fname
outfn = path.join(app.builder.outdir, fname)
ensuredir(path.dirname(outfn))
docdir = (path.dirname(app.builder.env.docname))
try:
debug(app, '[Yuml] generating diagram in %s' % fname)
opts = option_map['style']
if 'scale' in option_map:
opts += ';scale:%s' % option_map['scale']
opts += ';dir:%s' % option_map['direction']
try:
data = urllib.parse.quote(text, encoding='utf-8')
except Exception:
data = urllib.quote(text.encode('utf-8'))
url = '%s/%s/%s/%s.%s' % (app.builder.config.yuml_server_url.strip('/'), opts, option_map['type'], data, term)
debug(app, '[Yuml] with URL %s' % url)
headers = {
'User-Agent' : 'sphinxcontrib/yuml v0.1',
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
req = urllib2.Request(url, None, headers)
rep = urllib2.urlopen(req).read()
out = open(outfn, 'wb')
out.write(rep)
out.close()
except Exception:
(_t, e, _tb) = sys.exc_info()
del(_tb)
raise YumlError(str(e))
return relfn
示例5: render_gruffy
def render_gruffy(self, code, options, formattype, prefix='gruffy'):
hashkey = code.encode('utf-8') + str(options)
fname = "%s-%s.%s" % (prefix, sha(hashkey).hexdigest(), formattype)
relfn = posixpath.join('_images', fname)
outfn = os.path.join(self.builder.outdir, '_images', fname)
ensuredir(os.path.dirname(outfn))
exec "g = gruffy.%s(%d)" % (options['type'], options['width'])
g.title = str(options['title'])
for line in code.splitlines():
exec "g.%s" % line.strip()
g.write(outfn)
return relfn
示例6: render_sdx
def render_sdx(self, code, options, format, prefix='sdedit'):
"""
Render sequence diagram into a PNG or PDF output file.
"""
hashkey = code.encode('utf-8') + str(options) + \
str(self.builder.config.sdedit_args)
ofname = '%s-%s.%s' % (prefix, sha(hashkey).hexdigest(), format)
ifname = '%s-%s.sd' % (prefix, sha(hashkey).hexdigest())
infn = os.path.join(self.builder.outdir, ifname)
if hasattr(self.builder, 'imgpath'):
# HTML
relfn = posixpath.join(self.builder.imgpath, ofname)
outfn = os.path.join(self.builder.outdir, '_images', ofname)
else:
# LaTeX
relfn = ofname
outfn = os.path.join(self.builder.outdir, ofname)
if os.path.isfile(outfn):
return relfn, outfn
if hasattr(self.builder, '_sdedit_warned'):
return None, None
ensuredir(os.path.dirname(outfn))
ensuredir(os.path.dirname(infn))
inputfile = open(infn, "w")
if isinstance(code, unicode):
code = code.encode('utf-8')
inputfile.write(code)
inputfile.close()
path = self.builder.config.sdedit_path
if path.endswith(".jar"):
sdedit_args = [self.builder.config.sdedit_java_path, "-jar", path]
else:
sdedit_args = [path]
sdedit_args.extend(self.builder.config.sdedit_args)
sdedit_args.extend(['-t', format, '-o', outfn, infn])
if options.get("linewrap"):
sdedit_args.extend(['--lineWrap', 'true'])
if options.get("threadnumber"):
sdedit_args.extend(['--threadNumbersVisible', 'true'])
try:
p = Popen(sdedit_args, stdout=PIPE, stdin=None, stderr=PIPE)
except OSError, err:
if err.errno != 2: # No such file or directory
raise
self.builder.warn('sdedit command %r cannot be run (needed for '
'sequence diagram output), check the sdedit_path '
' setting' %
self.builder.config.sdedit_path)
self.builder._sdedit_warned = True
return None, None
示例7: render_aafigure
def render_aafigure(app, text, options):
"""
Render an ASCII art figure into the requested format output file.
"""
if aafigure is None:
raise AafigError("aafigure module not installed")
fname = get_basename(text, options)
fname = "%s.%s" % (get_basename(text, options), options["format"])
if app.builder.format == "html":
# HTML
imgpath = relative_uri(app.builder.env.docname, "_images")
relfn = posixpath.join(imgpath, fname)
outfn = path.join(app.builder.outdir, "_images", fname)
else:
# Non-HTML
if app.builder.format != "latex":
app.builder.warn(
"aafig: the builder format %s is not officially "
"supported, aafigure images could not work. Please report "
"problems and working builder to avoid this warning in "
"the future" % app.builder.format
)
relfn = fname
outfn = path.join(app.builder.outdir, fname)
metadata_fname = "%s.aafig" % outfn
try:
if path.isfile(outfn):
extra = None
if options["format"].lower() == "svg":
f = None
try:
try:
f = file(metadata_fname, "r")
extra = f.read()
except:
raise AafigError()
finally:
if f is not None:
f.close()
return relfn, outfn, id, extra
except AafigError:
pass
ensuredir(path.dirname(outfn))
try:
(visitor, output) = aafigure.render(text, outfn, options)
output.close()
except aafigure.UnsupportedFormatError, e:
raise AafigError(str(e))
示例8: setup
def setup(app):
app.add_node(bibtex,
html=(visit_bibtex_node, depart_bibtex_node))
app.add_directive('bibtex', Bibtex)
# Sphinx already comes with jquery, otherwise the following is needed.
#app.add_javascript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/'
# 'jquery.min.js')
bibjs = 'bibtex_js.js'
app.add_javascript(bibjs)
source = os.path.abspath(os.path.join(os.path.dirname(__file__), bibjs))
target = os.path.join(app.outdir, '_static', bibjs)
ensuredir(os.path.dirname(target))
shutil.copyfile(source, target)
示例9: write_doc
def write_doc(self, docname, doctree):
destination = StringOutput(encoding='utf-8')
self.writer.write(doctree, destination)
outfilename = path.join(self.outdir, os_path(docname) + self.out_suffix)
ensuredir(path.dirname(outfilename))
try:
f = codecs.open(outfilename, 'w', 'utf-8')
try:
f.write(self.writer.output)
finally:
f.close()
except (IOError, OSError), err:
self.warn("error writing file %s: %s" % (outfilename, err))
示例10: run
def run(self):
env = self.state.document.settings.env
app = env.app
# workaround (used below) for https://github.com/sphinx-doc/sphinx/issues/3924
current_docname = env.docname
docdir = dirname(env.doc2path(env.docname))
specpath = join(docdir, self.arguments[0])
dest_dir = join(dirname(specpath), "gallery")
ensuredir(dest_dir)
env.note_dependency(specpath)
spec = json.load(open(specpath))
details = spec['details']
details_iter = status_iterator(details,
'copying gallery files... ',
'brown',
len(details),
stringify_func=lambda x: x['name'] + ".py")
env.gallery_updated = []
for detail in details_iter:
src_path = abspath(join("..", detail['path']))
dest_path = join(dest_dir, detail['name'] + ".py")
# sphinx pickled env works only with forward slash
docname = join(env.app.config.bokeh_gallery_dir, detail['name']).replace("\\","/")
try:
copyfile(src_path, dest_path)
except OSError as e:
raise SphinxError('cannot copy gallery file %r, reason: %s' % (src_path, e))
try:
env.clear_doc(docname)
env.read_doc(docname, app=app)
env.gallery_updated.append(docname)
except Exception as e:
raise SphinxError('failed to read gallery doc %r, reason: %s' % (docname, e))
names = [detail['name']for detail in details]
rst_text = GALLERY_PAGE.render(names=names)
# workaround for https://github.com/sphinx-doc/sphinx/issues/3924
env.temp_data['docname'] = current_docname
return self._parse(rst_text, "<bokeh-gallery>")
示例11: write_doc
def write_doc(self, docname, doctree):
doctree = self.assemble_doctree(docname)
destination = StringOutput(encoding="utf-8")
self.writer.write(doctree, destination)
outfilename = self.handle_filename(docname) + self.out_suffix
ensuredir(path.dirname(outfilename))
try:
f = codecs.open(outfilename, "w", "utf-8")
try:
f.write("".join(self.writer.output))
finally:
f.close()
except (IOError, OSError), err:
self.warn("error writing file %s: %s" % (outfilename, err))
示例12: render_lily
def render_lily(self, lily):
"""
Render the Lilypond music expression *lily* using lilypond.
"""
shasum = "%s.png" % sha(lily.encode('utf-8')).hexdigest()
relfn = posixpath.join(self.builder.imgpath, 'lily', shasum)
outfn = path.join(self.builder.outdir, '_images', 'lily', shasum)
if path.isfile(outfn):
return relfn
if hasattr(self.builder, '_lilypng_warned'):
return None, None
music = DOC_HEAD + self.builder.config.pnglily_preamble + lily
if isinstance(music, unicode):
music = music.encode('utf-8')
# use only one tempdir per build -- the use of a directory is cleaner
# than using temporary files, since we can clean up everything at once
# just removing the whole directory (see cleanup_tempdir_lily)
if not hasattr(self.builder, '_lilypng_tempdir'):
tempdir = self.builder._lilypng_tempdir = tempfile.mkdtemp()
else:
tempdir = self.builder._lilypng_tempdir
tf = open(path.join(tempdir, 'music.ly'), 'w')
tf.write(music)
tf.close()
ensuredir(path.dirname(outfn))
# use some standard lilypond arguments
lilypond_args = [self.builder.config.pnglily_lilypond]
#lilypond_args += ['-o', tempdir, '--png']
lilypond_args += ['-dbackend=eps', '-dno-gs-load-fonts', '-dinclude-eps-fonts',
'-o', tempdir, '--png']
# add custom ones from config value
lilypond_args.extend(self.builder.config.pnglily_lilypond_args)
# last, the input file name
lilypond_args.append(path.join(tempdir, 'music.ly'))
try:
p = Popen(lilypond_args, stdout=PIPE, stderr=PIPE)
except OSError, err:
if err.errno != 2: # No such file or directory
raise
self.builder.warn('lilypond command %r cannot be run (needed for music '
'display), check the pnglily_lilypond setting' %
self.builder.config.pnglily_lilypond)
self.builder._lilypng_warned = True
return None, None
示例13: render_msc
def render_msc(self, code, format, prefix='mscgen'):
"""
Render mscgen code into a PNG or PDF output file.
"""
hashkey = str(code.encode('utf-8')) + str(self.builder.config.mscgen_args)
id = sha(bytes(hashkey, 'utf-8')).hexdigest()
fname = '%s-%s.%s' % (prefix, id, format)
if hasattr(self.builder, 'imgpath') and self.builder.imgpath:
# HTML
relfn = posixpath.join(self.builder.imgpath, fname)
outfn = path.join(self.builder.outdir, '_images', fname)
tmpfn = outfn
mapfn = outfn + '.map'
else:
# LaTeX
relfn = fname
outfn = path.join(self.builder.outdir, fname)
format = 'eps'
tmpfn = outfn[:-3] + format
if path.isfile(outfn):
return relfn, outfn, id
if hasattr(self.builder, '_mscgen_warned'):
return None, None, None
ensuredir(path.dirname(outfn))
# mscgen don't support encodings very well. ISO-8859-1 seems to work best,
# at least for PNG.
if isinstance(code, str):
code = code.encode('iso-8859-1')
mscgen_args = [self.builder.config.mscgen]
mscgen_args.extend(self.builder.config.mscgen_args)
mscgen_args.extend(['-T', format, '-o', tmpfn, '-S', 'signalling'])
if not run_cmd(self.builder, mscgen_args, 'mscgen', 'mscgen', code):
return None, None, None
# if format == 'png':
# mscgen_args = mscgen_args[:-4] + ['-T', 'ismap', '-o', mapfn]
# if not run_cmd(self.builder, mscgen_args, 'mscgen', 'mscgen', code):
# return None, None, None
# else: # PDF/EPS
# if not eps_to_pdf(self.builder, tmpfn, outfn):
# return None, None, None
return relfn, outfn, id
示例14: write_doc
def write_doc(self, docname, doctree):
# Mostly copied from TextBuilder
destination = StringOutput(encoding='utf-8')
self.writer.write(doctree, destination)
outfilename = path.join(self.outdir,
os_path(docname.capitalize())+self.out_suffix)
# normally different from self.outdir
ensuredir(path.dirname(outfilename))
try:
f = codecs.open(outfilename, 'w', 'utf-8')
try:
f.write(self.writer.output)
finally:
f.close()
except (IOError, OSError), err:
self.warn("Error writing file %s: %s" % (outfilename, err))
示例15: html_tag_with_thumbnail
def html_tag_with_thumbnail(self, code, fname, new_width, image, imgcls):
width, height = image.size
new_height = height * new_width / width
image.resize((new_width, new_height), Image.ANTIALIAS)
image.filter(ImageFilter.DETAIL)
dir, file = os.path.split(fname)
ofname = os.path.basename(fname)
relfn = posixpath.join(self.builder.imgpath, "thumbnail", ofname)
outfn = os.path.join(self.builder.outdir, '_images', "thumbnail", ofname)
ensuredir(os.path.dirname(outfn))
image.save(outfn, "PNG")
imgcss = imgcls and 'class="%s"' % imgcls or ''
self.body.append('<a href="%s">' % relfn)
self.body.append('<img src="%s" alt="%s" width="%s" height="%s" %s/>\n' %
(fname, self.encode(code).strip(), new_width, new_height, imgcss))
self.body.append('</a>')