TESTS:
sage: attach('http://wstein.org/loadtest.py')
Traceback (most recent call last):
...
NotImplementedError: you can't attach a URL
Check that no file clutter is produced:
sage: dir = tmp_dir()
sage: src = os.path.join(dir, 'foobar.sage')
sage: with open(src, 'w') as f:
....: f.write('print "<output from attached file>"\n')
sage: attach(src)
<output from attached file>
sage: os.listdir(dir)
['foobar.sage']
sage: detach(src)
In debug mode backtraces contain code snippets. We need to manually print the traceback because the python doctest module has special support for exceptions and does not match them character-by-character:
sage: import traceback
sage: with open(src, 'w') as f:
....: f.write('# first line\n')
....: f.write('# second line\n')
....: f.write('raise ValueError("third") # this should appear in the source snippet\n')
....: f.write('# fourth line\n')
sage: load_attach_mode(attach_debug=False)
sage: try:
....: attach(src)
....: except Exception:
....: traceback.print_exc()
Traceback (most recent call last):
...
exec(preparse_file(open(fpath).read()) + "\n", globals)
File "<string>", line 3, in <module>
ValueError: third
sage: detach(src)
sage: load_attach_mode(attach_debug=True)
sage: try:
....: attach(src)
....: except Exception:
....: traceback.print_exc()
Traceback (most recent call last):
...
exec(code, globals)
File ".../foobar.sage....py", line ..., in <module>
raise ValueError("third") # this should appear in the source snippet
ValueError: third
sage: detach(src)
Add to the list of attached files
This is a callback to be used from load() after evaluating the attached file the first time.
INPUT:
EXAMPLES:
sage: import sage.repl.attach as af
sage: af.reset()
sage: t = tmp_filename(ext='.py')
sage: af.add_attached_file(t)
sage: af.attached_files()
['/.../tmp_....py']
sage: af.detach(t)
sage: af.attached_files()
[]
Attach a file or files to a running instance of Sage and also load that file.
USAGE:
attach file1 ... - space-separated list of .py, .pyx, and .sage files, or attach('file1', 'file2') - filenames as strings, given as arguments to attach().
load() is the same as attach(), but doesn’t automatically reload a file when it changes.
Note
On the Sage prompt you can also just type attach "foo.sage" as a short-hand for attach('foo.sage'). However this alternate form is not part of the Python language and does not work in Python scripts.
EFFECT:
Each file is read in and added to an internal list of watched files. The meaning of reading in a file depends on the file type:
.py files are read in with no preparsing (so, e.g., 2^3 is 2 bit-xor 3);
.sage files are preparsed, then the result is read in;
module m and then from m import * is executed.
The contents of the file are then loaded, which means they are read into the running Sage session. For example, if foo.sage contains x=5, after attaching foo.sage the variable x will be set to 5. Moreover, any time you change foo.sage, before you execute a command, the attached file will be re-read automatically (with no intervention on your part).
EXAMPLES:
You attach a file, e.g., foo.sage or foo.py or foo.pyx, to a running Sage session by typing:
sage: attach foo.sage # or foo.py or foo.pyx or even a URL to such a file (not tested)
or:
sage: attach('foo.sage') # not tested
Here we test attaching multiple files at once:
sage: sage.repl.attach.reset()
sage: t1 = tmp_filename(ext='.py')
sage: open(t1,'w').write("print 'hello world'")
sage: t2 = tmp_filename(ext='.py')
sage: open(t2,'w').write("print 'hi there xxx'")
sage: attach(t1, t2)
hello world
hi there xxx
sage: set(attached_files()) == set([t1,t2])
True
See also
Returns a list of all files attached to the current session with attach().
OUTPUT:
The filenames in a sorted list of strings.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: open(t,'w').write("print 'hello world'")
sage: attach(t)
hello world
sage: attached_files()
['/....py']
sage: attached_files() == [t]
True
Detach a file.
This is the counterpart to attach().
INPUT:
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: open(t,'w').write("print 'hello world'")
sage: attach(t)
hello world
sage: attached_files() == [t]
True
sage: detach(t)
sage: attached_files()
[]
sage: sage.repl.attach.reset(); reset_load_attach_path()
sage: load_attach_path()
['.']
sage: t_dir = tmp_dir()
sage: fullpath = os.path.join(t_dir, 'test.py')
sage: open(fullpath, 'w').write("print 37 * 3")
sage: load_attach_path(t_dir)
sage: attach('test.py')
111
sage: attached_files() == [os.path.normpath(fullpath)]
True
sage: detach('test.py')
sage: attached_files()
[]
sage: attach('test.py')
111
sage: fullpath = os.path.join(t_dir, 'test2.py')
sage: open(fullpath, 'w').write("print 3")
sage: attach('test2.py')
3
sage: detach(attached_files())
sage: attached_files()
[]
TESTS:
sage: detach('/dev/null/foobar.sage')
Traceback (most recent call last):
...
ValueError: file '/dev/null/foobar.sage' is not attached, see attached_files()
Get or modify the current debug mode for the behavior of load() and attach() on .sage files.
In debug mode, loaded or attached .sage files are preparsed through a file to make their tracebacks more informative. If not in debug mode, then .sage files are preparsed in memory only for performance.
At startup, debug mode is True for attaching and False for loading.
Note
This function should really be deprecated and code executed from memory should raise proper tracebacks.
INPUT:
OUTPUT:
If all input values are None, returns a tuple giving the current modes for loading and attaching.
EXAMPLES:
sage: load_attach_mode()
(False, True)
sage: load_attach_mode(attach_debug=False)
sage: load_attach_mode()
(False, False)
sage: load_attach_mode(load_debug=True)
sage: load_attach_mode()
(True, False)
sage: load_attach_mode(load_debug=False, attach_debug=True)
Get or modify the current search path for load() and attach().
INPUT:
OUTPUT:
None or a reference to the current search paths.
EXAMPLES:
First, we extend the example given in load()‘s docstring:
sage: sage.repl.attach.reset(); reset_load_attach_path()
sage: load_attach_path()
['.']
sage: t_dir = tmp_dir()
sage: fullpath = os.path.join(t_dir, 'test.py')
sage: open(fullpath, 'w').write("print 37 * 3")
sage: attach('test.py')
Traceback (most recent call last):
...
IOError: did not find file 'test.py' in load / attach search path
sage: load_attach_path(t_dir)
sage: attach('test.py')
111
sage: attached_files() == [fullpath]
True
sage: sage.repl.attach.reset(); reset_load_attach_path()
sage: load_attach_path() == ['.']
True
sage: load('test.py')
Traceback (most recent call last):
...
IOError: did not find file 'test.py' in load / attach search path
The function returns a reference to the path list:
sage: reset_load_attach_path(); load_attach_path()
['.']
sage: load_attach_path('/path/to/my/sage/scripts'); load_attach_path()
['.', '/path/to/my/sage/scripts']
sage: load_attach_path(['good', 'bad', 'ugly'], replace=True)
sage: load_attach_path()
['good', 'bad', 'ugly']
sage: p = load_attach_path(); p.pop()
'ugly'
sage: p[0] = 'weird'; load_attach_path()
['weird', 'bad']
sage: reset_load_attach_path(); load_attach_path()
['.']
Iterate over the changed files
As a side effect the stored time stamps are updated with the actual time stamps. So if you iterate over the attached files in order to reload them and you hit an error then the subsequent files are not marked as read.
Files that are in the process of being saved are excluded.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: attach(t)
sage: from sage.repl.attach import modified_file_iterator
sage: list(modified_file_iterator())
[]
sage: sleep(1) # filesystem mtime granularity
sage: open(t, 'w').write('1')
sage: list(modified_file_iterator())
[('/.../tmp_....py', time.struct_time(...))]
Reload attached files that have been modified
This is the internal implementation of the attach mechanism.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: from sage.repl.interpreter import get_test_shell
sage: shell = get_test_shell()
sage: tmp = tmp_filename(ext='.py')
sage: open(tmp, 'w').write('a = 2\n')
sage: shell.run_cell('attach({0})'.format(repr(tmp)))
sage: shell.run_cell('a')
2
sage: sleep(1) # filesystem mtime granularity
sage: open(tmp, 'w').write('a = 3\n')
Note that the doctests are never really at the command prompt where the automatic reload is triggered. So we have to do it manually:
sage: shell.run_cell('from sage.repl.attach import reload_attached_files_if_modified')
sage: shell.run_cell('reload_attached_files_if_modified()')
### reloading attached file tmp_....py modified at ... ###
sage: shell.run_cell('a')
3
sage: shell.run_cell('detach({0})'.format(repr(tmp)))
sage: shell.run_cell('attached_files()')
[]
Remove all the attached files from the list of attached files.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: open(t,'w').write("print 'hello world'")
sage: attach(t)
hello world
sage: attached_files() == [t]
True
sage: sage.repl.attach.reset()
sage: attached_files()
[]
Resets the current search path for load() and attach().
The default path is '.' plus any paths specified in the environment variable SAGE_LOAD_ATTACH_PATH.
EXAMPLES:
sage: load_attach_path()
['.']
sage: t_dir = tmp_dir()
sage: load_attach_path(t_dir)
sage: t_dir in load_attach_path()
True
sage: reset_load_attach_path(); load_attach_path()
['.']
At startup, Sage adds colon-separated paths in the environment variable SAGE_LOAD_ATTACH_PATH:
sage: reset_load_attach_path(); load_attach_path()
['.']
sage: os.environ['SAGE_LOAD_ATTACH_PATH'] = '/veni/vidi:vici:'
sage: import imp
sage: imp.reload(sage.repl.attach) # Simulate startup
<module 'sage.repl.attach' from '...'>
sage: load_attach_path()
['.', '/veni/vidi', 'vici']
sage: del os.environ['SAGE_LOAD_ATTACH_PATH']
sage: imp.reload(sage.repl.preparse) # Simulate startup
<module 'sage.repl.preparse' from '...'>
sage: reset_load_attach_path(); load_attach_path()
['.']