[docs]defpreview(expr,output='png',viewer=None,euler=True,packages=(),filename=None,outputbuffer=None,preamble=None,dvioptions=None,outputTexFile=None,**latex_settings):r""" View expression or LaTeX markup in PNG, DVI, PostScript or PDF form. If the expr argument is an expression, it will be exported to LaTeX and then compiled using the available TeX distribution. The first argument, 'expr', may also be a LaTeX string. The function will then run the appropriate viewer for the given output format or use the user defined one. By default png output is generated. By default pretty Euler fonts are used for typesetting (they were used to typeset the well known "Concrete Mathematics" book). For that to work, you need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the texlive-fonts-extra package). If you prefer default AMS fonts or your system lacks 'eulervm' LaTeX package then unset the 'euler' keyword argument. To use viewer auto-detection, lets say for 'png' output, issue >>> from sympy import symbols, preview, Symbol >>> x, y = symbols("x,y") >>> preview(x + y, output='png') This will choose 'pyglet' by default. To select a different one, do >>> preview(x + y, output='png', viewer='gimp') The 'png' format is considered special. For all other formats the rules are slightly different. As an example we will take 'dvi' output format. If you would run >>> preview(x + y, output='dvi') then 'view' will look for available 'dvi' viewers on your system (predefined in the function, so it will try evince, first, then kdvi and xdvi). If nothing is found you will need to set the viewer explicitly. >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer') This will skip auto-detection and will run user specified 'superior-dvi-viewer'. If 'view' fails to find it on your system it will gracefully raise an exception. You may also enter 'file' for the viewer argument. Doing so will cause this function to return a file object in read-only mode, if 'filename' is unset. However, if it was set, then 'preview' writes the genereted file to this filename instead. There is also support for writing to a StringIO like object, which needs to be passed to the 'outputbuffer' argument. >>> from StringIO import StringIO >>> obj = StringIO() >>> preview(x + y, output='png', viewer='StringIO', ... outputbuffer=obj) The LaTeX preamble can be customized by setting the 'preamble' keyword argument. This can be used, e.g., to set a different font size, use a custom documentclass or import certain set of LaTeX packages. >>> preamble = "\\documentclass[10pt]{article}\n" \ ... "\\usepackage{amsmath,amsfonts}\\begin{document}" >>> preview(x + y, output='png', preamble=preamble) If the value of 'output' is different from 'dvi' then command line options can be set ('dvioptions' argument) for the execution of the 'dvi'+output conversion tool. These options have to be in the form of a list of strings (see subprocess.Popen). Additional keyword args will be passed to the latex call, e.g., the symbol_names flag. >>> phidd = Symbol('phidd') >>> preview(phidd, symbol_names={phidd:r'\ddot{\varphi}'}) For post-processing the generated TeX File can be written to a file by passing the desired filename to the 'outputTexFile' keyword argument. To write the TeX code to a file named "sample.tex" and run the default png viewer to display the resulting bitmap, do >>> preview(x + y, outputTexFile="sample.tex") """special=['pyglet']ifviewerisNone:ifoutput=="png":viewer="pyglet"else:# sorted in order from most pretty to most ugly# very discussable, but indeed 'gv' looks awful :)# TODO add candidates for windows to listcandidates={"dvi":["evince","okular","kdvi","xdvi"],"ps":["evince","okular","gsview","gv"],"pdf":["evince","okular","kpdf","acroread","xpdf","gv"],}try:forcandidateincandidates[output]:path=find_executable(candidate)ifpathisnotNone:viewer=pathbreakelse:raiseSystemError("No viewers found for '%s' output format."%output)exceptKeyError:raiseSystemError("Invalid output format: %s"%output)else:ifviewer=="file":iffilenameisNone:SymPyDeprecationWarning(feature="Using viewer=\"file\" without a ""specified filename",deprecated_since_version="0.7.3",useinstead="viewer=\"file\" and filename=\"desiredname\"",issue=3919).warn()elifviewer=="StringIO":ifoutputbufferisNone:raiseValueError("outputbuffer has to be a StringIO ""compatible object if viewer=\"StringIO\"")elifviewernotinspecialandnotfind_executable(viewer):raiseSystemError("Unrecognized viewer: %s"%viewer)ifpreambleisNone:actual_packages=packages+("amsmath","amsfonts")ifeuler:actual_packages+=("euler",)package_includes="\n"+"\n".join(["\\usepackage{%s}"%pforpinactual_packages])preamble=r"""\documentclass[12pt]{article}\pagestyle{empty}%s\begin{document}"""%(package_includes)else:iflen(packages)>0:raiseValueError("The \"packages\" keyword must not be set if a ""custom LaTeX preamble was specified")latex_main=preamble+'\n%s\n\n'+r"\end{document}"ifisinstance(expr,str):latex_string=exprelse:latex_string=latex(expr,mode='inline',**latex_settings)try:workdir=tempfile.mkdtemp()withopen(join(workdir,'texput.tex'),'w')asfh:fh.write(latex_main%latex_string)ifoutputTexFileisnotNone:shutil.copyfile(join(workdir,'texput.tex'),outputTexFile)ifnotfind_executable('latex'):raiseRuntimeError("latex program is not installed")try:check_output(['latex','-halt-on-error','-interaction=nonstopmode','texput.tex'],cwd=workdir,stderr=STDOUT)exceptCalledProcessError,e:raiseRuntimeError("'latex' exited abnormally with the following output:\n%s"%e.output)ifoutput!="dvi":defaultoptions={"ps":[],"pdf":[],"png":["-T","tight","-z","9","--truecolor"]}commandend={"ps":["-o","texput.ps","texput.dvi"],"pdf":["texput.dvi","texput.pdf"],"png":["-o","texput.png","texput.dvi"]}cmd=["dvi"+output]ifnotfind_executable(cmd[0]):raiseRuntimeError("%s is not installed"%cmd[0])try:ifdvioptionsisnotNone:cmd.extend(dvioptions)else:cmd.extend(defaultoptions[output])cmd.extend(commandend[output])exceptKeyError:raiseSystemError("Invalid output format: %s"%output)try:check_output(cmd,cwd=workdir,stderr=STDOUT)exceptCalledProcessError,e:raiseRuntimeError("'%s' exited abnormally with the following output:\n%s"%(' '.join(cmd),e.output))src="texput.%s"%(output)ifviewer=="file":iffilenameisNone:buffer=StringIO()withopen(join(workdir,src),'rb')asfh:buffer.write(fh.read())returnbufferelse:shutil.move(join(workdir,src),filename)elifviewer=="StringIO":withopen(join(workdir,src),'rb')asfh:outputbuffer.write(fh.read())elifviewer=="pyglet":try:frompygletimportwindow,image,glfrompyglet.windowimportkeyexceptImportError:raiseImportError("pyglet is required for preview.\n visit http://www.pyglet.org/")ifoutput=="png":frompyglet.image.codecs.pngimportPNGImageDecoderimg=image.load(join(workdir,src),decoder=PNGImageDecoder())else:raiseSystemError("pyglet preview works only for 'png' files.")offset=25win=window.Window(width=img.width+2*offset,height=img.height+2*offset,caption="sympy",resizable=False)win.set_vsync(False)try:defon_close():win.has_exit=Truewin.on_close=on_closedefon_key_press(symbol,modifiers):ifsymbolin[key.Q,key.ESCAPE]:on_close()win.on_key_press=on_key_pressdefon_expose():gl.glClearColor(1.0,1.0,1.0,1.0)gl.glClear(gl.GL_COLOR_BUFFER_BIT)img.blit((win.width-img.width)/2,(win.height-img.height)/2)win.on_expose=on_exposewhilenotwin.has_exit:win.dispatch_events()win.flip()exceptKeyboardInterrupt:passwin.close()else:try:check_output([viewer,src],cwd=workdir,stderr=STDOUT)exceptCalledProcessError,e:raiseRuntimeError("'%s%s' exited abnormally with the following output:\n%s"%(viewer,src,e.output))finally:try:shutil.rmtree(workdir)# delete directoryexceptOSError,e:ife.errno!=2:# code 2 - no such file or directoryraise