Ticket #378: trac_378-load_attach_path.patch

File trac_378-load_attach_path.patch, 8.4 KB (added by mpatel, 12 years ago)

First take on load / attach path. sage repo.

  • sage/misc/all.py

    # HG changeset patch
    # User Mitesh Patel <qed777@gmail.com>
    # Date 1266279236 28800
    # Node ID 608e15507f5d9552b2957a46096d076584ab1907
    # Parent  d0ed81abeefb9d6c0ac8a7d061d92710b3f642fd
    #378: Configurable load + attach path
    
    diff --git a/sage/misc/all.py b/sage/misc/all.py
    a b from mathml import mathml 
    6161
    6262from defaults import set_default_variable_name
    6363
    64 from preparser import preparse, implicit_multiplication, BackslashOperator, attached_files, detach
     64from preparser import preparse, implicit_multiplication, BackslashOperator, attached_files, detach, load_attach_path
    6565
    6666from interpreter import preparser
    6767
  • sage/misc/preparser.py

    diff --git a/sage/misc/preparser.py b/sage/misc/preparser.py
    a b def is_loadable_filename(filename): 
    13891389            return True
    13901390    return False
    13911391
     1392
     1393_load_attach_path = ['.']
     1394if 'SAGE_LOAD_ATTACH_PATH' in os.environ:
     1395    _load_attach_path.extend(os.environ['SAGE_LOAD_ATTACH_PATH'].split(':'))
     1396    if '' in _load_attach_path:
     1397        _load_attach_path.remove('')
     1398
     1399
    13921400def load(filename, globals, attach=False):
    13931401    """
    13941402    Executes a file in the scope given by ``globals``.  The
    def load(filename, globals, attach=False 
    14451453        sage: sage.misc.preparser.load('a.foo',globals())
    14461454        Traceback (most recent call last):
    14471455        ...
    1448         ValueError: argument (='a.foo') to load or attach must have extension py, sage, or pyx
     1456        ValueError: argument (='a.foo') to load or attach must have extension py, sage, pyx, spyx, or m
    14491457
    14501458    A filename given as an expression get evaluated.  This ensures
    14511459    that ``load DATA+'foo.sage'`` works in the Notebook, say::
    def load(filename, globals, attach=False 
    14641472        sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
    14651473        sage: sage.misc.preparser.load(t, globals(), attach=True)
    14661474        hello world
    1467         sage: t in sage.misc.preparser.attached
     1475        sage: os.path.normpath(t) in sage.misc.preparser.attached
    14681476        True
    14691477
    14701478    You can't attach remote URLs (yet)::
    def load(filename, globals, attach=False 
    14851493            for file in v:
    14861494                load(file, globals, attach=attach)
    14871495            return
    1488        
     1496
    14891497    filename = filename.strip()
    14901498   
    14911499    if filename.lower().startswith('http://'):
    def load(filename, globals, attach=False 
    14971505        from remote_file import get_remote_file
    14981506        filename = get_remote_file(filename, verbose=False)
    14991507
    1500     if filename.endswith('.py'):
    1501         execfile(filename, globals)
    1502     elif filename.endswith('.sage'):
    1503         exec(preparse_file(open(filename).read()), globals)
    1504     elif filename.endswith('.spyx') or filename.endswith('.pyx'):
    1505         import interpreter
    1506         exec(interpreter.load_cython(filename), globals)
    1507     elif filename.endswith('.m'):
    1508         # Assume magma for now, though maybe .m is used by maple and
    1509         # mathematica too, and we should really analyze the file
    1510         # further.
    1511         s = globals['magma'].load(filename)
    1512         i = s.find('\n'); s = s[i+1:]
    1513         print s
     1508    if not filename.endswith(('.py', '.sage', '.pyx', '.spyx', '.m')):
     1509        raise ValueError('argument (=%r) to load or attach must have extension py, sage, pyx, spyx, or m' % filename)
     1510
     1511    found_one = False
     1512    global _load_attach_path
     1513    for path in _load_attach_path:
     1514        fpath = os.path.join(path, filename)
     1515        if not os.path.exists(fpath):
     1516            continue
     1517
     1518        if fpath.endswith('.py'):
     1519            execfile(fpath, globals)
     1520            found_one = True
     1521            break
     1522        elif fpath.endswith('.sage'):
     1523            exec(preparse_file(open(fpath).read()), globals)
     1524            found_one = True
     1525            break
     1526        elif fpath.endswith('.spyx') or fpath.endswith('.pyx'):
     1527            import interpreter
     1528            exec(interpreter.load_cython(fpath), globals)
     1529            found_one = True
     1530            break
     1531        elif fpath.endswith('.m'):
     1532            # Assume magma for now, though maybe .m is used by maple and
     1533            # mathematica too, and we should really analyze the file
     1534            # further.
     1535            s = globals['magma'].load(fpath)
     1536            i = s.find('\n'); s = s[i+1:]
     1537            print s
     1538            found_one = True
     1539            break
     1540
     1541    if not found_one:
     1542        raise IOError('did not find %r in load / attach search path' % filename)
     1543
     1544    if attach and os.path.exists(fpath):
     1545        fpath = os.path.abspath(fpath)
     1546        attached[fpath] = os.path.getmtime(fpath)
     1547
     1548
     1549def load_attach_path(path=None, replace=False, reset=False):
     1550    """
     1551    Query or modify the current search path for loading and attaching
     1552    files.
     1553
     1554    INPUT:
     1555
     1556    - ``path`` - string or list of strings (default: None);
     1557
     1558    - ``replace`` - boolean (default: False); if ``path`` is not None,
     1559      whether to *replace* the search path or *append* to it.
     1560
     1561    - ``reset`` - boolean (default: False); whether to reset the
     1562      search path to ``'.'`` This overrides the other arguments.
     1563
     1564    OUTPUT:
     1565
     1566    - None or a list of the current search paths
     1567
     1568    EXAMPLES::
     1569
     1570        sage: sage.misc.reset.reset_attached()
     1571        sage: load_attach_path()
     1572        ['.']
     1573        sage: t_dir = tmp_dir()
     1574        sage: fullpath = os.path.join(t_dir, 'test.py')
     1575        sage: open(fullpath, 'w').write("print 37 * 3")
     1576        sage: attach('test.py')
     1577        Traceback (most recent call last):
     1578        ...
     1579        IOError: did not find 'test.py' in load / attach search path
     1580        sage: load_attach_path(t_dir)
     1581        sage: attach('test.py')
     1582        111
     1583        sage: attached_files() == [fullpath]
     1584        True       
     1585        sage: sage.misc.reset.reset_attached()
     1586        sage: load_attach_path(reset=True)
     1587        sage: load_attach_path() == ['.']
     1588        True
     1589        sage: load('test.py')
     1590        Traceback (most recent call last):
     1591        ...
     1592        IOError: did not find 'test.py' in load / attach search path
     1593    """
     1594    global _load_attach_path
     1595
     1596    if reset is True:
     1597        _load_attach_path = ['.']
     1598
     1599    elif path is None:
     1600        return _load_attach_path
     1601
    15141602    else:
    1515         raise ValueError, "argument (='%s') to load or attach must have extension py, sage, or pyx"%filename
     1603        if isinstance(path, basestring):
     1604            path = [path]
    15161605
    1517     if attach and os.path.exists(filename):
    1518         attached[filename] = os.path.getmtime(filename)
     1606        if replace:
     1607            _load_attach_path = path
     1608        else:
     1609            for p in path:
     1610                if p not in _load_attach_path:
     1611                    _load_attach_path.append(p)
    15191612
    15201613
    15211614import base64   
    def attached_files(): 
    15981691
    15991692        sage: sage.misc.reset.reset_attached()
    16001693        sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     1694        sage: t = os.path.normpath(t)
    16011695        sage: attach(t)
    16021696        hello world
    16031697        sage: attached_files() == [t]
    16041698        True
    1605    
    16061699    """
    16071700    return list(sorted(attached.keys()))
    16081701
    def detach(filename): 
    16181711
    16191712        sage: sage.misc.reset.reset_attached()
    16201713        sage: t=tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     1714        sage: t = os.path.normpath(t)
    16211715        sage: attach(t)
    16221716        hello world
    16231717        sage: attached_files() == [t]
    def detach(filename): 
    16261720        sage: attached_files()
    16271721        []
    16281722    """
    1629     if attached.has_key(filename):
    1630         del attached[filename]
     1723    attached.pop(filename, None)
  • sage/misc/reset.pyx

    diff --git a/sage/misc/reset.pyx b/sage/misc/reset.pyx
    a b def reset_attached(): 
    128128   
    129129        sage: sage.misc.reset.reset_attached()
    130130        sage: t = tmp_filename()+'.py'; open(t,'w').write("print 'hello world'")
     131        sage: t = os.path.normpath(t)
    131132        sage: attach(t)
    132133        hello world
    133134        sage: attached_files() == [t]
  • sage/misc/session.pyx

    diff --git a/sage/misc/session.pyx b/sage/misc/session.pyx
    a b def attach(*files): 
    380380        sage: sage.misc.reset.reset_attached()
    381381        sage: t1=tmp_filename()+'.py'; open(t1,'w').write("print 'hello world'")
    382382        sage: t2=tmp_filename()+'.py'; open(t2,'w').write("print 'hi there xxx'")
     383        sage: t1, t2 = map(os.path.normpath, (t1, t2))
    383384        sage: attach(t1, t2)
    384385        hello world
    385386        hi there xxx