Ticket #13579: 13579_sagelib.patch
File 13579_sagelib.patch, 46.7 KB (added by , 10 years ago) |
---|
-
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 9 9 pass 10 10 11 11 from sage.misc.cachefunc import cached_method 12 from sage.misc.misc import sage_makedirs as mkdir 12 13 13 14 # Read options 14 15 execfile(os.path.join(os.getenv('SAGE_ROOT'), 'devel', 'sage', 'doc', 'common' , 'build_options.py')) … … 16 17 ########################################## 17 18 # Utility Functions # 18 19 ########################################## 19 def mkdir(path):20 """21 Makes the directory at path if it doesn't exist and returns the22 string path.23 24 EXAMPLES::25 26 sage: import os, sys; sys.path.append(os.environ['SAGE_DOC']+'/common/'); import builder27 sage: d = tmp_filename(); d28 '/.../tmp_...'29 sage: os.path.exists(d)30 False31 sage: dd = builder.mkdir(d)32 sage: d == dd33 True34 sage: os.path.exists(d)35 True36 """37 if not os.path.exists(path):38 os.makedirs(path)39 return path40 41 20 def copytree(src, dst, symlinks=False, ignore_errors=False): 42 21 """ 43 22 Recursively copy a directory tree using copy2(). … … 141 120 sage: b._output_dir('html') 142 121 '.../devel/sage/doc/output/html/en/tutorial' 143 122 """ 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 145 126 146 127 def _doctrees_dir(self): 147 128 """ … … 156 137 sage: b._doctrees_dir() 157 138 '.../devel/sage/doc/output/doctrees/en/tutorial' 158 139 """ 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 160 143 161 144 def _output_formats(self): 162 145 """ -
doc/en/reference/misc.rst
diff --git a/doc/en/reference/misc.rst b/doc/en/reference/misc.rst
a b 17 17 sage/misc/function_mangling 18 18 sage/misc/exceptions 19 19 sage/misc/misc 20 sage/misc/temporary_file 20 21 sage/misc/bitset 21 22 sage/misc/constant_function 22 23 sage/misc/package -
sage/all.py
diff --git a/sage/all.py b/sage/all.py
a b 235 235 236 236 pari._unsafe_deallocate_pari_stack() 237 237 238 ### The following is removed -- since it would cleanup239 ### 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_tmpfiles242 # 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 # pass254 # Now delete the temp files255 #from sage.misc.misc import delete_tmpfiles256 #delete_tmpfiles()257 258 238 # stop the twisted reactor 259 239 try: 260 240 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 80 80 import sqlite3 as sqlite 81 81 import os 82 82 import re 83 from sage.misc. miscimport tmp_filename83 from sage.misc.all import tmp_filename 84 84 from sage.structure.sage_object import SageObject 85 85 86 86 sqlite_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 3987 3987 EXAMPLES:: 3988 3988 3989 3989 sage: from sage.ext.gen_interpreters import * 3990 sage: testdir = tmp_filename() 3991 sage: os.mkdir(testdir) 3990 sage: testdir = tmp_dir() 3992 3991 sage: rdf_interp = RDFInterpreter() 3993 3992 sage: build_interp(rdf_interp, testdir) 3994 3993 sage: open(testdir + '/interp_rdf.c').readline() … … 4016 4015 EXAMPLES:: 4017 4016 4018 4017 sage: from sage.ext.gen_interpreters import * 4019 sage: testdir = tmp_filename() 4020 sage: os.mkdir(testdir) 4018 sage: testdir = tmp_dir() 4021 4019 sage: rebuild(testdir) 4022 4020 Building interpreters for fast_callable 4023 4021 sage: rebuild(testdir) … … 4052 4050 build_interp(interp, dir) 4053 4051 4054 4052 # 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'): 4056 4054 pass 4057 4055 4058 4056 # 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 424 424 ``AAPL-minutely.csv``. One can load this information into a Stock 425 425 object like so. Note that the path must be explicit:: 426 426 427 sage: filename = tmp_filename( ) + '.csv'427 sage: filename = tmp_filename(ext='.csv') 428 428 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") 429 429 sage: finance.Stock('aapl').load_from_file(filename)[:5] 430 430 [ … … 471 471 472 472 This indirectly tests ``_load_from_csv()``:: 473 473 474 sage: filename = tmp_filename( ) + '.csv'474 sage: filename = tmp_filename(ext='.csv') 475 475 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") 476 476 sage: finance.Stock('aapl').load_from_file(filename) 477 477 [ -
sage/graphs/graph.py
diff --git a/sage/graphs/graph.py b/sage/graphs/graph.py
a b 3586 3586 EXAMPLES:: 3587 3587 3588 3588 sage: P = graphs.PetersenGraph() 3589 sage: P.write_to_eps(tmp_ dir() + 'sage.eps')3589 sage: P.write_to_eps(tmp_filename(ext='.eps')) 3590 3590 3591 3591 It is relatively simple to include this file in a LaTeX 3592 3592 document. ``\usepackagegraphics`` must appear in the -
sage/interfaces/axiom.py
diff --git a/sage/interfaces/axiom.py b/sage/interfaces/axiom.py
a b 253 253 254 254 :: 255 255 256 sage: filename = tmp_filename( )+'.input'256 sage: filename = tmp_filename(ext='.input') 257 257 sage: f = open(filename, 'w') 258 258 sage: f.write('xx := 22;\n') 259 259 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 76 76 sage: f.directory() 77 77 '/tmp/' 78 78 """ 79 from sage.misc. miscimport tmp_dir79 from sage.misc.temporary_file import tmp_dir 80 80 if self._directory is None: 81 81 # we have to put this here rather than in the __init__ 82 82 # 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 144 144 sage: from sage.interfaces.jmoldata import JmolData 145 145 sage: JData = JmolData() 146 146 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") 148 148 sage: JData.export_image(targetfile=testfile,datafile=script,image_type="PNG") # optional -- internet 149 149 sage: print os.path.exists(testfile) # optional -- internet 150 150 True -
sage/interfaces/magma.py
diff --git a/sage/interfaces/magma.py b/sage/interfaces/magma.py
a b 243 243 in a writable directory owned by the user, since when attached, 244 244 Magma has to write sig and lck files. 245 245 246 EXAMPLES: 246 EXAMPLES:: 247 247 248 sage: sage.interfaces.magma.extcode_dir() 248 249 '...dir_.../data/' 249 250 """ 250 251 global EXTCODE_DIR 251 252 if not EXTCODE_DIR: 252 253 import shutil 253 tmp = sage.misc. misc.tmp_dir()254 tmp = sage.misc.temporary_file.tmp_dir() 254 255 shutil.copytree('%s/magma/'%sage.misc.misc.SAGE_EXTCODE, tmp + '/data') 255 256 EXTCODE_DIR = "%s/data/"%tmp 256 257 return EXTCODE_DIR -
sage/interfaces/mathematica.py
diff --git a/sage/interfaces/mathematica.py b/sage/interfaces/mathematica.py
a b 368 368 from expect import (Expect, ExpectElement, ExpectFunction, 369 369 FunctionElement, AsciiArtString) 370 370 371 from sage.misc.misc import graphics_filename372 373 371 def clean_output(s): 374 372 if s is None: 375 373 return '' … … 837 835 P = self._check_valid() 838 836 if P.eval('InputForm[%s]' % self.name()).strip().startswith('Graphics['): 839 837 if filename is None: 838 from sage.misc.temporary_file import graphics_filename 840 839 filename = graphics_filename() 841 840 orig_dir = P.eval('Directory[]').strip() 842 841 P.chdir(os.path.abspath(".")) -
sage/interfaces/psage.py
diff --git a/sage/interfaces/psage.py b/sage/interfaces/psage.py
a b 54 54 raise NotImplementedError, "PSage doesn't work on remote server yet." 55 55 Sage.__init__(self, **kwds) 56 56 import sage.misc.misc 57 T = sage.misc. misc.tmp_dir('sage_smp')57 T = sage.misc.temporary_file.tmp_dir('sage_smp') 58 58 self.__tmp_dir = T 59 59 self.__tmp = '%s/lock'%T 60 60 self._unlock() -
sage/interfaces/sage0.py
diff --git a/sage/interfaces/sage0.py b/sage/interfaces/sage0.py
a b 284 284 EXAMPLES:: 285 285 286 286 sage: sage0._quit_string() 287 ' from sage.misc.misc import delete_tmpfiles; delete_tmpfiles()'287 '' 288 288 """ 289 return 'from sage.misc.misc import delete_tmpfiles; delete_tmpfiles()'289 return "" 290 290 291 291 def preparse(self, x): 292 292 """ -
sage/interfaces/tachyon.py
diff --git a/sage/interfaces/tachyon.py b/sage/interfaces/tachyon.py
a b 99 99 sage: t(tgen.str(), outfile = os.devnull) 100 100 tachyon ... 101 101 """ 102 modelfile = tmp_filename( ) + '.dat'102 modelfile = tmp_filename(ext='.dat') 103 103 open(modelfile,'w').write(model) 104 104 opts = '' 105 105 ext = outfile[-4:].lower() -
sage/matrix/matrix2.pyx
diff --git a/sage/matrix/matrix2.pyx b/sage/matrix/matrix2.pyx
a b 35 35 from sage.structure.sequence import Sequence 36 36 from sage.combinat.combinat import combinations_iterator 37 37 from sage.structure.element import is_Vector 38 from sage.misc.misc import verbose, get_verbose, graphics_filename 38 from sage.misc.misc import verbose, get_verbose 39 from sage.misc.temporary_file import graphics_filename 39 40 from sage.rings.number_field.all import is_NumberField 40 41 from sage.rings.integer_ring import ZZ, is_IntegerRing 41 42 from 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 84 84 cimport matrix_dense 85 85 from sage.rings.finite_rings.integer_mod cimport IntegerMod_int, IntegerMod_abstract 86 86 87 from sage.misc.misc import verbose, get_verbose, graphics_filename 87 from sage.misc.misc import verbose, get_verbose 88 from sage.misc.temporary_file import graphics_filename 88 89 89 90 import sage.rings.all as rings 90 91 -
sage/misc/all.py
diff --git a/sage/misc/all.py b/sage/misc/all.py
a b 4 4 version, banner, add, union, uniq, powerset, subsets, 5 5 exists, forall, is_iterator, 6 6 random_sublist, mul, walltime, generic_cmp, 7 repr_lincomb, tmp_dir, tmp_filename,7 repr_lincomb, 8 8 pad_zeros, attrcall, 9 9 DOT_SAGE, SAGE_ROOT, SAGE_URL, SAGE_DB, SAGE_TMP, 10 10 is_32_bit, is_64_bit, newton_method_sizes, compose, 11 11 self_compose, nest) 12 12 13 from temporary_file import tmp_dir, tmp_filename 14 13 15 from misc_c import prod, running_total, balanced_sum 14 16 15 17 from dev_tools import runsnake, import_statements -
sage/misc/cachefunc.pyx
diff --git a/sage/misc/cachefunc.pyx b/sage/misc/cachefunc.pyx
a b 2036 2036 sage: FC[((1,2),())] = 2 2037 2037 sage: FC[((1,),(('a',1),))] = 3 2038 2038 sage: for f in sorted(FC.file_list()): print f[len(dir):] 2039 /t-.key.sobj2040 /t-.sobj2041 /t-1_2.key.sobj2042 /t-1_2.sobj2043 /t-a-1.1.key.sobj2044 /t-a-1.1.sobj2039 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 2045 2045 """ 2046 2046 files = [] 2047 2047 prefix = self._prefix … … 2138 2138 EXAMPLES:: 2139 2139 2140 2140 sage: from sage.misc.cachefunc import FileCache 2141 sage: dir = tmp_dir() + '/'2141 sage: dir = tmp_dir() 2142 2142 sage: FC = FileCache(dir, memory_cache = False, prefix='foo') 2143 2143 sage: N = FC._filename(((1,2), (('a',1),('b',2)))) 2144 2144 sage: print N[len(dir):] … … 2166 2166 EXAMPLES:: 2167 2167 2168 2168 sage: from sage.misc.cachefunc import FileCache 2169 sage: dir = tmp_dir() + '/'2169 sage: dir = tmp_dir() 2170 2170 sage: FC = FileCache(dir, memory_cache = False, prefix='foo') 2171 2171 sage: k = ((),(('a',1),)) 2172 2172 sage: FC[k] = True … … 2185 2185 EXAMPLES:: 2186 2186 2187 2187 sage: from sage.misc.cachefunc import FileCache 2188 sage: dir = tmp_dir() + '/'2188 sage: dir = tmp_dir() 2189 2189 sage: FC1 = FileCache(dir, memory_cache = False, prefix='foo') 2190 2190 sage: FC2 = FileCache(dir, memory_cache = False, prefix='foo') 2191 2191 sage: k = ((),(('a',1),)) … … 2226 2226 EXAMPLES:: 2227 2227 2228 2228 sage: from sage.misc.cachefunc import FileCache 2229 sage: dir = tmp_dir() + '/'2229 sage: dir = tmp_dir() 2230 2230 sage: FC1 = FileCache(dir, memory_cache = False, prefix='foo') 2231 2231 sage: FC2 = FileCache(dir, memory_cache = False, prefix='foo') 2232 2232 sage: k = ((),(('a',1),)) … … 2255 2255 EXAMPLES:: 2256 2256 2257 2257 sage: from sage.misc.cachefunc import FileCache 2258 sage: dir = tmp_dir() + '/'2258 sage: dir = tmp_dir() 2259 2259 sage: FC1 = FileCache(dir, memory_cache = False, prefix='foo') 2260 2260 sage: FC2 = FileCache(dir, memory_cache = False, prefix='foo') 2261 2261 sage: k = ((),(('a',1),)) -
sage/misc/cython.py
diff --git a/sage/misc/cython.py b/sage/misc/cython.py
a b 647 647 if verbose: 648 648 print s 649 649 import sage.misc.misc 650 tmpfile = sage.misc. misc.tmp_filename() + ".spyx"650 tmpfile = sage.misc.temporary_file.tmp_filename(ext=".spyx") 651 651 open(tmpfile,'w').write(s) 652 652 653 653 import sage.server.support … … 748 748 sage: module.f(10) 749 749 100 750 750 """ 751 from sage.misc. miscimport tmp_filename752 file = tmp_filename( ) + ".pyx"751 from sage.misc.temporary_file import tmp_filename 752 file = tmp_filename(ext=".pyx") 753 753 open(file,'w').write(code) 754 754 from sage.server.support import cython_import 755 755 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 56 56 Need to create a clever caching system so code only gets 57 57 compiled once. 58 58 """ 59 tmpfile = sage.misc. misc.tmp_filename() + ".spyx"59 tmpfile = sage.misc.temporary_file.tmp_filename(ext=".spyx") 60 60 open(tmpfile,'w').write(code) 61 61 sage.server.support.cython_import_all(tmpfile, globals(), 62 62 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 1 1 import __builtin__ 2 2 import os 3 3 4 from sage.misc. miscimport tmp_filename4 from sage.misc.temporary_file import tmp_filename 5 5 6 6 count=0 7 7 … … 66 66 # if the first line has !f90 as a comment gfortran will treat it as 67 67 # fortran 90 code 68 68 if x.startswith('!f90'): 69 fname = os.path.join(tmp_filename() +'.f90')69 fname = tmp_filename(ext='.f90') 70 70 else: 71 fname = os.path.join(tmp_filename() +'.f')71 fname = tmp_filename(ext='.f') 72 72 73 73 log = tmp_filename() 74 74 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 380 380 """ 381 381 import sage.misc.misc 382 382 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') 384 384 out = open(tmpfilename,'w') 385 385 preparse_file_named_to_stream(name, out) 386 386 out.close() -
sage/misc/latex.py
diff --git a/sage/misc/latex.py b/sage/misc/latex.py
a b 54 54 import subprocess 55 55 import types 56 56 57 from miscimport tmp_dir, graphics_filename57 from sage.misc.temporary_file import tmp_dir, graphics_filename 58 58 import sage_eval 59 59 from sage.misc.sage_ostools import have_program 60 60 from 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 38 38 import operator, os, stat, socket, sys, signal, time, weakref, resource, math 39 39 import sage.misc.prandom as random 40 40 41 from sage.misc.temporary_file import tmp_dir, tmp_filename, delete_tmpfiles 42 41 43 from banner import version, banner 42 44 43 45 SAGE_ROOT = os.environ["SAGE_ROOT"] … … 136 138 # It is called temp instead of tmp mainly for 137 139 # "historical reasons"... 138 140 139 SAGE_TMP='%s/temp/%s/%s/'%(DOT_SAGE, HOSTNAME, os.getpid()) 140 141 SAGE_TMP = os.path.join(DOT_SAGE, 'tmp', HOSTNAME, str(os.getpid())) 141 142 sage_makedirs(SAGE_TMP) 142 143 143 SPYX_TMP = '%s/spyx/'%SAGE_TMP144 SPYX_TMP = os.path.join(SAGE_TMP, 'spyx/') 144 145 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 146 SAGE_TMP_INTERFACE = os.path.join(SAGE_TMP, 'interface/') 157 147 sage_makedirs(SAGE_TMP_INTERFACE) 158 148 159 SAGE_DB = '%s/db'%DOT_SAGE149 SAGE_DB = os.path.join(DOT_SAGE, 'db') 160 150 sage_makedirs(SAGE_DB) 161 151 162 152 try: … … 1965 1955 set_trace = pdb.set_trace 1966 1956 1967 1957 1968 #################################################################1969 # temporary directory1970 #################################################################1971 1972 def tmp_dir(name='dir'):1973 r"""1974 Create and return a temporary directory in1975 ``$HOME/.sage/temp/hostname/pid/``1976 """1977 name = str(name)1978 n = 01979 while True:1980 tmp = "%s/%s_%s"%(SAGE_TMP, name, n)1981 if not os.path.exists(tmp):1982 break1983 n += 11984 try:1985 os.makedirs(tmp)1986 except IOError:1987 # Put in local directory instead, e.g., because user doesn't1988 # have privileges to write in Sage's tmp directory. That's OK.1989 n = 01990 while True:1991 tmp = "/temp/tmp_%s_%s"%(name, n)1992 if not os.path.exists(tmp):1993 break1994 n += 11995 os.makedirs(tmp)1996 return os.path.abspath(tmp)1997 1998 1999 #################################################################2000 # temporary filename2001 #################################################################2002 2003 __tmp_n = 02004 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, etc2009 if not (name[i].isalpha() or name[i].isdigit()):2010 name[i] = '_'2011 name = ''.join(name)2012 2013 global __tmp_n2014 while True:2015 tmp = "%s/%s_%s"%(SAGE_TMP, name, __tmp_n)2016 __tmp_n += 12017 if not os.path.exists(tmp):2018 break2019 return tmp2020 2021 def graphics_filename(ext='png'):2022 """2023 Return the next available canonical filename for a plot/graphics2024 file.2025 """2026 i = 02027 while os.path.exists('sage%d.%s'%(i,ext)):2028 i += 12029 filename = 'sage%d.%s'%(i,ext)2030 return filename2031 2032 1958 2033 1959 ################################################################# 2034 1960 # Word wrap lines -
sage/misc/preparser.py
diff --git a/sage/misc/preparser.py b/sage/misc/preparser.py
a b 1506 1506 1507 1507 Note that .py files are *not* preparsed:: 1508 1508 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") 1510 1510 sage: sage.misc.preparser.load(t,globals()) 1511 1511 hi 0 1512 1512 sage: z … … 1514 1514 1515 1515 A .sage file *is* preparsed:: 1516 1516 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") 1518 1518 sage: sage.misc.preparser.load(t,globals()) 1519 1519 hi 2/3 1520 1520 sage: s … … 1522 1522 1523 1523 Cython files are *not* preparsed:: 1524 1524 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") 1526 1526 sage: z=0; sage.misc.preparser.load(t,globals()) 1527 1527 Compiling ....pyx... 1528 1528 hi 0 … … 1540 1540 A filename given as an expression get evaluated. This ensures 1541 1541 that ``load DATA+'foo.sage'`` works in the Notebook, say:: 1542 1542 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'") 1544 1544 sage: sage.misc.preparser.load(t, globals()) 1545 1545 hello world 1546 1546 … … 1555 1555 1556 1556 We attach a file:: 1557 1557 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'") 1559 1560 sage: sage.misc.preparser.load(t, globals(), attach=True) 1560 1561 hello world 1561 sage: os.path.normpath(t)in sage.misc.preparser.attached1562 sage: t in sage.misc.preparser.attached 1562 1563 True 1563 1564 1564 1565 You can't attach remote URLs (yet):: … … 1593 1594 1594 1595 Make sure that load handles filenames with spaces in the name or path:: 1595 1596 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") 1597 1598 sage: sage.misc.preparser.load(t, globals()) 1598 1599 2 1599 1600 """ … … 1842 1843 EXAMPLES:: 1843 1844 1844 1845 sage: sage.misc.reset.reset_attached() 1845 sage: t=tmp_filename( )+'.py';1846 sage: t=tmp_filename(ext='.py'); 1846 1847 sage: a = 0 1847 1848 sage: f = open(t,'w'); f.write("a = 5"); f.close() 1848 1849 sage: attach(t) … … 1879 1880 EXAMPLES:: 1880 1881 1881 1882 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'") 1884 1885 sage: attach(t) 1885 1886 hello world 1886 1887 sage: attached_files() == [t] … … 1899 1900 EXAMPLES:: 1900 1901 1901 1902 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'") 1904 1905 sage: attach(t) 1905 1906 hello world 1906 1907 sage: attached_files() == [t] -
sage/misc/reset.pyx
diff --git a/sage/misc/reset.pyx b/sage/misc/reset.pyx
a b 31 31 sage: x 32 32 x 33 33 34 sage: fn = os.path.normpath(tmp_filename() +'foo.py')34 sage: fn = tmp_filename(ext='foo.py') 35 35 sage: sage.misc.reset.EXCLUDE.add('fn') 36 36 sage: open(fn, 'w').write('a = 111') 37 37 sage: attach(fn) … … 167 167 EXAMPLES:: 168 168 169 169 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'") 172 172 sage: attach(t) 173 173 hello world 174 174 sage: attached_files() == [t] -
sage/misc/session.pyx
diff --git a/sage/misc/session.pyx b/sage/misc/session.pyx
a b 378 378 Here we test attaching multiple files at once:: 379 379 380 380 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'") 384 385 sage: attach(t1, t2) 385 386 hello world 386 387 hi there xxx 387 sage: attached_files() == [t1,t2]388 sage: set(attached_files()) == set([t1,t2]) 388 389 True 389 390 390 391 391 The contents of the file are then loaded, which means they are 392 392 read into the running Sage session. For example, if ``foo.sage`` 393 393 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 """ 2 Temporary file handling 3 4 AUTHORS: 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 21 import os 22 import tempfile 23 import atexit 24 25 def 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 53 atexit.register(delete_tmpfiles) 54 55 56 ################################################################# 57 # temporary directory 58 ################################################################# 59 60 def 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 101 def 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 145 def 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 84 84 v = list(inputs) 85 85 import os, sys, signal 86 86 from sage.structure.sage_object import load 87 from sage.misc. miscimport tmp_dir, walltime87 from sage.misc.all import tmp_dir, walltime 88 88 dir = tmp_dir() 89 89 timeout = self.timeout 90 90 # 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 2 2 Animated plots 3 3 4 4 EXAMPLES: 5 5 6 We plot a circle shooting up to the right:: 6 7 7 8 sage: a = animate([circle((i,i), 1-1/(i+1), hue=i/10) for i in srange(0,2,0.2)], … … 18 19 import os 19 20 20 21 from sage.structure.sage_object import SageObject 21 22 from sage.misc.temporary_file import tmp_filename, tmp_dir 22 23 import plot 23 24 import sage.misc.misc 24 25 import sage.misc.viewer … … 252 253 return self._png_dir 253 254 except AttributeError: 254 255 pass 255 d = sage.misc.misc.tmp_dir()256 d = tmp_dir() 256 257 G = self._frames 257 258 for i, frame in enumerate(self._frames): 258 259 filename = '%s/%s'%(d,sage.misc.misc.pad_zeros(i,8)) … … 331 332 332 333 sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)], 333 334 ... xmin=0, xmax=2*pi, figsize=[2,1]) 334 sage: dir = tmp_dir() + '/'335 sage: dir = tmp_dir() 335 336 sage: a.gif() # not tested 336 337 sage: a.gif(savefile=dir + 'my_animation.gif', delay=35, iterations=3) # optional -- ImageMagick 337 338 sage: a.gif(savefile=dir + 'my_animation.gif', show_path=True) # optional -- ImageMagick … … 449 450 See www.imagemagick.org and www.ffmpeg.org for more information. 450 451 """ 451 452 if plot.DOCTEST_MODE: 452 filename = sage.misc.misc.tmp_filename() + '.gif'453 filename = tmp_filename(ext='.gif') 453 454 self.gif(savefile=filename, delay=delay, iterations=iterations) 454 455 return 455 456 456 457 if plot.EMBEDDED_MODE: 457 458 self.gif(delay = delay, iterations = iterations) 458 459 else: 459 filename = sage.misc.misc.tmp_filename() + '.gif'460 filename = tmp_filename(ext='.gif') 460 461 self.gif(delay=delay, savefile=filename, iterations=iterations) 461 462 os.system('%s %s 2>/dev/null 1>/dev/null &'%( 462 463 sage.misc.viewer.browser(), filename)) … … 526 527 527 528 sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)], 528 529 ... xmin=0, xmax=2*pi, figsize=[2,1]) 529 sage: dir = tmp_dir() + '/'530 sage: dir = tmp_dir() 530 531 sage: a.ffmpeg(savefile=dir + 'new.mpg') # optional -- ffmpeg 531 532 sage: a.ffmpeg(savefile=dir + 'new.avi') # optional -- ffmpeg 532 533 sage: a.ffmpeg(savefile=dir + 'new.gif') # optional -- ffmpeg … … 620 621 621 622 sage: a = animate([sin(x + float(k)) for k in srange(0,2*pi,0.7)], 622 623 ... xmin=0, xmax=2*pi, figsize=[2,1]) 623 sage: dir = tmp_dir() + '/'624 sage: dir = tmp_dir() 624 625 sage: a.save() # not tested 625 626 sage: a.save(dir + 'wave.gif') # optional -- ImageMagick 626 627 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 28 28 import os 29 29 import sage.misc.misc 30 30 from sage.misc.html import html 31 from sage.misc.temporary_file import tmp_filename, graphics_filename 31 32 from sage.structure.sage_object import SageObject 32 33 from sage.misc.decorators import suboptions 33 34 from colors import rgbcolor … … 1731 1732 kwds.pop('filename', None) 1732 1733 self.save(DOCTEST_MODE_FILE, **kwds) 1733 1734 elif sage.plot.plot.EMBEDDED_MODE: 1734 kwds.setdefault('filename', sage.misc.misc.graphics_filename())1735 kwds.setdefault('filename', graphics_filename()) 1735 1736 self.save(**kwds) 1736 1737 if linkmode == True: 1737 1738 return "<img src='cell://%s'>" % kwds['filename'] 1738 1739 else: 1739 1740 html("<img src='cell://%s'>" % kwds['filename']) 1740 1741 else: 1741 kwds.setdefault('filename', sage.misc.misc.tmp_filename() + '.png')1742 kwds.setdefault('filename', tmp_filename(ext='.png')) 1742 1743 self.save(**kwds) 1743 1744 os.system('%s %s 2>/dev/null 1>/dev/null &' 1744 1745 % (sage.misc.viewer.browser(), kwds['filename'])) … … 2533 2534 You can also pass extra options to the plot command instead of this 2534 2535 method, e.g. :: 2535 2536 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')) 2538 2538 2539 2539 will save the same plot as the one shown by this command:: 2540 2540 … … 2572 2572 if filename is None: 2573 2573 filename = options.pop('filename') 2574 2574 if filename is None: 2575 filename = sage.misc.misc.graphics_filename()2575 filename = graphics_filename() 2576 2576 ext = os.path.splitext(filename)[1].lower() 2577 2577 2578 2578 if ext not in ALLOWED_EXTENSIONS: … … 2921 2921 2922 2922 EXAMPLES:: 2923 2923 2924 sage: F = sage.misc.misc.tmp_filename()+'.png'2924 sage: F = tmp_filename(ext='.png') 2925 2925 sage: L = [plot(sin(k*x),(x,-pi,pi)) for k in [1..3]] 2926 2926 sage: G = graphics_array(L) 2927 2927 sage: G.save(F,500,axes=False) # long time (6s on sage.math, 2012) … … 2966 2966 self.save(filename, dpi=dpi, figsize=self._figsize, axes = axes, **args) 2967 2967 return 2968 2968 if filename is None: 2969 filename = sage.misc.misc.tmp_filename() + '.png'2969 filename = tmp_filename(ext='.png') 2970 2970 self._render(filename, dpi=dpi, figsize=self._figsize, axes = axes, **args) 2971 2971 os.system('%s %s 2>/dev/null 1>/dev/null &'%( 2972 2972 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 42 42 43 43 from sage.rings.real_double import RDF 44 44 from sage.misc.functional import sqrt, atan, acos 45 from sage.misc.temporary_file import tmp_filename 45 46 46 47 from texture import Texture, is_Texture 47 48 from transform cimport Transformation, point_c, face_c … … 564 565 565 566 EXAMPLES:: 566 567 567 sage: out_file = sage.misc.misc.tmp_filename() + ".jmol"568 sage: out_file = tmp_filename(ext=".jmol") 568 569 sage: G = sphere((1, 2, 3), 5) + cube() + sage.plot.plot3d.shapes.Text("hi") 569 570 sage: G.export_jmol(out_file) 570 571 sage: import zipfile … … 1073 1074 filename = kwds['filename'] 1074 1075 del kwds['filename'] 1075 1076 else: 1076 filename = sage.misc.misc.tmp_filename()1077 filename = tmp_filename() 1077 1078 1078 1079 from sage.plot.plot import EMBEDDED_MODE, DOCTEST_MODE 1079 1080 ext = None … … 1084 1085 filename = sage.misc.misc.SAGE_TMP + "/tmp" 1085 1086 elif EMBEDDED_MODE: 1086 1087 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] 1088 1089 else: 1089 1090 opts = '-res %s %s'%(figsize[0]*100, figsize[1]*100) 1090 1091 … … 1222 1223 Since Tachyon only outputs PNG images, PIL will be used to convert to 1223 1224 alternate formats:: 1224 1225 1225 sage: cube().save(tmp_filename( ) + '.gif')1226 sage: cube().save(tmp_filename(ext='.gif')) 1226 1227 """ 1227 1228 ext = os.path.splitext(filename)[1].lower() 1228 1229 if ext == '' or ext == '.sobj': … … 1240 1241 out_filename = filename 1241 1242 else: 1242 1243 # 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) 1244 1245 tachyon_rt(T.tachyon(), out_filename, opts['verbosity'], True, 1245 1246 '-res %s %s' % (opts['figsize'][0]*100, opts['figsize'][1]*100)) 1246 1247 if ext != 'png': -
sage/plot/plot3d/tachyon.py
diff --git a/sage/plot/plot3d/tachyon.py b/sage/plot/plot3d/tachyon.py
a b 55 55 from sage.structure.sage_object import SageObject 56 56 57 57 from sage.misc.misc import SAGE_TMP 58 from sage.misc.temporary_file import tmp_filename, graphics_filename 58 59 59 60 #from sage.ext import fast_tachyon_routines 60 61 … … 312 313 """ 313 314 import sage.plot.plot 314 315 if sage.plot.plot.DOCTEST_MODE: 315 filename = sage.misc.misc.graphics_filename()316 filename = graphics_filename() 316 317 self.save(SAGE_TMP + '/test.png', verbose=verbose, extra_opts=extra_opts) 317 318 return 318 319 if sage.plot.plot.EMBEDDED_MODE: 319 filename = sage.misc.misc.graphics_filename()320 filename = graphics_filename() 320 321 self.save(filename, verbose=verbose, extra_opts=extra_opts) 321 322 return 322 filename = sage.misc.misc.tmp_filename() + '.png'323 filename = tmp_filename(ext='.png') 323 324 self.save(filename, verbose=verbose, extra_opts=extra_opts) 324 325 os.system('%s %s 2>/dev/null 1>/dev/null &'%(sage.misc.viewer.browser(), filename)) 325 326 -
sage/tests/cmdline.py
diff --git a/sage/tests/cmdline.py b/sage/tests/cmdline.py
a b 52 52 from subprocess import * 53 53 import os, select 54 54 55 def test_executable(args, input="", timeout=50.0): 55 56 def test_executable(args, input="", timeout=50.0, cwd=None): 56 57 """ 57 58 Run the program defined by ``args`` using the string ``input`` on 58 59 the standard input. … … 68 69 - ``timeout`` -- if the program produces no output for ``timeout`` 69 70 seconds, a RuntimeError is raised. 70 71 72 - ``cwd`` -- (default: ``None``) if not None, run the program from 73 the given directory. 74 71 75 OUTPUT: a tuple ``(out, err, ret)`` with the standard output, 72 76 standard error and exitcode of the program run. 73 77 … … 220 224 221 225 Test ``sage-run`` on a Python file, both with an absolute and with a relative path:: 222 226 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') 225 230 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]) 228 233 sage: print out 229 234 34 230 235 sage: err 231 236 '' 232 237 sage: ret 233 238 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) 237 240 sage: print out 238 241 34 239 242 sage: err 240 243 '' 241 244 sage: ret 242 245 0 243 sage: del F # Close and delete the file244 246 245 247 The same as above, but now with a ``.sage`` file. This indirectly 246 248 also tests the preparser:: 247 249 248 sage: import tempfile249 sage: F = tempfile.NamedTemporaryFile(suffix=".sage")250 sage: py_file = F.name[:-5] + ".py" # Will be created by the preparser250 sage: dir = tmp_dir(); name = 'sage_test_file.sage' 251 sage: fullname = os.path.join(dir, name) 252 sage: F = open(fullname, 'w') 251 253 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]) 255 256 sage: print out 256 257 1 257 258 sage: err 258 259 '' 259 260 sage: ret 260 261 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) 265 263 sage: print out 266 264 1 267 265 sage: err 268 266 '' 269 267 sage: ret 270 268 0 271 sage: del F # Close and delete the file272 269 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:: 274 272 275 sage: import os276 273 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' 278 276 sage: F = open(script, 'w') 279 277 sage: F.write(s) 280 278 sage: F.close() 281 sage: os.chdir(SAGE_TMP)282 279 sage: (out, err, ret) = test_executable(["sage", "--preparse", script]) 283 280 sage: ret 284 281 0 285 sage: os.path. exists(os.path.join(SAGE_TMP, 'my_script.py'))282 sage: os.path.isfile(script_py) 286 283 True 287 284 288 285 Now test my_script.sage and the preparsed version my_script.py:: … … 292 289 0 293 290 sage: out.find("All tests passed!") >= 0 294 291 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]) 296 293 sage: ret 297 294 0 298 295 sage: out.find("All tests passed!") >= 0 … … 307 304 sage: F.write(s) 308 305 sage: F.close() 309 306 sage: OLD_TESTDIR = os.environ['SAGE_TESTDIR'] 310 sage: os.environ['SAGE_TESTDIR'] = SAGE_TMP307 sage: os.environ['SAGE_TESTDIR'] = tmp_dir() 311 308 sage: (out, err, ret) = test_executable(["sage", "-t", script]) 312 309 sage: ret 313 310 128 … … 315 312 True 316 313 sage: os.environ['SAGE_TESTDIR'] = OLD_TESTDIR # just in case 317 314 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 318 333 Test external programs being called by Sage:: 319 334 320 335 sage: (out, err, ret) = test_executable(["sage", "--sh"], "echo Hello World\nexit 42\n") … … 507 522 True 508 523 509 524 """ 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) 512 528 p.stdin.close() 513 529 fdout = p.stdout.fileno() 514 530 fderr = p.stderr.fileno()