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


Python temporary_file.tmp_filename函数代码示例

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


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

示例1: show

    def show(self, delay=20, iterations=0):
        r"""
        Show this animation.

        INPUT:

        -  ``delay`` - (default: 20) delay in hundredths of a
           second between frames

        -  ``iterations`` - integer (default: 0); number of
           iterations of animation. If 0, loop forever.

        .. note::

           Currently this is done using an animated gif, though this
           could change in the future. This requires that either
           ffmpeg or the ImageMagick suite (in particular, the
           ``convert`` command) is installed.

        See also the :meth:`ffmpeg` method.

        EXAMPLES::

            sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)],
            ...                xmin=0, xmax=2*pi, figsize=[2,1])
            sage: a.show()       # optional -- ImageMagick

        The preceding will loop the animation forever. If you want to show
        only three iterations instead::

            sage: a.show(iterations=3)    # optional -- ImageMagick

        To put a half-second delay between frames::

            sage: a.show(delay=50)        # optional -- ImageMagick

        .. note::

           If you don't have ffmpeg or ImageMagick installed, you will
           get an error message like this::

              Error: Neither ImageMagick nor ffmpeg appears to be installed. Saving an
              animation to a GIF file or displaying an animation requires one of these
              packages, so please install one of them and try again.

              See www.imagemagick.org and www.ffmpeg.org for more information.
        """
        if plot.DOCTEST_MODE:
            filename = tmp_filename(ext=".gif")
            self.gif(savefile=filename, delay=delay, iterations=iterations)
            return

        if plot.EMBEDDED_MODE:
            self.gif(delay=delay, iterations=iterations)
        else:
            filename = tmp_filename(ext=".gif")
            self.gif(delay=delay, savefile=filename, iterations=iterations)
            os.system("%s %s 2>/dev/null 1>/dev/null &" % (sage.misc.viewer.browser(), filename))
开发者ID:sageb0t,项目名称:testsage,代码行数:58,代码来源:animate.py

示例2: graphics_from_save

def graphics_from_save(save_function, preferred_mime_types, 
                       allowed_mime_types=None, figsize=None, dpi=None):
    """
    Helper function to construct a graphics file.

    INPUT:
    
    - ``save_function`` -- callable that can save graphics to a file
      and accepts options like
      :meth:`sage.plot.graphics.Graphics.save``.

    - ``preferred_mime_types`` -- list of mime types. The graphics
      output mime types in order of preference (i.e. best quality to
      worst).

    - ``allowed_mime_types`` -- set of mime types (as strings). The
      graphics types that we can display. Output, if any, will be one
      of those.

    - ``figsize`` -- pair of integers (optional). The desired graphics
      size in pixels. Suggested, but need not be respected by the
      output.

    - ``dpi`` -- integer (optional). The desired resolution in dots
      per inch. Suggested, but need not be respected by the output.

    OUTPUT:

    Return an instance of
    :class:`sage.structure.graphics_file.GraphicsFile` encapsulating a
    suitable image file. Image is one of the
    ``preferred_mime_types``. If ``allowed_mime_types`` is specified,
    the resulting file format matches one of these.

    Alternatively, this function can return ``None`` to indicate that
    textual representation is preferable and/or no graphics with the
    desired mime type can be generated.
    """
    # Figure out best mime type
    mime = None
    if allowed_mime_types is None:
        mime = Mime.PNG
    else:
        # order of preference
        for m in preferred_mime_types:
            if m in allowed_mime_types:
                mime = m
                break
    if mime is None:
        return None    # don't know how to generate suitable graphics
    # Generate suitable temp file
    filename = tmp_filename(ext=os.path.extsep + Mime.extension(mime))
    # Call the save_function with the right arguments
    kwds = {}
    if figsize is not None:
        kwds['figsize'] = figsize
    if dpi is not None:
        kwds['dpi'] = dpi
    save_function(filename, **kwds)
    return GraphicsFile(filename, mime)
开发者ID:DrXyzzy,项目名称:sage,代码行数:60,代码来源:graphics_file.py

示例3: is_functional

    def is_functional(self):
        r"""
        Check whether ``theta`` works on a trivial example.

        EXAMPLES::

            sage: from sage.features.csdp import CSDP
            sage: CSDP().is_functional()  # optional: csdp
            FeatureTestResult('CSDP', True)
        """
        from sage.misc.temporary_file import tmp_filename
        tf_name = tmp_filename()
        with open(tf_name, 'wb') as tf:
            tf.write("2\n1\n1 1")
        devnull = open(os.devnull, 'wb')
        command = ['theta', tf_name]
        try:
            lines = subprocess.check_output(command, stderr=devnull)
        except subprocess.CalledProcessError as e:
            return FeatureTestResult(self, False,
                reason = "Call to `{command}` failed with exit code {e.returncode}.".format(command=" ".join(command), e=e))

        result = lines.strip().split('\n')[-1]
        match = re.match("^The Lovasz Theta Number is (.*)$", result)
        if match is None:
            return FeatureTestResult(self, False,
                reason = "Last line of the output of `{command}` did not have the expected format.".format(command=" ".join(command)))

        return FeatureTestResult(self, True)
开发者ID:sagemath,项目名称:sage,代码行数:29,代码来源:csdp.py

示例4: is_functional

    def is_functional(self):
        r"""
        Test whether ``lrs`` works on a trivial input.

        EXAMPLES::

            sage: from sage.features.lrs import Lrs
            sage: Lrs().is_functional()  # optional: lrslib
            FeatureTestResult('lrslib', True)
        """
        from sage.misc.temporary_file import tmp_filename
        tf_name = tmp_filename()
        with open(tf_name, 'wb') as tf:
            tf.write("V-representation\nbegin\n 1 1 rational\n 1 \nend\nvolume")
        devnull = open(os.devnull, 'wb')
        command = ['lrs', tf_name]
        try:
            lines = subprocess.check_output(command, stderr=devnull)
        except subprocess.CalledProcessError as e:
            return FeatureTestResult(self, False,
                reason = "Call to `{command}` failed with exit code {e.returncode}.".format(command=" ".join(command), e=e))

        expected = "Volume= 1"
        if lines.find(expected) == -1:
            return FeatureTestResult(self, False,
                reason = "Output of `{command}` did not contain the expected result `{expected}`.".format(command=" ".join(command),expected=expected))

        return FeatureTestResult(self, True)
开发者ID:sagemath,项目名称:sage,代码行数:28,代码来源:lrs.py

示例5: lrs_redund

def lrs_redund(in_str, verbose=False):
    r"""
    To remove redundant inequalities from an H-representation or
    input points that are not vertices from a V-representation
    use the command 'redund' from lrslib.

    Input: lrs format in_str; Output: lrs format out_str;

    Copy and edit from ``def _volume_lrs(self, verbose=False)``,
    http://www.sagenb.org/src/geometry/polyhedron/base.py
    """
    #if is_package_installed('lrslib') != True:
    #    print 'You must install the optional lrs package ' \
    #          'for this function to work'
    #    raise NotImplementedError

    in_filename = tmp_filename()
    in_file = open(in_filename,'w')
    in_file.write(in_str)
    in_file.close()
    if verbose: print(in_str)
    redund_procs = Popen(['redund',in_filename],stdin = PIPE, stdout=PIPE, stderr=PIPE)
    out_str, err = redund_procs.communicate()
    if verbose:
        print(out_str)
    return out_str
开发者ID:mkoeppe,项目名称:infinite-group-relaxation-code,代码行数:26,代码来源:vertex_enumeration.py

示例6: _launch_jmol

 def _launch_jmol(self):
     launch_script = tmp_filename(ext='.spt')
     with open(launch_script, 'w') as f:
         f.write('set defaultdirectory "{0}"\n'.format(self.filename()))
         f.write('script SCRIPT\n')
     from sage.env import SAGE_LOCAL
     JMOL = os.path.join(SAGE_LOCAL, 'bin', 'jmol')
     os.system('{0} {1} 2>/dev/null 1>/dev/null &'
               .format(JMOL, launch_script))
开发者ID:DrXyzzy,项目名称:sage,代码行数:9,代码来源:graphics_file.py

示例7: _launch_jmol

    def _launch_jmol(self):
        launch_script = tmp_filename(ext=".spt")
        with open(launch_script, "w") as f:
            f.write('set defaultdirectory "{0}"\n'.format(self.filename()))
            f.write("script SCRIPT\n")
        from sage.env import SAGE_LOCAL

        JMOL = os.path.join(SAGE_LOCAL, "bin", "jmol")
        os.system("{0} {1} 2>/dev/null 1>/dev/null &".format(JMOL, launch_script))
开发者ID:novoselt,项目名称:sage,代码行数:9,代码来源:graphics_file.py

示例8: file_name

 def file_name(self, val=None):
     """
     Show or set self.settings['file_name']
     """
     if val is not None:
         self.settings['file_name'] = val
     try:
         return self.settings['file_name']
     except KeyError:
         return self.file_name(tmp_filename(ext=self.image_format()))
开发者ID:nilesjohnson,项目名称:sage_animate,代码行数:10,代码来源:frame.py

示例9: filename

    def filename(self, ext=None):
        """
        Return the filename.

        INPUT:

        - ``ext`` -- string. The file extension.

        OUTPUT:

        Name of a file, most likely a temporary file. If ``ext`` is
        specified, the filename will have that extension.

        You must not modify the returned file. Its permissions are set
        to readonly to help with that.

        EXAMPLES::

            sage: from sage.repl.rich_output.buffer import OutputBuffer
            sage: buf = OutputBuffer('test')
            sage: buf.filename()           # random output
            '/home/user/.sage/temp/hostname/26085/tmp_RNSfAc'

            sage: os.path.isfile(buf.filename())
            True
            sage: buf.filename(ext='txt')  # random output
            '/home/user/.sage/temp/hostname/26085/tmp_Rjjp4V.txt'
            sage: buf.filename(ext='txt').endswith('.txt')
            True
        """
        if ext is None:
            ext = ''
        elif not ext.startswith('.'):
            ext = '.' + ext

        if self._filename is None or not self._filename.endswith(ext):
            from sage.misc.temporary_file import tmp_filename
            output = tmp_filename(ext=ext)
        else:
            output = self._filename

        if self._filename is None:
            assert self._data is not None
            with open(output, 'wb') as f:
                f.write(self._data)
            self._filename = output
        elif self._filename != output:
            try:
                os.link(self._filename, output)
            except (OSError, AttributeError):
                import shutil
                shutil.copy2(self._filename, output)

        self._chmod_readonly(output)
        return output
开发者ID:mcognetta,项目名称:sage,代码行数:55,代码来源:buffer.py

示例10: __call__

    def __call__(self, model, outfile='sage.png',
                 verbose=1, block=True, extra_opts=''):
        """
        This executes the tachyon program, given a scene file input.
        The default is to return the result as a PNG file called 'sage.png'.

        TESTS::

            sage: from sage.interfaces.tachyon import TachyonRT
            sage: tgen = Tachyon()
            sage: tgen.texture('t1')
            sage: tgen.sphere((0,0,0),1,'t1')
            sage: tgen.str()[30:40]
            'resolution'
            sage: t = TachyonRT()
            sage: import os
            sage: t(tgen.str(), outfile = os.devnull)
            tachyon ...
            Tachyon Parallel/Multiprocessor Ray Tracer...
        """
        modelfile = tmp_filename(ext='.dat')
        open(modelfile,'w').write(model)
        opts = ''
        ext = outfile[-4:].lower()
        if ext == '.png':
            opts += ' -format PNG '
        elif ext == '.tga':
            opts += ' -format TARGA '
        elif ext == '.bmp':
            opts += ' -format BMP '
        elif ext == '.ppm':
            opts += ' -format PPM '
        elif ext == '.rgb':
            opts += ' -format RGB '

        opts += ' -o %s '%outfile

        opts += ' ' + extra_opts + ' '

        if verbose >= 2:
            opts += ' +V '
        elif verbose == 0:
            opts += '  1>/dev/null'

        cmd = 'tachyon %s %s; rm -f "%s"'%(modelfile,opts, modelfile)

        if not block:
            cmd = '( ' + cmd + ' ) &'

        if verbose:
            print cmd
        # One should always flush before system()
        sys.stdout.flush()
        sys.stderr.flush()
        os.system(cmd)
开发者ID:bukzor,项目名称:sage,代码行数:55,代码来源:tachyon.py

示例11: preparse_file_named

def preparse_file_named(name):
    r"""
    Preparse file named \code{name} (presumably a .sage file), outputting to a
    temporary file.  Returns name of temporary file.
    """
    from sage.misc.temporary_file import tmp_filename
    tmpfilename = tmp_filename(os.path.basename(name)) + '.py'
    out = open(tmpfilename, 'w')
    preparse_file_named_to_stream(name, out)
    out.close()
    return tmpfilename
开发者ID:BlairArchibald,项目名称:sage,代码行数:11,代码来源:preparse.py

示例12: tex

    def tex(self, filename=None, include_header=True):
        """
        Writes the latex code to a file.

        INPUT:

        - ``filename`` -- string (default:``None``), the output filename.
          If ``None``, it saves the file in a temporary directory.
        - ``include_header`` -- bool (default:``True``) whether to include
          the header latex part. If ``False``, it prints only the
          tikzpicture part to the file.

        OUTPUT:

            string, path to tex file

        EXAMPLES::

            sage: from slabbe import TikzPicture
            sage: V = [[1,0,1],[1,0,0],[1,1,0],[0,0,-1],[0,1,0],[-1,0,0],[0,1,1],[0,0,1],[0,-1,0]]
            sage: P = Polyhedron(vertices=V).polar()
            sage: s = P.projection().tikz([674,108,-731],112)
            sage: t = TikzPicture(s)
            sage: _ = t.tex()

        Write only the tikzpicture without header and begin/end document::

            sage: _ = t.tex(include_header=False)

        Write to a given filename::

            sage: from sage.misc.temporary_file import tmp_filename
            sage: filename = tmp_filename('temp','.tex')
            sage: _ = t.tex(filename)

        """
        if filename is None:
            filename = tmp_filename('tikz_','.tex')
        else:
            filename = os.path.abspath(filename)

        if include_header:
            output = str(self)
        else:
            output = self.tikz_picture_code()

        with open(filename, 'w') as f:
            f.write(output)

        return filename
开发者ID:seblabbe,项目名称:slabbe,代码行数:50,代码来源:tikz_picture.py

示例13: runsnake

def runsnake(command):
    """
    Graphical profiling with ``runsnake``

    INPUT:

    - ``command`` -- the command to be run as a string.

    EXAMPLES::

        sage: runsnake("list(SymmetricGroup(3))")        # optional - runsnake

    ``command`` is first preparsed (see :func:`preparse`)::

        sage: runsnake('for x in range(1,4): print(x^2)') # optional - runsnake
        1
        4
        9

    :func:`runsnake` requires the program ``runsnake``. Due to non
    trivial dependencies (python-wxgtk, ...), installing it within the
    Sage distribution is unpractical. Hence, we recommend installing
    it with the system wide Python. On Ubuntu 10.10, this can be done
    with::

        > sudo apt-get install python-profiler python-wxgtk2.8 python-setuptools
        > sudo easy_install RunSnakeRun

    See the ``runsnake`` website for instructions for other platforms.

    :func:`runsnake` further assumes that the system wide Python is
    installed in ``/usr/bin/python``.

    .. seealso::

        - `The runsnake website <http://www.vrplumber.com/programming/runsnakerun/>`_
        - ``%prun``
        - :class:`Profiler`

    """
    import cProfile
    import os
    from sage.misc.temporary_file import tmp_filename
    from sage.misc.misc import get_main_globals
    from sage.repl.preparse import preparse
    tmpfile = tmp_filename()
    cProfile.runctx(preparse(command.lstrip().rstrip()), get_main_globals(), locals(), filename=tmpfile)
    os.system("/usr/bin/python -E `which runsnake` %s &" % tmpfile)
开发者ID:robertwb,项目名称:sage,代码行数:48,代码来源:dev_tools.py

示例14: lcdd_rational

def lcdd_rational(in_str, verbose=False):
    r"""
    Use the command ``lcdd_gmp`` from cddlib.

    Input: cdd format in_str; Output: cdd format out_str;
    """
    in_filename = tmp_filename()
    in_file = open(in_filename,'w')
    in_file.write(in_str)
    in_file.close()
    if verbose: 
        print(in_str)
    redund_procs = Popen(['lcdd_gmp',in_filename],stdin = PIPE, stdout=PIPE, stderr=PIPE)
    out_str, err = redund_procs.communicate()
    if verbose:
        print(out_str)
    return out_str
开发者ID:mkoeppe,项目名称:infinite-group-relaxation-code,代码行数:17,代码来源:vertex_enumeration.py

示例15: test_write_to_file

def test_write_to_file():
    """
    Test that libgap can write to files

    See :trac:`16502`, :trac:`15833`.

    EXAMPLES::

        sage: from sage.libs.gap.test import test_write_to_file
        sage: test_write_to_file()
    """
    fname = tmp_filename()
    message = "Ceci n'est pas une groupe"
    libgap.PrintTo(fname, message)
    with open(fname, 'r') as f:
        assert f.read() == message
    SystemFile = libgap.function_factory('StringFile')
    assert SystemFile(fname).sage() == message
开发者ID:Babyll,项目名称:sage,代码行数:18,代码来源:test.py


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