Example #1
0
    def _start(self):
        r"""
        Initialize the interface and start gap3.

        EXAMPLES::

            sage: gap3 = Gap3()                            #optional - gap3
            sage: gap3.is_running()
            False
            sage: gap3._start()                            #optional - gap3
            sage: gap3.is_running()                        #optional - gap3
            True

        Check that :trac:`23142` is fixed::

            sage: gap3.eval("1+1")                         #optional - gap3
            '2'
            sage: gap3.quit()                              #optional - gap3
        """
        Expect._start(self)
        # The -p command-line option to GAP3 produces the following
        # funny-looking patterns in the interface. We compile the patterns
        # now, and use them later for interpreting interface messages.
        self._compiled_full_pattern = self._expect.compile_pattern_list([
            r'@p\d+\.', '@@', '@[A-Z]', r'@[123456!"#$%&][^+]*\+', '@e', '@c',
            '@f', '@h', '@i', '@m', '@n', '@r', r'@s\d', r'@w.*\+', '@x', '@z'
        ])
        self._compiled_small_pattern = self._expect.compile_pattern_list('@J')
        self._expect.expect("@i")
Example #2
0
    def __init__(self,
                 maxread=None,
                 script_subdirectory=None,
                 server=None,
                 server_tmpdir=None,
                 logfile=None):
        """
        Create an instance of the Giac interpreter.

        EXAMPLES::

            sage: giac == loads(dumps(giac))
            True
        """
        Expect.__init__(
            self,
            name='giac',
            prompt='[0-9]*>> ',
            command="giac --sage",
            init_code=['maple_mode(0);I:=i;'
                       ],  #  coercion could be broken in maple_mode
            script_subdirectory=script_subdirectory,
            restart_on_ctrlc=False,
            server=server,
            server_tmpdir=server_tmpdir,
            verbose_start=False,
            logfile=logfile,
            eval_using_file_cutoff=1000)
Example #3
0
    def __init__(self,
                 maxread             = 100000,
                 script_subdirectory = None,
                 logfile             = None,
                 server              = None,
                 server_tmpdir       = None):
        """
        Pexpect-based interface to Julia
        """
        self._prompt = 'julia>'
        Expect.__init__(self,
                        name                = 'Julia',
                        prompt              = self._prompt,
                        command             = "julia",

                        maxread             = maxread,
                        server              = server,
                        server_tmpdir       = server_tmpdir,
                        script_subdirectory = script_subdirectory,

                        restart_on_ctrlc    = False,
                        verbose_start       = False,

                        logfile             = logfile)

        self.__seq = 0
        self.__in_seq = 1
Example #4
0
 def __init__(self, maxread=100, script_subdirectory=None, logfile=None, server=None, server_tmpdir=None):
     Expect.__init__(self,
                     name = 'mathematica',
                     prompt = 'In[[0-9]+]:=',
                     command = "math-readline",
                     maxread = maxread,
                     server = server,
                     server_tmpdir = server_tmpdir,
                     script_subdirectory = script_subdirectory,
                     verbose_start = False,
                     logfile=logfile,
                     eval_using_file_cutoff=50)
Example #5
0
    def __init__(self,
                 maxread=None,
                 script_subdirectory=None,
                 logfile=None,
                 server=None,
                 server_tmpdir=None,
                 command=None,
                 verbose_start=False):
        r"""
        TESTS:

        Test that :trac:`28075` is fixed::

            sage: repr(mathematica.eval("Print[1]; Print[2]; Print[3]"))  # optional - mathematica
            '1\n2\n3'
        """
        # We use -rawterm to get a raw text interface in Mathematica 9 or later.
        # This works around the following issues of Mathematica 9 or later
        # (tested with Mathematica 11.0.1 for Mac OS X x86 (64-bit))
        #
        # 1) If TERM is unset and input is a pseudoterminal, Mathematica shows no
        # prompts, so pexpect will not work.
        #
        # 2) If TERM is set (to dumb, lpr, vt100, or xterm), there will be
        # prompts; but there is bizarre echoing behavior by Mathematica (not
        # the terminal driver).  For example, with TERM=dumb, many spaces and
        # \r's are echoed.  With TERM=vt100 or better, in addition, many escape
        # sequences are printed.
        #
        if command is None:
            command = os.getenv('SAGE_MATHEMATICA_COMMAND') or 'math -rawterm'
        eval_using_file_cutoff = 1024
        # Removing terminal echo using "stty -echo" is not essential but it slightly
        # improves performance (system time) and eliminates races of the terminal echo
        # as a possible source of error.
        if server:
            command = 'stty -echo; {}'.format(command)
        else:
            command = 'sh -c "stty -echo; {}"'.format(command)
        Expect.__init__(self,
                        name='mathematica',
                        terminal_echo=False,
                        command=command,
                        prompt=r'In\[[0-9]+\]:= ',
                        server=server,
                        server_tmpdir=server_tmpdir,
                        script_subdirectory=script_subdirectory,
                        verbose_start=verbose_start,
                        logfile=logfile,
                        eval_using_file_cutoff=eval_using_file_cutoff)
Example #6
0
    def __init__(self,
                 maxread=10000,
                 script_subdirectory=None,
                 logfile=None,
                 server=None,
                 server_tmpdir=None):
        """
        Initialize a Macaulay2 interface instance.

        We replace the standard input prompt with a strange one, so that
        we do not catch input prompts inside the documentation.

        We replace the standard input continuation prompt, which is
        just a bunch of spaces and cannot be automatically detected in a
        reliable way. This is necessary for allowing commands that occupy
        several strings.

        We also change the starting line number to make all the output
        labels to be of the same length. This allows correct stripping of
        the output of several commands.

        TESTS::

            sage: macaulay2 == loads(dumps(macaulay2))
            True
        """
        init_str = (
            # Prompt changing commands
            """ZZ#{Standard,Core#"private dictionary"#"InputPrompt"} = lineno -> "%s";"""
            % PROMPT +
            """ZZ#{Standard,Core#"private dictionary"#"InputContinuationPrompt"} = lineno -> "%s";"""
            % PROMPT +
            # Also prevent line wrapping in Macaulay2
            "printWidth = 0;" +
            # And make all output labels to be of the same width
            "lineNumber = 10^9;")
        Expect.__init__(
            self,
            name='macaulay2',
            prompt=PROMPT,
            command="M2 --no-debug --no-readline --silent -e '%s'" % init_str,
            maxread=maxread,
            server=server,
            server_tmpdir=server_tmpdir,
            script_subdirectory=script_subdirectory,
            verbose_start=False,
            logfile=logfile,
            eval_using_file_cutoff=500)
Example #7
0
    def eval(self, code, strip=True, **kwds):
        r"""
        Send the code x to the Giac interpreter.
        Remark: To enable multi-lines codes in the notebook magic mode: ``%giac``,
        the ``\n`` are removed before sending the code to giac.

        INPUT:

        - code -- str
        - strip -- Default is True and removes ``\n``

        EXAMPLES::

            sage: giac.eval("2+2;\n3")
            '4,3'
            sage: giac.eval("2+2;\n3",False)
            '4\n3'
            sage: s='g(x):={\nx+1;\nx+2;\n}'
            sage: giac(s)
            ...x+1...x+2...
            sage: giac.g(5)
            7
        """
        #we remove \n to enable multiline code in the notebook magic mode %giac
        if strip:
             code = code.replace("\n","").strip()
        ans = Expect.eval(self, code, strip=strip, **kwds).strip()
        return ans
Example #8
0
    def eval(self, code, strip=True, **kwds):
        """
        Send the code x to the Giac interpreter.
        Remark: To enable multi-lines codes in the notebook magic mode: %giac,
        the \\n are removed before sending the code to giac.

        INPUT:
            code -- str
            strip -- Default is True and removes \n

        EXAMPLES:
            sage: giac.eval("2+2;\n3") #optional - giac
            '4,3'
            sage: giac.eval("2+2;\n3",False) # optional - giac
            '4\n3'
            sage: s='g(x):={\nx+1;\nx+2;\n}'
            sage: giac(s)                    # optional - giac
            (x)->{
            x+1;
            x+2;
            }
            sage: giac.g(5)                   # optional - giac
            7
        """
        #we remove \n to enable multiline code in the notebook magic mode %giac
        if strip:
             code = code.replace("\n","").strip()
        ans = Expect.eval(self, code, strip=strip, **kwds).strip()
        return ans
Example #9
0
    def _eval_line(self,
                   line,
                   allow_use_file=True,
                   wait_for_prompt=True,
                   restart_if_needed=False):
        """
        EXAMPLES::

            sage: giac._eval_line('2+2')
            '4'

            sage: A = matrix([range(280)])
            sage: GA = giac(A)

        TESTS::

            sage: h1 = 'int(sin(x)^2, x)'
            sage: h2 = 'int(cos(x)^2, x)'
            sage: giac_result = giac(h1) + giac(h2)
            sage: bool(giac_result.sage() == x)
            True

        """
        with gc_disabled():
            z = Expect._eval_line(self,
                                  line,
                                  allow_use_file=allow_use_file,
                                  wait_for_prompt=wait_for_prompt)
            if z.lower().find("error") != -1:
                raise RuntimeError(
                    "An error occurred running a Giac command:\nINPUT:\n%s\nOUTPUT:\n%s"
                    % (line, z))
        lines = (line for line in z.splitlines()
                 if not line.startswith('Evaluation time:'))
        return "\n".join(lines)
Example #10
0
    def _eval_line(self, line, reformat=True, allow_use_file=False,
                   wait_for_prompt=True, restart_if_needed=False):
        """
        EXAMPLES::

            sage: print octave._eval_line('2+2')  #optional - octave
              ans =  4
        """
        if not wait_for_prompt:
            return Expect._eval_line(self, line)
        if line == '':
            return ''
        if self._expect is None:
            self._start()
        if allow_use_file and len(line)>3000:
            return self._eval_line_using_file(line)
        try:
            E = self._expect
            verbose("in = '%s'"%line,level=3)
            E.sendline(line)
            E.expect(self._prompt)
            out = E.before
            verbose("out = '%s'"%out,level=3)
        except EOF:
            if self._quit_string() in line:
                return ''
        except KeyboardInterrupt:
            self._keyboard_interrupt()
        if reformat:
            if '>>> ' in out and 'syntax error' in out:
                raise SyntaxError(out)
        out = "\n".join(out.splitlines()[1:])
        return out
Example #11
0
 def eval(self, code, strip=True, **kwds):
     #        print "Evaluating %s"%code
     code = code.replace("\n", " ")
     result = Expect.eval(self, code, strip=strip, **kwds)
     if result.find("Exception") != -1:
         raise ValueError, "An Exception occured: %s" % result
     else:
         return result
Example #12
0
    def __init__(self, command=gap3_cmd):
        r"""
        Initialize the GAP3 interface and start a session.

        INPUT:

        -  command - string (default "gap3"); points to the gap3
           executable on your system; by default, it is assumed the
           executable is in your path.

        EXAMPLES::

            sage: gap3 = Gap3()                            #optional - gap3
            sage: gap3.is_running()
            False
            sage: gap3._start()                            #optional - gap3
            sage: gap3.is_running()                        #optional - gap3
            True
        """
        self.__gap3_command_string = command
        # Explanation of additional command-line options passed to gap3:
        #
        #     -p invokes the internal programmatic interace, which is how Sage
        #     talks to GAP4. This allows reuse some of the GAP4 interface code.
        #
        #     -y -- sets the number of lines of the terminal; controls how many
        #     lines of text are output by GAP3 before the pager is invoked.
        #     This option is useful in dealing with the GAP3 help system.
        Expect.__init__(self,
                        name='gap3',
                        prompt='gap> ',
                        command=self.__gap3_command_string + " -p -y 500",
                        server=None,
                        ulimit=None,
                        maxread=100000,
                        script_subdirectory=None,
                        restart_on_ctrlc=True,
                        verbose_start=False,
                        init_code=[],
                        max_startup_time=None,
                        logfile=None,
                        eval_using_file_cutoff=100,
                        do_cleaner=True,
                        remote_cleaner=False,
                        path=None)
Example #13
0
    def _start(self):
        """
        Starts the Octave process.

        EXAMPLES::

            sage: o = Octave()    # optional - octave
            sage: o.is_running()  # optional - octave
            False
            sage: o._start()      # optional - octave
            sage: o.is_running()  # optional - octave
            True
        """
        Expect._start(self)
        self.eval("page_screen_output=0;")
        self.eval("format none;")
        # set random seed
        self.set_seed(self._seed)
Example #14
0
 def _eval_line(self,
                line,
                allow_use_file=True,
                wait_for_prompt=True,
                restart_if_needed=False):
     s = Expect._eval_line(self,
                           line,
                           allow_use_file=allow_use_file,
                           wait_for_prompt=wait_for_prompt)
     return str(s).strip('\n')
Example #15
0
 def __init__(self,
              maxread=100000,
              script_subdirectory=None,
              logfile=None,
              server=None,
              server_tmpdir=None):
     Expect.__init__(
         self,
         name='conexp-clj',
         prompt='user=> ',  # fix this!
         command='conexp-clj.sh',
         maxread=maxread,
         server=server,
         server_tmpdir=server_tmpdir,
         script_subdirectory=script_subdirectory,
         restart_on_ctrlc=True,
         verbose_start=False,
         logfile=logfile,
         eval_using_file_cutoff=1024)
Example #16
0
    def _start(self):
        r"""
        EXAMPLES::

            sage: gap3 = Gap3()                            #optional - gap3
            sage: gap3.is_running()
            False
            sage: gap3._start()                            #optional - gap3
            sage: gap3.is_running()                        #optional - gap3
            True
            sage: gap3.quit()                              #optional - gap3
        """
        n = self._session_number
        Expect._start(self)
        # The -p command-line option to GAP3 produces the following
        # funny-looking patterns in the interface. We compile the patterns
        # now, and use them later for interpreting interface messages.
        self._compiled_full_pattern = self._expect.compile_pattern_list([
            '@p\d+\.','@@','@[A-Z]','@[123456!"#$%&][^+]*\+', '@e','@c',
            '@f','@h','@i','@m','@n','@r','@s\d','@w.*\+','@x','@z'])
        self._compiled_small_pattern = self._expect.compile_pattern_list('@J')
Example #17
0
    def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True):
        """
        EXAMPLES::

            sage: giac._eval_line('2+2')  # optional - giac
            '4'
        """
        with gc_disabled():
            z = Expect._eval_line(self, line, allow_use_file=allow_use_file,
                    wait_for_prompt=wait_for_prompt)
            if z.lower().find("error") != -1:
                raise RuntimeError, "An error occurred running a Giac command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z)
        return z
Example #18
0
    def set(self, var, value):
        """
        Set the variable var to the given value.

        EXAMPLES::

            sage: macaulay2.set("a", "2")  # optional - macaulay2
            sage: macaulay2.get("a")       # optional - macaulay2
            2
        """
        cmd = '%s=%s;'%(var,value)
        ans = Expect.eval(self, cmd)
        if ans.find("stdio:") != -1:
            raise RuntimeError("Error evaluating Macaulay2 code.\nIN:%s\nOUT:%s"%(cmd, ans))
Example #19
0
    def __init__(self, maxread=100, script_subdirectory=None, logfile=None, server=None, server_tmpdir=None,
                 seed=None):
        """
        EXAMPLES::

            sage: octave == loads(dumps(octave))
            True
        """
        Expect.__init__(self,
                        name = 'octave',
                        # We want the prompt sequence to be unique to avoid confusion with syntax error messages containing >>>
                        prompt = 'octave\:\d+> ',
                        # We don't want any pagination of output
                        command = "sage-native-execute octave --no-line-editing --silent --eval 'PS2(PS1());more off' --persist",
                        maxread = maxread,
                        server = server,
                        server_tmpdir = server_tmpdir,
                        script_subdirectory = script_subdirectory,
                        restart_on_ctrlc = False,
                        verbose_start = False,
                        logfile = logfile,
                        eval_using_file_cutoff=100)
        self._seed = seed
Example #20
0
File: giac.py Project: yjjcc/sage
    def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=False):
        """
        EXAMPLES::

            sage: giac._eval_line('2+2')
            '4'

            sage: A=matrix([range(280)])
            sage: GA=giac(A)
        """
        with gc_disabled():
            z = Expect._eval_line(self, line, allow_use_file=allow_use_file,
                    wait_for_prompt=wait_for_prompt)
            if z.lower().find("error") != -1:
                raise RuntimeError("An error occurred running a Giac command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z))
        return z
Example #21
0
    def eval(self, code, strip=True, **kwds):
        """
        Send the code x to the Macaulay2 interpreter and return the output
        as a string suitable for input back into Macaulay2, if possible.

        INPUT:

        - code -- str
        - strip -- ignored

        EXAMPLES::

            sage: macaulay2.eval("2+2") # optional - macaulay2
            4
        """
        code = code.strip()
        # TODO: in some cases change toExternalString to toString??
        ans = Expect.eval(self, code, strip=strip, **kwds).strip('\n')
        if strip:
            ans = remove_output_labels(ans)
        return AsciiArtString(ans)
Example #22
0
    def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=False):
        """
        EXAMPLES::

            sage: giac._eval_line('2+2')
            '4'

            sage: A = matrix([range(280)])
            sage: GA = giac(A)

        TESTS::

            sage: h='int(1/x*((-2*x^(1/3)+1)^(1/4))^3,x)'
            sage: giac(h)
            12*(...)
        """
        with gc_disabled():
            z = Expect._eval_line(self, line, allow_use_file=allow_use_file,
                    wait_for_prompt=wait_for_prompt)
            if z.lower().find("error") != -1:
                raise RuntimeError("An error occurred running a Giac command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z))
        lines = (line for line in z.splitlines()
                 if not line.startswith('Evaluation time:'))
        return "\n".join(lines)
Example #23
0
 def eval(self, code, strip=True, **kwds):
     s = Expect.eval(self, code, **kwds)
     if strip:
         return AsciiArtString(clean_output(s))
     else:
         return AsciiArtString(s)
Example #24
0
 def _start(self, *args, **kwds):
     Expect._start(self, *args, **kwds)