Ejemplo n.º 1
0
def do_prefilter_paste(line, continuation):
    """
    Alternate prefilter for input.

    INPUT:
        line -- a single line; must *not* have any newlines in it
        continuation -- whether the input line is really part
                     of the previous line, because of open parens or backslash.
    """
    if '\n' in line:
        raise RuntimeError, "bug in function that calls do_prefilter_paste -- there can be no newlines in the input"
    
    global attached

    # This is so it's OK to have lots of blank space at the
    # beginning of any non-continuation line.
    
    if continuation:
        # strip ...'s that appear in examples
        L = line.lstrip()
        if L[:3] == '...':
            line = L[3:]
    else:
        line = line.lstrip()
        
    line = line.rstrip()

    if not line.startswith('attach ') and not line.startswith('load ') and not line.startswith('%run '):
        for F in attached.keys():
            tm = attached[F]
            if os.path.exists(F) and os.path.getmtime(F) > tm:
                # Reload F.
                try:
                    if F.endswith('.py'):
                        _ip.runlines('%%run -i "%s"'%F)
                    elif F.endswith('.sage'):
                        _ip.runlines('%%run -i "%s"'%preparse_file_named(F))
                    elif F.endswith('.spyx') or F.endswith('.pyx'):
                        X = load_cython(F)
                        __IPYTHON__.push(X)
                    else:
                        line = 'load("%s")'%F
                    t = os.path.getmtime(F)                    
                    attached[F] = t
                except IOError:
                    del attached[F]
                

    # Get rid of leading sage: so that pasting of examples from the documentation
    # works.  This is like MAGMA's SetLinePrompt(false).
    for prompt in ['sage:', '>>>']:
        if not continuation:
            while True:
                strip = False
                if line[:3] == prompt:
                    line = line[3:].lstrip()
                    strip = True
                elif line[:5] == prompt:
                    line = line[5:].lstrip()
                    strip = True
                if not strip:
                    break
                else:
                    line = line.lstrip()
        
    # 'quit' alone on a line to quit.
    if line.lower() in ['quit', 'exit', 'quit;', 'exit;']:
        line = '%quit'

    #################################################################
    # An interactive load command, like iload in MAGMA.
    #################################################################
    if line[:6] == 'iload ':
        import sage.misc.log as log
        try:
            name = str(eval(line[6:]))
        except:
            name = str(line[6:].strip())
        try:
            F = open(name)
        except IOError:
            raise ImportError, 'Could not open file "%s"'%name
        
        print 'Interactively loading "%s"'%name
        n = len(__IPYTHON__.input_hist)
        for L in F.readlines():
            L = L.rstrip()
            Llstrip = L.lstrip()
            raw_input('sage: %s'%L.rstrip())
            __IPYTHON__.input_hist_raw.append(L)
            if Llstrip[:5] == 'load ' or Llstrip[:7] == 'attach ' \
                   or Llstrip[:6] == 'iload ':
                log.offset -= 1                    
                L = do_prefilter_paste(L, False)
                if len(L.strip()) > 0:
                    _ip.runlines(L)
                L = ''
            else:
                L = preparser_ipython.preparse_ipython(L, not continuation)
            __IPYTHON__.input_hist.append(L)
            __IPYTHON__.push(L)
        log.offset += 1
        return ''

        
    #################################################################
    # A "load" command, like \r file in PARI or load "file" in MAGMA
    #################################################################
    if line[:5] == 'load ':
        # The -i so the file is run with the same environment,
        # e.g., including the "from sage import *"
        try:
            name = str(eval(line[5:])).strip()
        except:
            name = str(line[5:].strip())
        if name.lower().startswith('http://'):
            name = remote_file.get_remote_file(name)
        if isinstance(name, str):
            if not os.path.exists(name):
                raise ImportError, "File '%s' not found (be sure to give .sage, .py, or .pyx extension)"%name
            elif name.endswith('.py'):
                try:
                    line = '%run -i "' + name + '"'
                except IOError, s:
                    print s
                    raise ImportError, "Error loading '%s'"%name
            elif name.endswith('.sage'):
                try:
                    line = '%run -i "' + preparse_file_named(name) + '"'
                except IOError, s:
                    print s
                    raise ImportError, "Error loading '%s'"%name
                    line = ""
            elif name.endswith('.spyx') or name.endswith('.pyx'):
                line = load_cython(name)
            else:
                line = 'load("%s")'%name
Ejemplo n.º 2
0
                attached[name] = os.path.getmtime(name)
            except IOError, OSError:
                raise ImportError, "File '%s' not found."%name
        elif name.endswith('.pyx') or name.endswith('.spyx'):
            try:
                line = load_cython(name)
                attached[name] = os.path.getmtime(name)
            except IOError, OSError:
                raise ImportError, "File '%s' not found."%name
                line = ''
        else:
            #line = 'load("%s")'%name
            raise ImportError, "Attaching of '%s' not implemented (load .py, .pyx, and .sage files)"%name
        
    if len(line) > 0:
        line = preparser_ipython.preparse_ipython(line, not continuation)
    return line

def load_cython(name):
    cur = os.path.abspath(os.curdir)
    try:
        mod, dir  = cython.cython(name, compile_message=True, use_cache=True)
    except (IOError, OSError, RuntimeError), msg:
        print "Error compiling cython file:\n%s"%msg
        return ''
    import sys
    sys.path.append(dir)
    return 'from %s import *'%mod

def handle_encoding_declaration(contents, out):
    """Find a Python encoding declaration in the first line
Ejemplo n.º 3
0
def do_prefilter_paste(line, continuation):
    """
    Alternate prefilter for input.

    INPUT:
    
    - ``line`` -- a single line; must *not* have any newlines in it
    - ``continuation`` -- whether the input line is really part
      of the previous line, because of open parens or backslash.
    """
    if '\n' in line:
        raise RuntimeError, "bug in function that calls do_prefilter_paste -- there can be no newlines in the input"

    # This is so it's OK to have lots of blank space at the
    # beginning of any non-continuation line.
    
    if continuation:
        # strip ...'s that appear in examples
        L = line.lstrip()
        if L[:3] == '...':
            line = L[3:]
    else:
        line = line.lstrip()
        
    line = line.rstrip()

    # Process attached files.
    for F in modified_attached_files():
        # We attach the files again instead of loading them,
        # to preserve tracebacks or efficiency according
        # to the settings of load_attach_mode().
        _ip.runlines(load_wrap(F, attach=True))
        
    # Get rid of leading sage: prompts so that pasting of examples
    # from the documentation works.  This is like MAGMA's
    # SetLinePrompt(false).
    for prompt in ['sage:', '>>>']:
        if not continuation:
            while True:
                strip = False
                if line[:3] == prompt:
                    line = line[3:].lstrip()
                    strip = True
                elif line[:5] == prompt:
                    line = line[5:].lstrip()
                    strip = True
                if not strip:
                    break
                else:
                    line = line.lstrip()
        
    # 'quit' alone on a line to quit.
    if line.lower() in ['quit', 'exit', 'quit;', 'exit;']:
        line = '%quit'

    # An interactive load command, like iload in MAGMA.
    if line[:6] == 'iload ':
        try:
            name = str(eval(line[6:]))
        except:
            name = str(line[6:].strip())
        try:
            F = open(name)
        except IOError:
            raise ImportError, 'Could not open file "%s"'%name
        
        print 'Interactively loading "%s"'%name
        n = len(__IPYTHON__.input_hist)
        for L in F.readlines():
            L = L.rstrip()
            Llstrip = L.lstrip()
            raw_input('sage: %s'%L.rstrip())
            __IPYTHON__.input_hist_raw.append(L)
            if Llstrip[:5] == 'load ' or Llstrip[:7] == 'attach ' \
                   or Llstrip[:6] == 'iload ':
                log.offset -= 1                    
                L = do_prefilter_paste(L, False)
                if len(L.strip()) > 0:
                    _ip.runlines(L)
                L = ''
            else:
                L = preparser_ipython.preparse_ipython(L, not continuation)
            __IPYTHON__.input_hist.append(L)
            __IPYTHON__.push(L)
        log.offset += 1
        return ''

        
    #################################################################
    # load and attach commands
    #################################################################
    for cmd in ['load', 'attach']:
        if line.lstrip().startswith(cmd+' '):
            j = line.find(cmd+' ')
            s = line[j+len(cmd)+1:].strip()
            if not s.startswith('('):
                line = ' '*j + load_wrap(s, cmd=='attach')

    if len(line) > 0:
        line = preparser_ipython.preparse_ipython(line, not continuation)

    return line
Ejemplo n.º 4
0
def do_prefilter_paste(line, continuation):
    """
    Alternate prefilter for input.

    INPUT:
        line -- a single line; must *not* have any newlines in it
        continuation -- whether the input line is really part
                     of the previous line, because of open parens or backslash.
    """
    if '\n' in line:
        raise RuntimeError, "bug in function that calls do_prefilter_paste -- there can be no newlines in the input"

    global attached

    # This is so it's OK to have lots of blank space at the
    # beginning of any non-continuation line.

    if continuation:
        # strip ...'s that appear in examples
        L = line.lstrip()
        if L[:3] == '...':
            line = L[3:]
    else:
        line = line.lstrip()

    line = line.rstrip()

    if not line.startswith('attach ') and not line.startswith(
            'load ') and not line.startswith('%run '):
        for F in attached.keys():
            tm = attached[F]
            if os.path.exists(F) and os.path.getmtime(F) > tm:
                # Reload F.
                try:
                    if F.endswith('.py'):
                        _ip.runlines('%%run -i "%s"' % F)
                    elif F.endswith('.sage'):
                        _ip.runlines('%%run -i "%s"' % preparse_file_named(F))
                    elif F.endswith('.spyx') or F.endswith('.pyx'):
                        X = load_cython(F)
                        __IPYTHON__.push(X)
                    else:
                        line = 'load("%s")' % F
                    t = os.path.getmtime(F)
                    attached[F] = t
                except IOError:
                    del attached[F]

    # Get rid of leading sage: so that pasting of examples from the documentation
    # works.  This is like MAGMA's SetLinePrompt(false).
    for prompt in ['sage:', '>>>']:
        if not continuation:
            while True:
                strip = False
                if line[:3] == prompt:
                    line = line[3:].lstrip()
                    strip = True
                elif line[:5] == prompt:
                    line = line[5:].lstrip()
                    strip = True
                if not strip:
                    break
                else:
                    line = line.lstrip()

    # 'quit' alone on a line to quit.
    if line.lower() in ['quit', 'exit', 'quit;', 'exit;']:
        line = '%quit'

    #################################################################
    # An interactive load command, like iload in MAGMA.
    #################################################################
    if line[:6] == 'iload ':
        import sage.misc.log as log
        try:
            name = str(eval(line[6:]))
        except:
            name = str(line[6:].strip())
        try:
            F = open(name)
        except IOError:
            raise ImportError, 'Could not open file "%s"' % name

        print 'Interactively loading "%s"' % name
        n = len(__IPYTHON__.input_hist)
        for L in F.readlines():
            L = L.rstrip()
            Llstrip = L.lstrip()
            raw_input('sage: %s' % L.rstrip())
            __IPYTHON__.input_hist_raw.append(L)
            if Llstrip[:5] == 'load ' or Llstrip[:7] == 'attach ' \
                   or Llstrip[:6] == 'iload ':
                log.offset -= 1
                L = do_prefilter_paste(L, False)
                if len(L.strip()) > 0:
                    _ip.runlines(L)
                L = ''
            else:
                L = preparser_ipython.preparse_ipython(L, not continuation)
            __IPYTHON__.input_hist.append(L)
            __IPYTHON__.push(L)
        log.offset += 1
        return ''

    #################################################################
    # A "load" command, like \r file in PARI or load "file" in MAGMA
    #################################################################
    if line[:5] == 'load ':
        # The -i so the file is run with the same environment,
        # e.g., including the "from sage import *"
        try:
            name = str(eval(line[5:])).strip()
        except:
            name = str(line[5:].strip())
        if name.lower().startswith('http://'):
            name = remote_file.get_remote_file(name)
        if isinstance(name, str):
            if not os.path.exists(name):
                raise ImportError, "File '%s' not found (be sure to give .sage, .py, or .pyx extension)" % name
            elif name.endswith('.py'):
                try:
                    line = '%run -i "' + name + '"'
                except IOError, s:
                    print s
                    raise ImportError, "Error loading '%s'" % name
            elif name.endswith('.sage'):
                try:
                    line = '%run -i "' + preparse_file_named(name) + '"'
                except IOError, s:
                    print s
                    raise ImportError, "Error loading '%s'" % name
                    line = ""
            elif name.endswith('.spyx') or name.endswith('.pyx'):
                line = load_cython(name)
            else:
                line = 'load("%s")' % name
Ejemplo n.º 5
0
                attached[name] = os.path.getmtime(name)
            except IOError, OSError:
                raise ImportError, "File '%s' not found." % name
        elif name.endswith('.pyx') or name.endswith('.spyx'):
            try:
                line = load_cython(name)
                attached[name] = os.path.getmtime(name)
            except IOError, OSError:
                raise ImportError, "File '%s' not found." % name
                line = ''
        else:
            #line = 'load("%s")'%name
            raise ImportError, "Attaching of '%s' not implemented (load .py, .pyx, and .sage files)" % name

    if len(line) > 0:
        line = preparser_ipython.preparse_ipython(line, not continuation)
    return line


def load_cython(name):
    cur = os.path.abspath(os.curdir)
    try:
        mod, dir = cython.cython(name, compile_message=True, use_cache=True)
    except (IOError, OSError, RuntimeError), msg:
        print "Error compiling cython file:\n%s" % msg
        return ''
    import sys
    sys.path.append(dir)
    return 'from %s import *' % mod

Ejemplo n.º 6
0
def do_prefilter_paste(line, continuation):
    """
    Alternate prefilter for input.

    INPUT:
    
        - ``line`` -- a single line; must *not* have any newlines in it
        - ``continuation`` -- whether the input line is really part
          of the previous line, because of open parens or backslash.
    """
    if '\n' in line:
        raise RuntimeError, "bug in function that calls do_prefilter_paste -- there can be no newlines in the input"

    # This is so it's OK to have lots of blank space at the
    # beginning of any non-continuation line.
    
    if continuation:
        # strip ...'s that appear in examples
        L = line.lstrip()
        if L[:3] == '...':
            line = L[3:]
    else:
        line = line.lstrip()
        
    line = line.rstrip()

    # Process attached files.
    for F in modified_attached_files():
        # We attach the files again instead of loading them,
        # to preserve tracebacks or efficiency according
        # to the settings of load_attach_mode().
        _ip.runlines(load_wrap(F, attach=True))
        
    # Get rid of leading sage: prompts so that pasting of examples
    # from the documentation works.  This is like MAGMA's
    # SetLinePrompt(false).
    for prompt in ['sage:', '>>>']:
        if not continuation:
            while True:
                strip = False
                if line[:3] == prompt:
                    line = line[3:].lstrip()
                    strip = True
                elif line[:5] == prompt:
                    line = line[5:].lstrip()
                    strip = True
                if not strip:
                    break
                else:
                    line = line.lstrip()
        
    # 'quit' alone on a line to quit.
    if line.lower() in ['quit', 'exit', 'quit;', 'exit;']:
        line = '%quit'

    # An interactive load command, like iload in MAGMA.
    if line[:6] == 'iload ':
        try:
            name = str(eval(line[6:]))
        except:
            name = str(line[6:].strip())
        try:
            F = open(name)
        except IOError:
            raise ImportError, 'Could not open file "%s"'%name
        
        print 'Interactively loading "%s"'%name
        n = len(__IPYTHON__.input_hist)
        for L in F.readlines():
            L = L.rstrip()
            Llstrip = L.lstrip()
            raw_input('sage: %s'%L.rstrip())
            __IPYTHON__.input_hist_raw.append(L)
            if Llstrip[:5] == 'load ' or Llstrip[:7] == 'attach ' \
                   or Llstrip[:6] == 'iload ':
                log.offset -= 1                    
                L = do_prefilter_paste(L, False)
                if len(L.strip()) > 0:
                    _ip.runlines(L)
                L = ''
            else:
                L = preparser_ipython.preparse_ipython(L, not continuation)
            __IPYTHON__.input_hist.append(L)
            __IPYTHON__.push(L)
        log.offset += 1
        return ''

        
    #################################################################
    # load and attach commands
    #################################################################
    for cmd in ['load', 'attach']:
        if line.lstrip().startswith(cmd+' '):
            j = line.find(cmd+' ')
            s = line[j+len(cmd)+1:].strip()
            if not s.startswith('('):
                line = ' '*j + load_wrap(s, cmd=='attach')

    if len(line) > 0:
        line = preparser_ipython.preparse_ipython(line, not continuation)

    return line