Ticket #13579: trac_13579_fix_test_executable.patch

File trac_13579_fix_test_executable.patch, 40.3 KB (added by vbraun, 9 years ago)

Updated patch

  • doc/common/builder.py

    # HG changeset patch
    # User Volker Braun <vbraun@stp.dias.ie>
    # Date 1349872370 -3600
    # Node ID 7ad363f983947f8f9b301b22107a5b99cda7934a
    # Parent  3f6951d77c2825cdebba3c451fda811c756640f8
    Fix security risk in test_executable
    
    diff --git a/doc/common/builder.py b/doc/common/builder.py
    a b  
    2323
    2424    EXAMPLES::
    2525
    26         sage: import os, sys; sys.path.append(os.environ['SAGE_DOC']+'/common/'); import builder
    27         sage: d = tmp_filename(); d
    28         '/.../tmp_...'
     26        sage: sys.path.append(os.environ['SAGE_DOC']+'/common/'); import builder
     27        sage: from sage.misc.misc import SAGE_TMP
     28        sage: d = os.path.join(SAGE_TMP, 'builder_test_dir');  d
     29        '...builder_test_dir'
    2930        sage: os.path.exists(d)
    3031        False
    3132        sage: dd = builder.mkdir(d)
  • doc/en/reference/misc.rst

    diff --git a/doc/en/reference/misc.rst b/doc/en/reference/misc.rst
    a b  
    1717   sage/misc/function_mangling
    1818   sage/misc/exceptions
    1919   sage/misc/misc
     20   sage/misc/temporary_file
    2021   sage/misc/bitset
    2122   sage/misc/constant_function
    2223   sage/misc/package
  • sage/databases/sql_db.py

    diff --git a/sage/databases/sql_db.py b/sage/databases/sql_db.py
    a b  
    8080import sqlite3 as sqlite
    8181import os
    8282import re
    83 from sage.misc.misc import tmp_filename
     83from sage.misc.all import tmp_filename
    8484from sage.structure.sage_object import SageObject
    8585
    8686sqlite_keywords = ['ABORT','ACTION','ADD','AFTER','ALL','ALTER','ANALYZE',
  • sage/ext/gen_interpreters.py

    diff --git a/sage/ext/gen_interpreters.py b/sage/ext/gen_interpreters.py
    a b  
    39873987    EXAMPLES::
    39883988
    39893989        sage: from sage.ext.gen_interpreters import *
    3990         sage: testdir = tmp_filename()
    3991         sage: os.mkdir(testdir)
     3990        sage: testdir = tmp_dir()
    39923991        sage: rdf_interp = RDFInterpreter()
    39933992        sage: build_interp(rdf_interp, testdir)
    39943993        sage: open(testdir + '/interp_rdf.c').readline()
     
    40164015    EXAMPLES::
    40174016
    40184017        sage: from sage.ext.gen_interpreters import *
    4019         sage: testdir = tmp_filename()
    4020         sage: os.mkdir(testdir)
     4018        sage: testdir = tmp_dir()
    40214019        sage: rebuild(testdir)
    40224020        Building interpreters for fast_callable
    40234021        sage: rebuild(testdir)
     
    40524050    build_interp(interp, dir)
    40534051
    40544052    # Do this last, so we don't do it if there's an error above.
    4055     with open(dir + '/timestamp', 'w'):
     4053    with open(os.path.join(dir, 'timestamp'), 'w'):
    40564054        pass
    40574055
    40584056# This list of modules gets added to the list in module_list.py.
  • sage/finance/stock.py

    diff --git a/sage/finance/stock.py b/sage/finance/stock.py
    a b  
    424424        ``AAPL-minutely.csv``. One can load this information into a Stock
    425425        object like so. Note that the path must be explicit::
    426426
    427             sage: filename = tmp_filename() + '.csv'
     427            sage: filename = tmp_filename(ext='.csv')
    428428            sage: open(filename,'w').write("Date,Open,High,Low,Close,Volume\n1212405780,187.80,187.80,187.80,187.80,100\n1212407640,187.75,188.00,187.75,188.00,2000\n1212407700,188.00,188.00,188.00,188.00,1000\n1212408000,188.00,188.11,188.00,188.00,2877\n1212408060,188.00,188.00,188.00,188.00,687")
    429429            sage: finance.Stock('aapl').load_from_file(filename)[:5]
    430430            [
     
    471471
    472472        This indirectly tests ``_load_from_csv()``::
    473473
    474             sage: filename = tmp_filename() + '.csv'
     474            sage: filename = tmp_filename(ext='.csv')
    475475            sage: open(filename,'w').write("Date,Open,High,Low,Close,Volume\n1212405780,187.80,187.80,187.80,187.80,100\n1212407640,187.75,188.00,187.75,188.00,2000\n1212407700,188.00,188.00,188.00,188.00,1000\n1212408000,188.00,188.11,188.00,188.00,2877\n1212408060,188.00,188.00,188.00,188.00,687")
    476476            sage: finance.Stock('aapl').load_from_file(filename)
    477477            [
  • sage/graphs/graph.py

    diff --git a/sage/graphs/graph.py b/sage/graphs/graph.py
    a b  
    35863586        EXAMPLES::
    35873587
    35883588            sage: P = graphs.PetersenGraph()
    3589             sage: P.write_to_eps(tmp_dir() + 'sage.eps')
     3589            sage: P.write_to_eps(tmp_filename(ext='.eps'))
    35903590
    35913591        It is relatively simple to include this file in a LaTeX
    35923592        document.  ``\usepackagegraphics`` must appear in the
  • sage/interfaces/axiom.py

    diff --git a/sage/interfaces/axiom.py b/sage/interfaces/axiom.py
    a b  
    253253       
    254254        ::
    255255       
    256             sage: filename = tmp_filename()+'.input'
     256            sage: filename = tmp_filename(ext='.input')
    257257            sage: f = open(filename, 'w')
    258258            sage: f.write('xx := 22;\n')
    259259            sage: f.close()
  • sage/interfaces/four_ti_2.py

    diff --git a/sage/interfaces/four_ti_2.py b/sage/interfaces/four_ti_2.py
    a b  
    7676            sage: f.directory()
    7777            '/tmp/'
    7878        """
    79         from sage.misc.misc import tmp_dir
     79        from sage.misc.temporary_file import tmp_dir
    8080        if self._directory is None:
    8181            # we have to put this here rather than in the __init__
    8282            # method since apparently importing sage.misc.misc does not
  • sage/interfaces/jmoldata.py

    diff --git a/sage/interfaces/jmoldata.py b/sage/interfaces/jmoldata.py
    a b  
    144144            sage: from sage.interfaces.jmoldata import JmolData
    145145            sage: JData = JmolData()
    146146            sage: script = "load =1lcd;display DNA;moveto 0.0 { -473 -713 -518 59.94} 100.0 0.0 0.0 {21.17 26.72 27.295} 27.544636 {0.0 0.0 0.0} -25.287832 64.8414 0.0;"
    147             sage: testfile = tmp_filename()+"DNA.png"
     147            sage: testfile = tmp_filename(ext="DNA.png")
    148148            sage: JData.export_image(targetfile=testfile,datafile=script,image_type="PNG") # optional -- internet
    149149            sage: print os.path.exists(testfile) # optional -- internet
    150150            True
  • sage/interfaces/magma.py

    diff --git a/sage/interfaces/magma.py b/sage/interfaces/magma.py
    a b  
    245245
    246246    EXAMPLES:
    247247        sage: sage.interfaces.magma.extcode_dir()
    248         '...dir_.../data/'
     248        '...tmp_dir-.../data/'
    249249    """
    250250    global EXTCODE_DIR
    251251    if not EXTCODE_DIR:
    252252        import shutil
    253         tmp = sage.misc.misc.tmp_dir()
     253        tmp = sage.misc.temporary_file.tmp_dir()
    254254        shutil.copytree('%s/magma/'%sage.misc.misc.SAGE_EXTCODE, tmp + '/data')
    255255        EXTCODE_DIR = "%s/data/"%tmp
    256256    return EXTCODE_DIR
  • sage/interfaces/mathematica.py

    diff --git a/sage/interfaces/mathematica.py b/sage/interfaces/mathematica.py
    a b  
    368368from expect import (Expect, ExpectElement, ExpectFunction,
    369369                    FunctionElement, AsciiArtString)
    370370
    371 from sage.misc.misc import graphics_filename
    372 
    373371def clean_output(s):
    374372    if s is None:
    375373        return ''
     
    837835        P = self._check_valid()
    838836        if P.eval('InputForm[%s]' % self.name()).strip().startswith('Graphics['):
    839837            if filename is None:
     838                from sage.misc.temporary_file import graphics_filename
    840839                filename = graphics_filename()
    841840            orig_dir = P.eval('Directory[]').strip()
    842841            P.chdir(os.path.abspath("."))
  • sage/interfaces/psage.py

    diff --git a/sage/interfaces/psage.py b/sage/interfaces/psage.py
    a b  
    5454            raise NotImplementedError, "PSage doesn't work on remote server yet."
    5555        Sage.__init__(self, **kwds)
    5656        import sage.misc.misc
    57         T = sage.misc.misc.tmp_dir('sage_smp')
     57        T = sage.misc.temporary_file.tmp_dir('sage_smp')
    5858        self.__tmp_dir = T
    5959        self.__tmp = '%s/lock'%T
    6060        self._unlock()
  • sage/interfaces/tachyon.py

    diff --git a/sage/interfaces/tachyon.py b/sage/interfaces/tachyon.py
    a b  
    9999            sage: t(tgen.str(), outfile = os.devnull)
    100100            tachyon ...
    101101        """
    102         modelfile = tmp_filename() + '.dat'
     102        modelfile = tmp_filename(ext='.dat')
    103103        open(modelfile,'w').write(model)
    104104        opts = ''
    105105        ext = outfile[-4:].lower()
  • sage/matrix/matrix2.pyx

    diff --git a/sage/matrix/matrix2.pyx b/sage/matrix/matrix2.pyx
    a b  
    3535from sage.structure.sequence import Sequence
    3636from sage.combinat.combinat import combinations_iterator
    3737from sage.structure.element import is_Vector
    38 from sage.misc.misc import verbose, get_verbose, graphics_filename
     38from sage.misc.misc import verbose, get_verbose
     39from sage.misc.temporary_file import graphics_filename
    3940from sage.rings.number_field.all import is_NumberField
    4041from sage.rings.integer_ring import ZZ, is_IntegerRing
    4142from sage.rings.integer import Integer
  • sage/matrix/matrix_modn_sparse.pyx

    diff --git a/sage/matrix/matrix_modn_sparse.pyx b/sage/matrix/matrix_modn_sparse.pyx
    a b  
    8484cimport matrix_dense
    8585from sage.rings.finite_rings.integer_mod cimport IntegerMod_int, IntegerMod_abstract
    8686
    87 from sage.misc.misc import verbose, get_verbose, graphics_filename
     87from sage.misc.misc import verbose, get_verbose
     88from sage.misc.temporary_file import graphics_filename
    8889
    8990import sage.rings.all as rings
    9091
  • sage/misc/all.py

    diff --git a/sage/misc/all.py b/sage/misc/all.py
    a b  
    44                  version, banner, add, union, uniq, powerset, subsets,
    55                  exists, forall, is_iterator,
    66                  random_sublist, mul, walltime, generic_cmp,
    7                   repr_lincomb, tmp_dir, tmp_filename,
     7                  repr_lincomb,
    88                  pad_zeros, attrcall,
    99                  DOT_SAGE, SAGE_ROOT, SAGE_URL, SAGE_DB, SAGE_TMP,
    1010                  is_32_bit, is_64_bit, newton_method_sizes, compose,
    1111                  self_compose, nest)
    1212
     13from temporary_file import tmp_dir, tmp_filename
     14
    1315from misc_c import prod, running_total, balanced_sum
    1416
    1517from dev_tools import runsnake, import_statements
  • sage/misc/cachefunc.pyx

    diff --git a/sage/misc/cachefunc.pyx b/sage/misc/cachefunc.pyx
    a b  
    20362036            sage: FC[((1,2),())] = 2
    20372037            sage: FC[((1,),(('a',1),))] = 3
    20382038            sage: for f in sorted(FC.file_list()): print f[len(dir):]
    2039             /t-.key.sobj
    2040             /t-.sobj
    2041             /t-1_2.key.sobj
    2042             /t-1_2.sobj
    2043             /t-a-1.1.key.sobj
    2044             /t-a-1.1.sobj
     2039            t-.key.sobj
     2040            t-.sobj
     2041            t-1_2.key.sobj
     2042            t-1_2.sobj
     2043            t-a-1.1.key.sobj
     2044            t-a-1.1.sobj
    20452045        """
    20462046        files = []
    20472047        prefix = self._prefix
     
    21382138        EXAMPLES::
    21392139
    21402140            sage: from sage.misc.cachefunc import FileCache
    2141             sage: dir = tmp_dir() + '/'
     2141            sage: dir = tmp_dir()
    21422142            sage: FC = FileCache(dir, memory_cache = False, prefix='foo')
    21432143            sage: N = FC._filename(((1,2), (('a',1),('b',2))))
    21442144            sage: print N[len(dir):]
     
    21662166        EXAMPLES::
    21672167
    21682168            sage: from sage.misc.cachefunc import FileCache
    2169             sage: dir = tmp_dir() + '/'
     2169            sage: dir = tmp_dir()
    21702170            sage: FC = FileCache(dir, memory_cache = False, prefix='foo')
    21712171            sage: k = ((),(('a',1),))
    21722172            sage: FC[k] = True
     
    21852185        EXAMPLES::
    21862186
    21872187            sage: from sage.misc.cachefunc import FileCache
    2188             sage: dir = tmp_dir() + '/'
     2188            sage: dir = tmp_dir()
    21892189            sage: FC1 = FileCache(dir, memory_cache = False, prefix='foo')
    21902190            sage: FC2 = FileCache(dir, memory_cache = False, prefix='foo')
    21912191            sage: k = ((),(('a',1),))
     
    22262226        EXAMPLES::
    22272227
    22282228            sage: from sage.misc.cachefunc import FileCache
    2229             sage: dir = tmp_dir() + '/'
     2229            sage: dir = tmp_dir()
    22302230            sage: FC1 = FileCache(dir, memory_cache = False, prefix='foo')
    22312231            sage: FC2 = FileCache(dir, memory_cache = False, prefix='foo')
    22322232            sage: k = ((),(('a',1),))
     
    22552255        EXAMPLES::
    22562256
    22572257            sage: from sage.misc.cachefunc import FileCache
    2258             sage: dir = tmp_dir() + '/'
     2258            sage: dir = tmp_dir()
    22592259            sage: FC1 = FileCache(dir, memory_cache = False, prefix='foo')
    22602260            sage: FC2 = FileCache(dir, memory_cache = False, prefix='foo')
    22612261            sage: k = ((),(('a',1),))
  • sage/misc/cython.py

    diff --git a/sage/misc/cython.py b/sage/misc/cython.py
    a b  
    647647    if verbose:
    648648        print s
    649649    import sage.misc.misc
    650     tmpfile = sage.misc.misc.tmp_filename() + ".spyx"
     650    tmpfile = sage.misc.temporary_file.tmp_filename(ext=".spyx")
    651651    open(tmpfile,'w').write(s)
    652652
    653653    import sage.server.support
     
    748748        sage: module.f(10)
    749749        100
    750750    """
    751     from sage.misc.misc import tmp_filename
    752     file = tmp_filename() + ".pyx"
     751    from sage.misc.temporary_file import tmp_filename
     752    file = tmp_filename(ext=".pyx")
    753753    open(file,'w').write(code)
    754754    from sage.server.support import cython_import
    755755    return cython_import(file, create_local_c_file=False)
  • sage/misc/cython_c.pyx

    diff --git a/sage/misc/cython_c.pyx b/sage/misc/cython_c.pyx
    a b  
    5656        Need to create a clever caching system so code only gets
    5757        compiled once.
    5858    """
    59     tmpfile = sage.misc.misc.tmp_filename() + ".spyx"
     59    tmpfile = sage.misc.temporary_file.tmp_filename(ext=".spyx")
    6060    open(tmpfile,'w').write(code)
    6161    sage.server.support.cython_import_all(tmpfile, globals(),
    6262                                         verbose=verbose, compile_message=compile_message,
  • sage/misc/inline_fortran.py

    diff --git a/sage/misc/inline_fortran.py b/sage/misc/inline_fortran.py
    a b  
    11import __builtin__
    22import os
    33
    4 from sage.misc.misc import tmp_filename
     4from sage.misc.temporary_file import tmp_filename
    55
    66count=0
    77
     
    6666        # if the first line has !f90 as a comment gfortran will treat it as
    6767        # fortran 90 code
    6868        if x.startswith('!f90'):
    69             fname = os.path.join(tmp_filename() +'.f90')
     69            fname = tmp_filename(ext='.f90')
    7070        else:
    71             fname = os.path.join(tmp_filename() +'.f')
     71            fname = tmp_filename(ext='.f')
    7272
    7373        log = tmp_filename()
    7474        extra_args = '--quiet --f77exec=sage-inline-fortran --f90exec=sage-inline-fortran %s %s >"%s" 2>&1'%(
  • sage/misc/latex.py

    diff --git a/sage/misc/latex.py b/sage/misc/latex.py
    a b  
    5454import subprocess
    5555import types
    5656
    57 from misc import tmp_dir, graphics_filename
     57from sage.misc.temporary_file import tmp_dir, graphics_filename
    5858import sage_eval
    5959from sage.misc.sage_ostools import have_program
    6060from sage.misc.cachefunc import cached_function, cached_method
  • sage/misc/misc.py

    diff --git a/sage/misc/misc.py b/sage/misc/misc.py
    a b  
    3838import operator, os, stat, socket, sys, signal, time, weakref, resource, math
    3939import sage.misc.prandom as random
    4040
     41from sage.misc.temporary_file import tmp_dir, tmp_filename
     42
    4143from banner import version, banner
    4244
    4345SAGE_ROOT = os.environ["SAGE_ROOT"]
     
    19651967set_trace = pdb.set_trace
    19661968
    19671969
    1968 #################################################################
    1969 # temporary directory
    1970 #################################################################
    1971 
    1972 import tempfile
    1973 
    1974 def tmp_dir(name="dir", ext=""):
    1975     r"""
    1976     Create and return a temporary directory in
    1977     ``$HOME/.sage/temp/hostname/pid/``
    1978 
    1979     INPUT:
    1980 
    1981     - ``name`` -- (default: "dir") A prefix for the directory name.
    1982 
    1983     - ``ext`` -- (default: "") A suffix for the directory name.
    1984 
    1985     OUTPUT: The absolute path of the temporary directory created.
    1986 
    1987     EXAMPLES::
    1988        
    1989         sage: d = tmp_dir('dir_testing_', '.extension')
    1990         sage: d  # random
    1991         '/home/username/sage/temp/hostname/7961/dir_testing_XgRu4p.extension'
    1992         sage: os.chdir(d)
    1993         sage: _ = open('file_inside_d', 'w')
    1994         sage: os.chdir(DOT_SAGE)
    1995         sage: import shutil
    1996         sage: shutil.rmtree(d)
    1997     """
    1998     tmp = tempfile.mkdtemp(prefix=name, suffix=ext, dir=SAGE_TMP)
    1999     return os.path.abspath(tmp)
    2000    
    2001 
    2002 #################################################################
    2003 # temporary filename
    2004 #################################################################
    2005 
    2006 def tmp_filename(name="tmp", ext=""):
    2007     r"""
    2008     Create and return a temporary file in
    2009     ``$HOME/.sage/temp/hostname/pid/``
    2010 
    2011     INPUT:
    2012 
    2013     - ``name`` -- (default: "tmp") A prefix for the file name.
    2014 
    2015     - ``ext`` -- (default: "") A suffix for the file name.
    2016 
    2017     OUTPUT: The absolute path of the temporary file created.
    2018 
    2019     EXAMPLES::
    2020 
    2021         sage: fn = tmp_filename('just_for_testing_', '.extension')
    2022         sage: fn  # random
    2023         '/home/username/.sage/temp/hostname/8044/just_for_testing_tVVHsn.extension'
    2024         sage: _ = open(fn, 'w')
    2025         sage: os.unlink(fn)
    2026     """
    2027     handle, tmp = tempfile.mkstemp(prefix=name, suffix=ext, dir=SAGE_TMP)
    2028     os.close(handle)
    2029     return os.path.abspath(tmp)
    2030 
    2031 def graphics_filename(ext='png'):
    2032     """
    2033     Return the next available canonical filename for a plot/graphics
    2034     file.
    2035     """
    2036     i = 0
    2037     while os.path.exists('sage%d.%s'%(i,ext)):
    2038         i += 1
    2039     filename = 'sage%d.%s'%(i,ext)
    2040     return filename
    2041 
    20421970
    20431971#################################################################
    20441972# Word wrap lines
  • sage/misc/preparser.py

    diff --git a/sage/misc/preparser.py b/sage/misc/preparser.py
    a b  
    15061506
    15071507    Note that .py files are *not* preparsed::
    15081508   
    1509         sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hi',2/3; z=-2/9")
     1509        sage: t=tmp_filename(ext='.py'); open(t,'w').write("print 'hi',2/3; z=-2/9")
    15101510        sage: sage.misc.preparser.load(t,globals())
    15111511        hi 0
    15121512        sage: z
     
    15141514
    15151515    A .sage file *is* preparsed::
    15161516   
    1517         sage: t=tmp_filename()+'.sage'; open(t,'w').write("print 'hi',2/3; s=-2/7")
     1517        sage: t=tmp_filename(ext='.sage'); open(t,'w').write("print 'hi',2/3; s=-2/7")
    15181518        sage: sage.misc.preparser.load(t,globals())
    15191519        hi 2/3
    15201520        sage: s
     
    15221522
    15231523    Cython files are *not* preparsed::
    15241524   
    1525         sage: t=tmp_filename()+'.pyx'; open(t,'w').write("print 'hi',2/3; z=-2/9")
     1525        sage: t=tmp_filename(ext='.pyx'); open(t,'w').write("print 'hi',2/3; z=-2/9")
    15261526        sage: z=0; sage.misc.preparser.load(t,globals())
    15271527        Compiling ....pyx...
    15281528        hi 0
     
    15401540    A filename given as an expression get evaluated.  This ensures
    15411541    that ``load DATA+'foo.sage'`` works in the Notebook, say::
    15421542
    1543         sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     1543        sage: t=tmp_filename(ext='.py'); open(t,'w').write("print 'hello world'")
    15441544        sage: sage.misc.preparser.load(t, globals())
    15451545        hello world
    15461546
     
    15551555
    15561556    We attach a file::
    15571557
    1558         sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     1558        sage: t=tmp_filename(ext='.py'); open(t,'w').write("print 'hello world'")
    15591559        sage: sage.misc.preparser.load(t, globals(), attach=True)
    15601560        hello world
    15611561        sage: os.path.normpath(t) in sage.misc.preparser.attached
     
    15931593
    15941594    Make sure that load handles filenames with spaces in the name or path::
    15951595
    1596         sage: t = tmp_filename() + ' b.sage'; open(t,'w').write("print 2")
     1596        sage: t = tmp_filename(ext=' b.sage'); open(t,'w').write("print 2")
    15971597        sage: sage.misc.preparser.load(t, globals())
    15981598        2
    15991599    """
     
    18421842    EXAMPLES::
    18431843   
    18441844        sage: sage.misc.reset.reset_attached()
    1845         sage: t=tmp_filename()+'.py';
     1845        sage: t=tmp_filename(ext='.py');
    18461846        sage: a = 0
    18471847        sage: f = open(t,'w'); f.write("a = 5"); f.close()
    18481848        sage: attach(t)
     
    18791879    EXAMPLES::
    18801880
    18811881        sage: sage.misc.reset.reset_attached()
    1882         sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     1882        sage: t=tmp_filename(ext='.py'); open(t,'w').write("print 'hello world'")
    18831883        sage: t = os.path.normpath(t)
    18841884        sage: attach(t)
    18851885        hello world
     
    18991899    EXAMPLES::
    19001900
    19011901        sage: sage.misc.reset.reset_attached()
    1902         sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     1902        sage: t=tmp_filename(ext='.py'); open(t,'w').write("print 'hello world'")
    19031903        sage: t = os.path.normpath(t)
    19041904        sage: attach(t)
    19051905        hello world
  • sage/misc/reset.pyx

    diff --git a/sage/misc/reset.pyx b/sage/misc/reset.pyx
    a b  
    3131        sage: x
    3232        x
    3333
    34         sage: fn = os.path.normpath(tmp_filename() + 'foo.py')
     34        sage: fn = tmp_filename(ext='foo.py')
    3535        sage: sage.misc.reset.EXCLUDE.add('fn')
    3636        sage: open(fn, 'w').write('a = 111')
    3737        sage: attach(fn)
     
    167167    EXAMPLES::
    168168   
    169169        sage: sage.misc.reset.reset_attached()
    170         sage: t = tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     170        sage: t = tmp_filename(ext='.py'); open(t,'w').write("print 'hello world'")
    171171        sage: t = os.path.normpath(t)
    172172        sage: attach(t)
    173173        hello world
  • sage/misc/session.pyx

    diff --git a/sage/misc/session.pyx b/sage/misc/session.pyx
    a b  
    378378    Here we test attaching multiple files at once::
    379379   
    380380        sage: sage.misc.reset.reset_attached()
    381         sage: t1=tmp_filename()+'.py'; open(t1,'w').write("print 'hello world'")
    382         sage: t2=tmp_filename()+'.py'; open(t2,'w').write("print 'hi there xxx'")
     381        sage: t1=tmp_filename(ext='.py'); open(t1,'w').write("print 'hello world'")
     382        sage: t2=tmp_filename(ext='.py'); open(t2,'w').write("print 'hi there xxx'")
    383383        sage: t1, t2 = map(os.path.normpath, (t1, t2))
    384384        sage: attach(t1, t2)
    385385        hello world
    386386        hi there xxx
    387         sage: attached_files() == [t1,t2]
     387        sage: set(attached_files()) == set([t1,t2])
    388388        True
    389        
    390    
     389
    391390    The contents of the file are then loaded, which means they are
    392391    read into the running Sage session. For example, if ``foo.sage``
    393392    contains ``x=5``, after attaching ``foo.sage`` the variable ``x``
  • new file sage/misc/temporary_file.py

    diff --git a/sage/misc/temporary_file.py b/sage/misc/temporary_file.py
    new file mode 100644
    - +  
     1"""
     2Temporary file handling
     3"""
     4
     5import os
     6import tempfile
     7import atexit
     8from shutil import rmtree
     9
     10temporary_directories = []
     11temporary_files = []
     12
     13def _delete_temporary_files_at_exit():
     14    """
     15    Remove all temporary files
     16
     17    EXAMPLES::
     18
     19        sage: from sage.misc.temporary_file import tmp_filename, temporary_files
     20        sage: old_temporary_files = list(temporary_files)
     21        sage: tmp = tmp_filename('test')
     22        sage: new_temporary_files = list(temporary_files)
     23        sage: set(new_temporary_files).difference(old_temporary_files) == set([tmp])
     24        True
     25    """
     26    global temporary_files, temporary_directories
     27    for f in temporary_files:
     28        try:
     29            os.unlink(f)
     30        except OSError:
     31            pass
     32    for d in temporary_directories:
     33        rmtree(d, ignore_errors=True)
     34
     35
     36# Run when Python shuts down
     37atexit.register(_delete_temporary_files_at_exit)
     38
     39
     40#################################################################
     41# temporary directory
     42#################################################################
     43
     44def tmp_dir(name="tmp_dir-", ext=""):
     45    r"""
     46    Create and return a temporary directory in
     47    ``$HOME/.sage/temp/hostname/pid/``
     48
     49    The temporary directory is deleted automatically when Sage exits.
     50
     51    INPUT:
     52
     53    - ``name`` -- (default: "tmp_dir") A prefix for the directory name.
     54
     55    - ``ext`` -- (default: "") A suffix for the directory name.
     56
     57    OUTPUT:
     58
     59    The absolute path of the temporary directory created, with a
     60    trailing slash (or whatever the path separator is on your OS).
     61
     62    EXAMPLES::
     63       
     64        sage: d = tmp_dir('dir_testing_', '.extension')
     65        sage: d   # random output
     66        '/home/username/.sage/temp/hostname/7961/dir_testing_XgRu4p.extension/'
     67        sage: os.chdir(d)
     68        sage: _ = open('file_inside_d', 'w')
     69    """
     70    from sage.misc.misc import SAGE_TMP
     71    tmp = tempfile.mkdtemp(prefix=name, suffix=ext, dir=SAGE_TMP)
     72    name = os.path.abspath(tmp)
     73    global temporary_directories
     74    temporary_directories.append(name)
     75    return name + os.sep
     76   
     77
     78#################################################################
     79# temporary filename
     80#################################################################
     81
     82def tmp_filename(name="tmp_filename-", ext=""):
     83    r"""
     84    Create and return a temporary file in
     85    ``$HOME/.sage/temp/hostname/pid/``
     86
     87    The temporary file is deleted automatically when Sage exits.
     88
     89    .. warning::
     90
     91        If you need a particular file extension always use
     92        ``tmp_filename(ext=".foo")``, this will ensure that the file
     93        does not yet exist. If you were to use
     94        ``tmp_filename()+".foo"``, then you might overwrite an
     95        existing file!
     96
     97    INPUT:
     98
     99    - ``name`` -- (default: "tmp_filename-") A prefix for the file name.
     100
     101    - ``ext`` -- (default: "") A suffix for the file name.
     102
     103    OUTPUT:
     104
     105    The absolute path of the temporary file created.
     106
     107    EXAMPLES::
     108
     109        sage: fn = tmp_filename('just_for_testing_', '.extension')
     110        sage: fn  # random
     111        '/home/username/.sage/temp/hostname/8044/just_for_testing_tVVHsn.extension'
     112        sage: _ = open(fn, 'w')
     113    """
     114    from sage.misc.misc import SAGE_TMP
     115    handle, tmp = tempfile.mkstemp(prefix=name, suffix=ext, dir=SAGE_TMP)
     116    os.close(handle)
     117    name = os.path.abspath(tmp)
     118    global temporary_files
     119    temporary_files.append(name)
     120    return name
     121
     122def graphics_filename(ext='png'):
     123    """
     124    Return the next available canonical filename for a plot/graphics
     125    file.
     126    """
     127    i = 0
     128    while os.path.exists('sage%d.%s'%(i,ext)):
     129        i += 1
     130    filename = 'sage%d.%s'%(i,ext)
     131    return filename
  • sage/parallel/use_fork.py

    diff --git a/sage/parallel/use_fork.py b/sage/parallel/use_fork.py
    a b  
    8484        v = list(inputs)
    8585        import os, sys, signal
    8686        from sage.structure.sage_object import load
    87         from sage.misc.misc import tmp_dir, walltime
     87        from sage.misc.all import tmp_dir, walltime
    8888        dir = tmp_dir()
    8989        timeout = self.timeout
    9090        # Subprocesses shouldn't inherit unflushed buffers (cf. #11778):
  • sage/plot/animate.py

    diff --git a/sage/plot/animate.py b/sage/plot/animate.py
    a b  
    1818import os
    1919
    2020from sage.structure.sage_object import SageObject
    21 
     21from sage.misc.temporary_file import tmp_filename
    2222import plot
    2323import sage.misc.misc
    2424import sage.misc.viewer
     
    252252            return self._png_dir
    253253        except AttributeError:
    254254            pass
    255         d = sage.misc.misc.tmp_dir()
     255        d = sage.misc.temporary_file.tmp_dir()
    256256        G = self._frames
    257257        for i, frame in enumerate(self._frames):
    258258            filename = '%s/%s'%(d,sage.misc.misc.pad_zeros(i,8))
     
    331331
    332332            sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)],
    333333            ...                xmin=0, xmax=2*pi, figsize=[2,1])
    334             sage: dir = tmp_dir() + '/'
     334            sage: dir = tmp_dir()
    335335            sage: a.gif()              # not tested
    336336            sage: a.gif(savefile=dir + 'my_animation.gif', delay=35, iterations=3)  # optional -- ImageMagick
    337337            sage: a.gif(savefile=dir + 'my_animation.gif', show_path=True) # optional -- ImageMagick
     
    449449              See www.imagemagick.org and www.ffmpeg.org for more information.
    450450        """
    451451        if plot.DOCTEST_MODE:
    452             filename = sage.misc.misc.tmp_filename() + '.gif'
     452            filename = tmp_filename(ext='.gif')
    453453            self.gif(savefile=filename, delay=delay, iterations=iterations)
    454454            return
    455455       
    456456        if plot.EMBEDDED_MODE:
    457457            self.gif(delay = delay, iterations = iterations)
    458458        else:
    459             filename = sage.misc.misc.tmp_filename() + '.gif'
     459            filename = tmp_filename(ext='.gif')
    460460            self.gif(delay=delay, savefile=filename, iterations=iterations)
    461461            os.system('%s %s 2>/dev/null 1>/dev/null &'%(
    462462                sage.misc.viewer.browser(), filename))
     
    526526
    527527            sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)],
    528528            ...                xmin=0, xmax=2*pi, figsize=[2,1])
    529             sage: dir = tmp_dir() + '/'
     529            sage: dir = tmp_dir()
    530530            sage: a.ffmpeg(savefile=dir + 'new.mpg')       # optional -- ffmpeg
    531531            sage: a.ffmpeg(savefile=dir + 'new.avi')       # optional -- ffmpeg
    532532            sage: a.ffmpeg(savefile=dir + 'new.gif')       # optional -- ffmpeg
     
    620620
    621621            sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)],
    622622            ...                xmin=0, xmax=2*pi, figsize=[2,1])
    623             sage: dir = tmp_dir() + '/'
     623            sage: dir = tmp_dir()
    624624            sage: a.save()         # not tested
    625625            sage: a.save(dir + 'wave.gif')   # optional -- ImageMagick
    626626            sage: a.save(dir + 'wave.gif', show_path=True)   # optional -- ImageMagick
  • sage/plot/graphics.py

    diff --git a/sage/plot/graphics.py b/sage/plot/graphics.py
    a b  
    2828import os
    2929import sage.misc.misc
    3030from sage.misc.html import html
     31from sage.misc.temporary_file import tmp_filename, graphics_filename
    3132from sage.structure.sage_object import SageObject
    3233from sage.misc.decorators import suboptions
    3334from colors import rgbcolor
     
    17311732            kwds.pop('filename', None)
    17321733            self.save(DOCTEST_MODE_FILE, **kwds)
    17331734        elif sage.plot.plot.EMBEDDED_MODE:
    1734             kwds.setdefault('filename', sage.misc.misc.graphics_filename())
     1735            kwds.setdefault('filename', graphics_filename())
    17351736            self.save(**kwds)
    17361737            if linkmode == True:
    17371738                return "<img src='cell://%s'>" % kwds['filename']
    17381739            else:
    17391740                html("<img src='cell://%s'>" % kwds['filename'])
    17401741        else:
    1741             kwds.setdefault('filename', sage.misc.misc.tmp_filename() + '.png')
     1742            kwds.setdefault('filename', tmp_filename(ext='.png'))
    17421743            self.save(**kwds)
    17431744            os.system('%s %s 2>/dev/null 1>/dev/null &'
    17441745                      % (sage.misc.viewer.browser(), kwds['filename']))
     
    25332534        You can also pass extra options to the plot command instead of this
    25342535        method, e.g. ::
    25352536       
    2536             sage: plot(x^2 - 5, (x, 0, 5), ymin=0).save(
    2537             ...       sage.misc.misc.tmp_filename() + '.png')
     2537            sage: plot(x^2 - 5, (x, 0, 5), ymin=0).save(tmp_filename(ext='.png'))
    25382538           
    25392539        will save the same plot as the one shown by this command::
    25402540       
     
    25722572        if filename is None:
    25732573            filename = options.pop('filename')
    25742574        if filename is None:
    2575             filename = sage.misc.misc.graphics_filename()
     2575            filename = graphics_filename()
    25762576        ext = os.path.splitext(filename)[1].lower()
    25772577       
    25782578        if ext not in ALLOWED_EXTENSIONS:
     
    29212921
    29222922        EXAMPLES::
    29232923
    2924             sage: F = sage.misc.misc.tmp_filename()+'.png'
     2924            sage: F = tmp_filename(ext='.png')
    29252925            sage: L = [plot(sin(k*x),(x,-pi,pi)) for k in [1..3]]
    29262926            sage: G = graphics_array(L)
    29272927            sage: G.save(F,500,axes=False)  # long time (6s on sage.math, 2012)
     
    29662966            self.save(filename, dpi=dpi, figsize=self._figsize, axes = axes, **args)
    29672967            return
    29682968        if filename is None:
    2969             filename = sage.misc.misc.tmp_filename() + '.png'
     2969            filename = tmp_filename(ext='.png')
    29702970        self._render(filename, dpi=dpi, figsize=self._figsize, axes = axes, **args)
    29712971        os.system('%s %s 2>/dev/null 1>/dev/null &'%(
    29722972                         sage.misc.viewer.browser(), filename))
  • sage/plot/plot3d/base.pyx

    diff --git a/sage/plot/plot3d/base.pyx b/sage/plot/plot3d/base.pyx
    a b  
    4242
    4343from sage.rings.real_double import RDF
    4444from sage.misc.functional import sqrt, atan, acos
     45from sage.misc.temporary_file import tmp_filename
    4546
    4647from texture import Texture, is_Texture
    4748from transform cimport Transformation, point_c, face_c
     
    564565
    565566        EXAMPLES::
    566567
    567             sage: out_file = sage.misc.misc.tmp_filename() + ".jmol"
     568            sage: out_file = tmp_filename(ext=".jmol")
    568569            sage: G = sphere((1, 2, 3), 5) + cube() + sage.plot.plot3d.shapes.Text("hi")
    569570            sage: G.export_jmol(out_file)
    570571            sage: import zipfile
     
    10731074            filename = kwds['filename']
    10741075            del kwds['filename']
    10751076        else:
    1076             filename = sage.misc.misc.tmp_filename()
     1077            filename = tmp_filename()
    10771078
    10781079        from sage.plot.plot import EMBEDDED_MODE, DOCTEST_MODE
    10791080        ext = None
     
    10841085            filename = sage.misc.misc.SAGE_TMP + "/tmp"
    10851086        elif EMBEDDED_MODE:
    10861087            opts = '-res %s %s'%(figsize[0]*100, figsize[1]*100)
    1087             filename = sage.misc.misc.graphics_filename()[:-4]
     1088            filename = sage.misc.temporary_file.graphics_filename()[:-4]
    10881089        else:
    10891090            opts = '-res %s %s'%(figsize[0]*100, figsize[1]*100)
    10901091
     
    12221223        Since Tachyon only outputs PNG images, PIL will be used to convert to
    12231224        alternate formats::
    12241225
    1225             sage: cube().save(tmp_filename() + '.gif')
     1226            sage: cube().save(tmp_filename(ext='.gif'))
    12261227        """
    12271228        ext = os.path.splitext(filename)[1].lower()
    12281229        if ext == '' or ext == '.sobj':
     
    12401241                out_filename = filename
    12411242            else:
    12421243                # Save to a temporary file, and then convert using PIL
    1243                 out_filename = sage.misc.misc.tmp_filename()
     1244                out_filename = sage.misc.temporary_file.tmp_filename(ext=ext)
    12441245            tachyon_rt(T.tachyon(), out_filename, opts['verbosity'], True,
    12451246                '-res %s %s' % (opts['figsize'][0]*100, opts['figsize'][1]*100))
    12461247            if ext != 'png':
  • sage/plot/plot3d/tachyon.py

    diff --git a/sage/plot/plot3d/tachyon.py b/sage/plot/plot3d/tachyon.py
    a b  
    5555from sage.structure.sage_object import SageObject
    5656
    5757from sage.misc.misc import SAGE_TMP
     58from sage.misc.temporary_file import tmp_filename, graphics_filename
    5859
    5960#from sage.ext import fast_tachyon_routines
    6061
     
    312313        """
    313314        import sage.plot.plot
    314315        if sage.plot.plot.DOCTEST_MODE:
    315             filename = sage.misc.misc.graphics_filename()
     316            filename = graphics_filename()
    316317            self.save(SAGE_TMP + '/test.png', verbose=verbose, extra_opts=extra_opts)
    317318            return
    318319        if sage.plot.plot.EMBEDDED_MODE:
    319             filename = sage.misc.misc.graphics_filename()
     320            filename = graphics_filename()
    320321            self.save(filename, verbose=verbose, extra_opts=extra_opts)
    321322            return
    322         filename = sage.misc.misc.tmp_filename() + '.png'
     323        filename = tmp_filename(ext='.png')
    323324        self.save(filename, verbose=verbose, extra_opts=extra_opts)
    324325        os.system('%s %s 2>/dev/null 1>/dev/null &'%(sage.misc.viewer.browser(), filename))
    325326
  • sage/tests/cmdline.py

    diff --git a/sage/tests/cmdline.py b/sage/tests/cmdline.py
    a b  
    5151
    5252from subprocess import *
    5353import os, select
     54from sage.misc.cachefunc import cached_function
     55
     56
     57@cached_function
     58def get_tmpdir():
     59    """
     60    Return a safe temporary directory to run the executable in.
     61   
     62    EXAMPLES::
     63
     64        sage: from sage.tests.cmdline import get_tmpdir
     65        sage: get_tmpdir()   # random output
     66        '/home/username/.sage/temp/hostname/pid/sage-test-cmdline-extension'
     67        sage: get_tmpdir() == get_tmpdir()  # test caching
     68        True
     69    """
     70    from sage.misc.temporary_file import tmp_dir
     71    return tmp_dir('sage-test-cmdline-')
     72
    5473
    5574def test_executable(args, input="", timeout=50.0):
    5675    """
     
    7493
    7594    EXAMPLES::
    7695
    77         sage: from sage.tests.cmdline import test_executable
     96        sage: from sage.tests.cmdline import test_executable, get_tmpdir
    7897        sage: (out, err, ret) = test_executable(["cat"], "Hello World!")
    7998        sage: out
    8099        'Hello World!'
     
    220239
    221240    Test ``sage-run`` on a Python file, both with an absolute and with a relative path::
    222241
    223         sage: import tempfile
    224         sage: F = tempfile.NamedTemporaryFile(suffix=".py")
     242        sage: F = open(os.path.join(get_tmpdir(), 'python_test_file.py'), 'w')
    225243        sage: F.write("print 3^33\n")
    226         sage: F.flush()
     244        sage: F.close()
    227245        sage: (out, err, ret) = test_executable(["sage", F.name])
    228246        sage: print out
    229247        34
     
    240258        ''
    241259        sage: ret
    242260        0
    243         sage: del F   # Close and delete the file
    244261
    245262    The same as above, but now with a ``.sage`` file.  This indirectly
    246263    also tests the preparser::
    247 
    248         sage: import tempfile
    249         sage: F = tempfile.NamedTemporaryFile(suffix=".sage")
    250         sage: py_file = F.name[:-5] + ".py"  # Will be created by the preparser
     264   
     265        sage: sage_test_file = 'sage_test_file.sage'
     266        sage: F = open(os.path.join(get_tmpdir(), sage_test_file), 'w')
    251267        sage: F.write("k.<a> = GF(5^3); print a^124\n")
    252         sage: F.flush()
     268        sage: F.close()
    253269        sage: (out, err, ret) = test_executable(["sage", F.name])
    254         sage: os.unlink(py_file)
    255270        sage: print out
    256271        1
    257272        sage: err
    258273        ''
    259274        sage: ret
    260275        0
    261         sage: (dir,filename) = os.path.split(F.name)
    262         sage: os.chdir(dir)
    263         sage: (out, err, ret) = test_executable(["sage", filename])
    264         sage: os.unlink(py_file)
     276        sage: (out, err, ret) = test_executable(["sage", sage_test_file])
    265277        sage: print out
    266278        1
    267279        sage: err
    268280        ''
    269281        sage: ret
    270282        0
    271         sage: del F   # Close and delete the file
    272283
    273284    Testing "sage --preparse FILE" and "sage -t FILE".  First create a file and preparse it::
    274285
    275         sage: import os
    276286        sage: s = '\"\"\"\nThis is a test file.\n\"\"\"\ndef my_add(a,b):\n    \"\"\"\n    Add a to b.\n\n        EXAMPLES::\n\n            sage: my_add(2,2)\n            4\n        \"\"\"\n    return a+b\n'
    277         sage: script = os.path.join(SAGE_TMP, 'my_script.sage')
     287        sage: script = os.path.join(get_tmpdir(), 'my_script.sage')
     288        sage: script_py = script[:-5] + '.py'
    278289        sage: F = open(script, 'w')
    279290        sage: F.write(s)
    280291        sage: F.close()
    281         sage: os.chdir(SAGE_TMP)
    282292        sage: (out, err, ret) = test_executable(["sage", "--preparse", script])
    283293        sage: ret
    284294        0
    285         sage: os.path.exists(os.path.join(SAGE_TMP, 'my_script.py'))
     295        sage: os.path.exists(script_py)
    286296        True
    287297
    288298    Now test my_script.sage and the preparsed version my_script.py::
     
    292302        0
    293303        sage: out.find("All tests passed!") >= 0
    294304        True
    295         sage: (out, err, ret) = test_executable(["sage", "-t", os.path.join(SAGE_TMP, 'my_script.py')])
     305        sage: (out, err, ret) = test_executable(["sage", "-t", script_py])
    296306        sage: ret
    297307        0
    298308        sage: out.find("All tests passed!") >= 0
     
    307317        sage: F.write(s)
    308318        sage: F.close()
    309319        sage: OLD_TESTDIR = os.environ['SAGE_TESTDIR']
    310         sage: os.environ['SAGE_TESTDIR'] = SAGE_TMP
     320        sage: os.environ['SAGE_TESTDIR'] = get_tmpdir()
    311321        sage: (out, err, ret) = test_executable(["sage", "-t", script])
    312322        sage: ret
    313323        128
     
    507517        True
    508518   
    509519    """
    510     p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
     520    p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=get_tmpdir())
    511521    if input: p.stdin.write(input)
    512522    p.stdin.close()
    513523    fdout = p.stdout.fileno()