Ticket #13579: 13579_sagelib.patch

File 13579_sagelib.patch, 46.7 KB (added by jdemeyer, 9 years ago)

All Sage library patches folded

  • doc/common/builder.py

    # HG changeset patch
    # User Jeroen Demeyer <jdemeyer@cage.ugent.be>
    # Date 1349687927 -7200
    # Node ID 590fdec26c7f176ad8d71daf5c3b93620538f007
    # Parent  c95c1ffa8aff73e6055bf82919815d93bf66d1a8
    Use tempfile for tmp_dir() and tmp_filename()
    and move these to sage/misc/temporary_file.py
    
    diff --git a/doc/common/builder.py b/doc/common/builder.py
    a b  
    99    pass
    1010
    1111from sage.misc.cachefunc import cached_method
     12from sage.misc.misc import sage_makedirs as mkdir
    1213
    1314# Read options
    1415execfile(os.path.join(os.getenv('SAGE_ROOT'), 'devel', 'sage', 'doc', 'common' , 'build_options.py'))
     
    1617##########################################
    1718#          Utility Functions             #
    1819##########################################
    19 def mkdir(path):
    20     """
    21     Makes the directory at path if it doesn't exist and returns the
    22     string path.
    23 
    24     EXAMPLES::
    25 
    26         sage: import os, sys; sys.path.append(os.environ['SAGE_DOC']+'/common/'); import builder
    27         sage: d = tmp_filename(); d
    28         '/.../tmp_...'
    29         sage: os.path.exists(d)
    30         False
    31         sage: dd = builder.mkdir(d)
    32         sage: d == dd
    33         True
    34         sage: os.path.exists(d)
    35         True
    36     """
    37     if not os.path.exists(path):
    38         os.makedirs(path)
    39     return path
    40 
    4120def copytree(src, dst, symlinks=False, ignore_errors=False):
    4221    """
    4322    Recursively copy a directory tree using copy2().
     
    141120            sage: b._output_dir('html')
    142121            '.../devel/sage/doc/output/html/en/tutorial'
    143122        """
    144         return mkdir(os.path.join(SAGE_DOC, "output", type, self.lang, self.name))
     123        d = os.path.join(SAGE_DOC, "output", type, self.lang, self.name)
     124        mkdir(d)
     125        return d
    145126
    146127    def _doctrees_dir(self):
    147128        """
     
    156137            sage: b._doctrees_dir()
    157138            '.../devel/sage/doc/output/doctrees/en/tutorial'
    158139        """
    159         return mkdir(os.path.join(SAGE_DOC, "output", 'doctrees', self.lang, self.name))
     140        d = os.path.join(SAGE_DOC, "output", 'doctrees', self.lang, self.name)
     141        mkdir(d)
     142        return d
    160143
    161144    def _output_formats(self):
    162145        """
  • 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/all.py

    diff --git a/sage/all.py b/sage/all.py
    a b  
    235235
    236236    pari._unsafe_deallocate_pari_stack()
    237237   
    238     ### The following is removed -- since it would cleanup
    239     ### the tmp directory that the sage cleaner depends upon.
    240     # The following code close all open file descriptors,
    241     # so that on shared file systems the delete_tmpfiles
    242     # command below works.
    243     # AUTHOR:
    244     #    * Kate Minola (2007-05-03)
    245     #import resource             # Resource usage information.
    246     #maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    247     #if maxfd != resource.RLIM_INFINITY:
    248         # Iterate through and close all file descriptors.
    249     #    for fd in range(0, maxfd):
    250     #        try:
    251     #            os.close(fd)
    252     #        except OSError:  # ERROR, fd wasn't open to begin with (ignored)
    253     #            pass
    254     # Now delete the temp files
    255     #from sage.misc.misc import delete_tmpfiles
    256     #delete_tmpfiles()
    257 
    258238    # stop the twisted reactor
    259239    try:
    260240       from twisted.internet import reactor
  • 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  
    243243    in a writable directory owned by the user, since when attached,
    244244    Magma has to write sig and lck files.
    245245
    246     EXAMPLES:
     246    EXAMPLES::
     247
    247248        sage: sage.interfaces.magma.extcode_dir()
    248249        '...dir_.../data/'
    249250    """
    250251    global EXTCODE_DIR
    251252    if not EXTCODE_DIR:
    252253        import shutil
    253         tmp = sage.misc.misc.tmp_dir()
     254        tmp = sage.misc.temporary_file.tmp_dir()
    254255        shutil.copytree('%s/magma/'%sage.misc.misc.SAGE_EXTCODE, tmp + '/data')
    255256        EXTCODE_DIR = "%s/data/"%tmp
    256257    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/sage0.py

    diff --git a/sage/interfaces/sage0.py b/sage/interfaces/sage0.py
    a b  
    284284        EXAMPLES::
    285285       
    286286            sage: sage0._quit_string()
    287             'from sage.misc.misc import delete_tmpfiles; delete_tmpfiles()'
     287            ''
    288288        """
    289         return 'from sage.misc.misc import delete_tmpfiles; delete_tmpfiles()'
     289        return ""
    290290
    291291    def preparse(self, x):
    292292        """
  • 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/interpreter.py

    diff --git a/sage/misc/interpreter.py b/sage/misc/interpreter.py
    a b  
    380380    """
    381381    import sage.misc.misc
    382382    name = os.path.abspath(name)
    383     tmpfilename = os.path.abspath(sage.misc.misc.tmp_filename(name) + ".py")
     383    tmpfilename = sage.misc.misc.tmp_filename('preparse', ext='.py')
    384384    out = open(tmpfilename,'w')
    385385    preparse_file_named_to_stream(name, out)
    386386    out.close()
  • 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, delete_tmpfiles
     42
    4143from banner import version, banner
    4244
    4345SAGE_ROOT = os.environ["SAGE_ROOT"]
     
    136138# It is called temp instead of tmp mainly for
    137139# "historical reasons"...
    138140
    139 SAGE_TMP='%s/temp/%s/%s/'%(DOT_SAGE, HOSTNAME, os.getpid())
    140 
     141SAGE_TMP = os.path.join(DOT_SAGE, 'tmp', HOSTNAME, str(os.getpid()))
    141142sage_makedirs(SAGE_TMP)
    142143
    143 SPYX_TMP = '%s/spyx/'%SAGE_TMP
     144SPYX_TMP = os.path.join(SAGE_TMP, 'spyx/')
    144145
    145 
    146 def delete_tmpfiles():
    147     # !!!If you change this, see also SAGE_ROOT/local/bin/sage-doctest!!!
    148     import shutil
    149     try:
    150         if os.path.exists(SAGE_TMP):
    151             shutil.rmtree(SAGE_TMP)
    152     except OSError, msg:
    153         print msg
    154         pass
    155 
    156 SAGE_TMP_INTERFACE='%s/interface/'%SAGE_TMP
     146SAGE_TMP_INTERFACE = os.path.join(SAGE_TMP, 'interface/')
    157147sage_makedirs(SAGE_TMP_INTERFACE)
    158148
    159 SAGE_DB = '%s/db'%DOT_SAGE
     149SAGE_DB = os.path.join(DOT_SAGE, 'db')
    160150sage_makedirs(SAGE_DB)
    161151
    162152try:
     
    19651955set_trace = pdb.set_trace
    19661956
    19671957
    1968 #################################################################
    1969 # temporary directory
    1970 #################################################################
    1971 
    1972 def tmp_dir(name='dir'):
    1973     r"""
    1974     Create and return a temporary directory in
    1975     ``$HOME/.sage/temp/hostname/pid/``
    1976     """
    1977     name = str(name)
    1978     n = 0
    1979     while True:
    1980         tmp = "%s/%s_%s"%(SAGE_TMP, name, n)
    1981         if not os.path.exists(tmp):
    1982             break
    1983         n += 1
    1984     try:
    1985         os.makedirs(tmp)
    1986     except IOError:
    1987         # Put in local directory instead, e.g., because user doesn't
    1988         # have privileges to write in Sage's tmp directory.  That's OK.
    1989         n = 0
    1990         while True:
    1991             tmp = "/temp/tmp_%s_%s"%(name, n)
    1992             if not os.path.exists(tmp):
    1993                 break
    1994             n += 1
    1995         os.makedirs(tmp)
    1996     return os.path.abspath(tmp)
    1997    
    1998 
    1999 #################################################################
    2000 # temporary filename
    2001 #################################################################
    2002 
    2003 __tmp_n = 0
    2004 
    2005 def tmp_filename(name='tmp'):
    2006     name = list(str(name))
    2007     for i in range(len(name)):
    2008         # protect against paths with slashes, colons, etc
    2009         if not (name[i].isalpha() or name[i].isdigit()):
    2010             name[i] = '_'
    2011     name = ''.join(name)
    2012 
    2013     global __tmp_n
    2014     while True:
    2015         tmp = "%s/%s_%s"%(SAGE_TMP, name, __tmp_n)
    2016         __tmp_n += 1
    2017         if not os.path.exists(tmp):
    2018             break
    2019     return tmp
    2020 
    2021 def graphics_filename(ext='png'):
    2022     """
    2023     Return the next available canonical filename for a plot/graphics
    2024     file.
    2025     """
    2026     i = 0
    2027     while os.path.exists('sage%d.%s'%(i,ext)):
    2028         i += 1
    2029     filename = 'sage%d.%s'%(i,ext)
    2030     return filename
    2031 
    20321958
    20331959#################################################################
    20341960# 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')
     1559        sage: open(t,'w').write("print 'hello world'")
    15591560        sage: sage.misc.preparser.load(t, globals(), attach=True)
    15601561        hello world
    1561         sage: os.path.normpath(t) in sage.misc.preparser.attached
     1562        sage: t in sage.misc.preparser.attached
    15621563        True
    15631564
    15641565    You can't attach remote URLs (yet)::
     
    15931594
    15941595    Make sure that load handles filenames with spaces in the name or path::
    15951596
    1596         sage: t = tmp_filename() + ' b.sage'; open(t,'w').write("print 2")
     1597        sage: t = tmp_filename(ext=' b.sage'); open(t,'w').write("print 2")
    15971598        sage: sage.misc.preparser.load(t, globals())
    15981599        2
    15991600    """
     
    18421843    EXAMPLES::
    18431844   
    18441845        sage: sage.misc.reset.reset_attached()
    1845         sage: t=tmp_filename()+'.py';
     1846        sage: t=tmp_filename(ext='.py');
    18461847        sage: a = 0
    18471848        sage: f = open(t,'w'); f.write("a = 5"); f.close()
    18481849        sage: attach(t)
     
    18791880    EXAMPLES::
    18801881
    18811882        sage: sage.misc.reset.reset_attached()
    1882         sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
    1883         sage: t = os.path.normpath(t)
     1883        sage: t = tmp_filename(ext='.py')
     1884        sage: open(t,'w').write("print 'hello world'")
    18841885        sage: attach(t)
    18851886        hello world
    18861887        sage: attached_files() == [t]
     
    18991900    EXAMPLES::
    19001901
    19011902        sage: sage.misc.reset.reset_attached()
    1902         sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
    1903         sage: t = os.path.normpath(t)
     1903        sage: t = tmp_filename(ext='.py')
     1904        sage: open(t,'w').write("print 'hello world'")
    19041905        sage: attach(t)
    19051906        hello world
    19061907        sage: attached_files() == [t]
  • 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'")
    171         sage: t = os.path.normpath(t)
     170        sage: t = tmp_filename(ext='.py')
     171        sage: open(t,'w').write("print 'hello world'")
    172172        sage: attach(t)
    173173        hello world
    174174        sage: attached_files() == [t]
  • 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'")
    383         sage: t1, t2 = map(os.path.normpath, (t1, t2))
     381        sage: t1 = tmp_filename(ext='.py')
     382        sage: open(t1,'w').write("print 'hello world'")
     383        sage: t2 = tmp_filename(ext='.py')
     384        sage: open(t2,'w').write("print 'hi there xxx'")
    384385        sage: attach(t1, t2)
    385386        hello world
    386387        hi there xxx
    387         sage: attached_files() == [t1,t2]
     388        sage: set(attached_files()) == set([t1,t2])
    388389        True
    389        
    390    
     390
    391391    The contents of the file are then loaded, which means they are
    392392    read into the running Sage session. For example, if ``foo.sage``
    393393    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
     4AUTHORS:
     5
     6- Volker Braun, Jeroen Demeyer (2012-10-18): move these functions here
     7  from sage/misc/misc.py and make them secure, see :trac:`13579`.
     8"""
     9
     10#*****************************************************************************
     11#       Copyright (C) 2012 Volker Braun <vbraun@stp.dias.ie>
     12#       Copyright (C) 2012 Jeroen Demeyer <jdemeyer@cage.ugent.be>
     13#
     14#  Distributed under the terms of the GNU General Public License (GPL)
     15#  as published by the Free Software Foundation; either version 2 of
     16#  the License, or (at your option) any later version.
     17#                  http://www.gnu.org/licenses/
     18#*****************************************************************************
     19
     20
     21import os
     22import tempfile
     23import atexit
     24
     25def delete_tmpfiles():
     26    """
     27    Remove the directory ``SAGE_TMP``.
     28
     29    TESTS:
     30
     31    This is automatically run when Sage exits, test this by running a
     32    separate session of Sage::
     33
     34        sage: from sage.tests.cmdline import test_executable
     35        sage: child_SAGE_TMP, err, ret = test_executable(["sage", "-c", "print SAGE_TMP"])
     36        sage: err, ret
     37        ('', 0)
     38        sage: os.path.exists(child_SAGE_TMP)
     39        False
     40
     41    The parent directory should exist::
     42
     43        sage: parent_SAGE_TMP = os.path.normpath(child_SAGE_TMP + '/..')
     44        sage: os.path.isdir(parent_SAGE_TMP)
     45        True
     46    """
     47    import shutil
     48    from sage.misc.misc import SAGE_TMP
     49    shutil.rmtree(str(SAGE_TMP), ignore_errors=True)
     50
     51
     52# Run when Python shuts down
     53atexit.register(delete_tmpfiles)
     54
     55
     56#################################################################
     57# temporary directory
     58#################################################################
     59
     60def tmp_dir(name="dir_", ext=""):
     61    r"""
     62    Create and return a temporary directory in
     63    ``$HOME/.sage/temp/hostname/pid/``
     64
     65    The temporary directory is deleted automatically when Sage exits.
     66
     67    INPUT:
     68
     69    - ``name`` -- (default: ``"dir_"``) A prefix for the directory name.
     70
     71    - ``ext`` -- (default: ``""``) A suffix for the directory name.
     72
     73    OUTPUT:
     74
     75    The absolute path of the temporary directory created, with a
     76    trailing slash (or whatever the path separator is on your OS).
     77
     78    EXAMPLES::
     79       
     80        sage: d = tmp_dir('dir_testing_', '.extension')
     81        sage: d   # random output
     82        '/home/username/.sage/temp/hostname/7961/dir_testing_XgRu4p.extension/'
     83        sage: os.chdir(d)
     84        sage: _ = open('file_inside_d', 'w')
     85
     86    Temporary directories are unaccessible by other users::
     87
     88        sage: os.stat(d).st_mode & 0o077
     89        0
     90    """
     91    from sage.misc.misc import SAGE_TMP
     92    tmp = tempfile.mkdtemp(prefix=name, suffix=ext, dir=str(SAGE_TMP))
     93    name = os.path.abspath(tmp)
     94    return name + os.sep
     95   
     96
     97#################################################################
     98# temporary filename
     99#################################################################
     100
     101def tmp_filename(name="tmp_", ext=""):
     102    r"""
     103    Create and return a temporary file in
     104    ``$HOME/.sage/temp/hostname/pid/``
     105
     106    The temporary file is deleted automatically when Sage exits.
     107
     108    .. warning::
     109
     110        If you need a particular file extension always use
     111        ``tmp_filename(ext=".foo")``, this will ensure that the file
     112        does not yet exist. If you were to use
     113        ``tmp_filename()+".foo"``, then you might overwrite an
     114        existing file!
     115
     116    INPUT:
     117
     118    - ``name`` -- (default: ``"tmp_"``) A prefix for the file name.
     119
     120    - ``ext`` -- (default: ``""``) A suffix for the file name.
     121
     122    OUTPUT:
     123
     124    The absolute path of the temporary file created.
     125
     126    EXAMPLES::
     127
     128        sage: fn = tmp_filename('just_for_testing_', '.extension')
     129        sage: fn  # random
     130        '/home/username/.sage/temp/hostname/8044/just_for_testing_tVVHsn.extension'
     131        sage: _ = open(fn, 'w')
     132
     133    Temporary files are unaccessible by other users::
     134
     135        sage: os.stat(fn).st_mode & 0o077
     136        0
     137    """
     138    from sage.misc.misc import SAGE_TMP
     139    handle, tmp = tempfile.mkstemp(prefix=name, suffix=ext, dir=str(SAGE_TMP))
     140    os.close(handle)
     141    name = os.path.abspath(tmp)
     142    return name
     143
     144
     145def graphics_filename(ext='png'):
     146    """
     147    Return the next available canonical filename for a plot/graphics
     148    file.
     149    """
     150    i = 0
     151    while os.path.exists('sage%d.%s'%(i,ext)):
     152        i += 1
     153    filename = 'sage%d.%s'%(i,ext)
     154    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  
    22Animated plots
    33
    44EXAMPLES:
     5
    56We plot a circle shooting up to the right::
    67
    78    sage: a = animate([circle((i,i), 1-1/(i+1), hue=i/10) for i in srange(0,2,0.2)],
     
    1819import os
    1920
    2021from sage.structure.sage_object import SageObject
    21 
     22from sage.misc.temporary_file import tmp_filename, tmp_dir
    2223import plot
    2324import sage.misc.misc
    2425import sage.misc.viewer
     
    252253            return self._png_dir
    253254        except AttributeError:
    254255            pass
    255         d = sage.misc.misc.tmp_dir()
     256        d = tmp_dir()
    256257        G = self._frames
    257258        for i, frame in enumerate(self._frames):
    258259            filename = '%s/%s'%(d,sage.misc.misc.pad_zeros(i,8))
     
    331332
    332333            sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)],
    333334            ...                xmin=0, xmax=2*pi, figsize=[2,1])
    334             sage: dir = tmp_dir() + '/'
     335            sage: dir = tmp_dir()
    335336            sage: a.gif()              # not tested
    336337            sage: a.gif(savefile=dir + 'my_animation.gif', delay=35, iterations=3)  # optional -- ImageMagick
    337338            sage: a.gif(savefile=dir + 'my_animation.gif', show_path=True) # optional -- ImageMagick
     
    449450              See www.imagemagick.org and www.ffmpeg.org for more information.
    450451        """
    451452        if plot.DOCTEST_MODE:
    452             filename = sage.misc.misc.tmp_filename() + '.gif'
     453            filename = tmp_filename(ext='.gif')
    453454            self.gif(savefile=filename, delay=delay, iterations=iterations)
    454455            return
    455456       
    456457        if plot.EMBEDDED_MODE:
    457458            self.gif(delay = delay, iterations = iterations)
    458459        else:
    459             filename = sage.misc.misc.tmp_filename() + '.gif'
     460            filename = tmp_filename(ext='.gif')
    460461            self.gif(delay=delay, savefile=filename, iterations=iterations)
    461462            os.system('%s %s 2>/dev/null 1>/dev/null &'%(
    462463                sage.misc.viewer.browser(), filename))
     
    526527
    527528            sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)],
    528529            ...                xmin=0, xmax=2*pi, figsize=[2,1])
    529             sage: dir = tmp_dir() + '/'
     530            sage: dir = tmp_dir()
    530531            sage: a.ffmpeg(savefile=dir + 'new.mpg')       # optional -- ffmpeg
    531532            sage: a.ffmpeg(savefile=dir + 'new.avi')       # optional -- ffmpeg
    532533            sage: a.ffmpeg(savefile=dir + 'new.gif')       # optional -- ffmpeg
     
    620621
    621622            sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)],
    622623            ...                xmin=0, xmax=2*pi, figsize=[2,1])
    623             sage: dir = tmp_dir() + '/'
     624            sage: dir = tmp_dir()
    624625            sage: a.save()         # not tested
    625626            sage: a.save(dir + 'wave.gif')   # optional -- ImageMagick
    626627            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  
    5252from subprocess import *
    5353import os, select
    5454
    55 def test_executable(args, input="", timeout=50.0):
     55
     56def test_executable(args, input="", timeout=50.0, cwd=None):
    5657    """
    5758    Run the program defined by ``args`` using the string ``input`` on
    5859    the standard input.
     
    6869    - ``timeout`` -- if the program produces no output for ``timeout``
    6970      seconds, a RuntimeError is raised.
    7071
     72    - ``cwd`` -- (default: ``None``) if not None, run the program from
     73      the given directory.
     74
    7175    OUTPUT: a tuple ``(out, err, ret)`` with the standard output,
    7276    standard error and exitcode of the program run.
    7377
     
    220224
    221225    Test ``sage-run`` on a Python file, both with an absolute and with a relative path::
    222226
    223         sage: import tempfile
    224         sage: F = tempfile.NamedTemporaryFile(suffix=".py")
     227        sage: dir = tmp_dir(); name = 'python_test_file.py'
     228        sage: fullname = os.path.join(dir, name)
     229        sage: F = open(fullname, 'w')
    225230        sage: F.write("print 3^33\n")
    226         sage: F.flush()
    227         sage: (out, err, ret) = test_executable(["sage", F.name])
     231        sage: F.close()
     232        sage: (out, err, ret) = test_executable(["sage", fullname])
    228233        sage: print out
    229234        34
    230235        sage: err
    231236        ''
    232237        sage: ret
    233238        0
    234         sage: (dir,filename) = os.path.split(F.name)
    235         sage: os.chdir(dir)
    236         sage: (out, err, ret) = test_executable(["sage", filename])
     239        sage: (out, err, ret) = test_executable(["sage", name], cwd=dir)
    237240        sage: print out
    238241        34
    239242        sage: err
    240243        ''
    241244        sage: ret
    242245        0
    243         sage: del F   # Close and delete the file
    244246
    245247    The same as above, but now with a ``.sage`` file.  This indirectly
    246248    also tests the preparser::
    247249
    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
     250        sage: dir = tmp_dir(); name = 'sage_test_file.sage'
     251        sage: fullname = os.path.join(dir, name)
     252        sage: F = open(fullname, 'w')
    251253        sage: F.write("k.<a> = GF(5^3); print a^124\n")
    252         sage: F.flush()
    253         sage: (out, err, ret) = test_executable(["sage", F.name])
    254         sage: os.unlink(py_file)
     254        sage: F.close()
     255        sage: (out, err, ret) = test_executable(["sage", fullname])
    255256        sage: print out
    256257        1
    257258        sage: err
    258259        ''
    259260        sage: ret
    260261        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)
     262        sage: (out, err, ret) = test_executable(["sage", name], cwd=dir)
    265263        sage: print out
    266264        1
    267265        sage: err
    268266        ''
    269267        sage: ret
    270268        0
    271         sage: del F   # Close and delete the file
    272269
    273     Testing "sage --preparse FILE" and "sage -t FILE".  First create a file and preparse it::
     270    Testing ``sage --preparse FILE`` and ``sage -t FILE``.  First create
     271    a file and preparse it::
    274272
    275         sage: import os
    276273        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')
     274        sage: script = os.path.join(tmp_dir(), 'my_script.sage')
     275        sage: script_py = script[:-5] + '.py'
    278276        sage: F = open(script, 'w')
    279277        sage: F.write(s)
    280278        sage: F.close()
    281         sage: os.chdir(SAGE_TMP)
    282279        sage: (out, err, ret) = test_executable(["sage", "--preparse", script])
    283280        sage: ret
    284281        0
    285         sage: os.path.exists(os.path.join(SAGE_TMP, 'my_script.py'))
     282        sage: os.path.isfile(script_py)
    286283        True
    287284
    288285    Now test my_script.sage and the preparsed version my_script.py::
     
    292289        0
    293290        sage: out.find("All tests passed!") >= 0
    294291        True
    295         sage: (out, err, ret) = test_executable(["sage", "-t", os.path.join(SAGE_TMP, 'my_script.py')])
     292        sage: (out, err, ret) = test_executable(["sage", "-t", script_py])
    296293        sage: ret
    297294        0
    298295        sage: out.find("All tests passed!") >= 0
     
    307304        sage: F.write(s)
    308305        sage: F.close()
    309306        sage: OLD_TESTDIR = os.environ['SAGE_TESTDIR']
    310         sage: os.environ['SAGE_TESTDIR'] = SAGE_TMP
     307        sage: os.environ['SAGE_TESTDIR'] = tmp_dir()
    311308        sage: (out, err, ret) = test_executable(["sage", "-t", script])
    312309        sage: ret
    313310        128
     
    315312        True
    316313        sage: os.environ['SAGE_TESTDIR'] = OLD_TESTDIR  # just in case
    317314
     315    Check that Sage refuses to run doctests from a directory whose
     316    permissions are too loose.  We create a world-writable directory
     317    inside a safe temporary directory to test this::
     318
     319        sage: d = os.path.join(tmp_dir(), "test")
     320        sage: os.mkdir(d)
     321        sage: os.chmod(d, 0o777)
     322        sage: (out, err, ret) = test_executable(["sage", "-t", "nonexisting.py"], cwd=d)
     323        sage: print err
     324        Traceback (most recent call last):
     325        ...
     326        RuntimeError: refusing to run doctests...
     327        sage: (out, err, ret) = test_executable(["sage", "-tp", "1", "nonexisting.py"], cwd=d)
     328        sage: print err
     329        Traceback (most recent call last):
     330        ...
     331        RuntimeError: refusing to run doctests...
     332
    318333    Test external programs being called by Sage::
    319334   
    320335        sage: (out, err, ret) = test_executable(["sage", "--sh"], "echo Hello World\nexit 42\n")
     
    507522        True
    508523   
    509524    """
    510     p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    511     if input: p.stdin.write(input)
     525    p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd)
     526    if input:
     527        p.stdin.write(input)
    512528    p.stdin.close()
    513529    fdout = p.stdout.fileno()
    514530    fderr = p.stderr.fileno()