Common Interface Functionality

See the examples in the other sections for how to use specific interfaces. The interface classes all derive from the generic interface that is described in this section.

AUTHORS:

  • William Stein (2005): initial version
  • William Stein (2006-03-01): got rid of infinite loop on startup if client system missing
class sage.interfaces.expect.AsciiArtString
__repr__()
class sage.interfaces.expect.Expect(name, prompt, command=None, server=None, server_tmpdir=None, ulimit=None, maxread=100000, script_subdirectory='', restart_on_ctrlc=False, verbose_start=False, init_code=[], max_startup_time=30, logfile=None, eval_using_file_cutoff=0, do_cleaner=True, remote_cleaner=False, path=None)

Expect interface object.

__call__(x, name=None)

Create a new object in self from x.

The object X returned can be used like any Sage object, and wraps an object in self. The standard arithmetic operators work. Moreover if foo is a function then

X.foo(y,z,...)

calls foo(X, y, z, ...) and returns the corresponding object.

EXAMPLES:

sage: gp(2)
2
sage: gp('2')
2
sage: a = gp(2); gp(a) is a
True
__cmp__(other)

Compare two pseudo-tty interfaces. Two interfaces compare equal if and only if they are identical objects (this is a critical constraint so that caching of representations of objects in interfaces works correctly). Otherwise they are never equal.

EXAMPLES:

sage: Maxima() == maxima
False
sage: maxima == maxima
True
__del__()
__getattr__(attrname)
__init__(name, prompt, command=None, server=None, server_tmpdir=None, ulimit=None, maxread=100000, script_subdirectory='', restart_on_ctrlc=False, verbose_start=False, init_code=[], max_startup_time=30, logfile=None, eval_using_file_cutoff=0, do_cleaner=True, remote_cleaner=False, path=None)
_assign_symbol()
_before()

Return the previous string that was send through the interface.

EXAMPLES:

sage: singular(2+3)
5
sage: singular._before() 
'print(sage...);\r\n5\r'
_change_prompt(prompt)
_check_valid_function_name(function)

Checks to see if function is a valid function name in this interface. If it is not, an exception is raised. Otherwise, nothing is done.

EXAMPLES:

sage: gap._check_valid_function_name('SymmetricGroup')
sage: gap._check_valid_function_name('')
...
ValueError: function name must be nonempty
sage: gap._check_valid_function_name('__foo')
...
AttributeError
_coerce_from_special_method(x)

Tries to coerce to self by calling a special underscore method.

If no such method is defined, raises an AttributeError instead of a TypeError.

_coerce_impl(x, use_special=True)
_contains(v1, v2)
_convert_args_kwds(args=None, kwds=None)

Converts all of the args and kwds to be elements of this interface.

EXAMPLES:

sage: args = [5]
sage: kwds = {'x': 6}
sage: args, kwds = gap._convert_args_kwds(args, kwds)
sage: args
[5]
sage: map(type, args)
[<class 'sage.interfaces.gap.GapElement'>]
sage: type(kwds['x'])
<class 'sage.interfaces.gap.GapElement'>
_crash_msg()

Show a message if the interface crashed.

EXAMPLE:

sage: singular._crash_msg()
Singular crashed -- automatically restarting.
sage: singular('2+3')
5
sage: import os
sage: singular._sendstr('quit;\n')   # make it so that singular appears to die.
sage: singular('2+3')
Singular crashed -- automatically restarting.
5
_create(value, name=None)
_do_cleaner()
_equality_symbol()
_eval_line(line, allow_use_file=True, wait_for_prompt=True)
_eval_line_using_file(line)
_expect_expr(expr=None, timeout=None)

Wait for a given expression expr (which could be a regular expression or list of regular expressions) to appear in the output for at most timeout seconds.

Use r._expect.before to see what was put in the output stream before the expression.

INPUT:

  • expr - None or a string or list of strings (default: None)
  • timeout - None or a number (default: None)

EXAMPLES: We test all of this using the R interface. First we put 10 + 15 in the input stream:

sage: r._sendstr('abc <- 10 +15;\n')

Here an exception is raised because 25 hasn’t appeared yet in the output stream. The key thing is that this doesn’t lock, but instead quickly raises an exception.

sage: t = walltime()
sage: try: r._expect_expr('25', timeout=0.5)
... except: print 'Did not get expression'
Did not get expression

A quick consistency check on the time that the above took:

sage: w = walltime(t); w > 0.4 and w < 10
True

We tell R to print abc, which equals 25.

sage: r._sendstr('abc;\n')

Now 25 is in the output stream, so we can wait for it.

sage: r._expect_expr('25')

This gives us everything before the 25.

sage: r._expect.before
'abc;\r\n[1] '

Here is a doc test related with trac ticket #6661:

sage: print sage0.eval("alarm(1); singular._expect_expr('1')")
Control-C pressed.  Interrupting Singular. Please wait a few seconds...
...
KeyboardInterrupt: computation timed out because alarm was set for 1 seconds
_false_symbol()
_function_call_string(function, args, kwds)

Returns the string used to make function calls.

EXAMPLES:

sage: maxima._function_call_string('diff', ['f(x)', 'x'], [])
'diff(f(x),x)'
_function_class()

EXAMPLES:

sage: from sage.interfaces.expect import Expect
sage: Expect._function_class(maxima)
<class 'sage.interfaces.expect.ExpectFunction'>
_function_element_class()

EXAMPLES:

sage: from sage.interfaces.expect import Expect
sage: Expect._function_element_class(maxima)
<class 'sage.interfaces.expect.FunctionElement'>
_get(wait=0.10000000000000001, alternate_prompt=None)
_get_tmpfile_from_server(local_file=None, remote_file=None)
_greaterthan_symbol()
_install_hints()

Hints for installing needed slave program on your computer.

There are no hints by default.

_install_hints_ssh()
Hints for installing passwordless authentication on your computer...
_install_hints_ssh_through_gate()
Hints for installing passwordless authentication through a gate
_interrupt()
_keyboard_interrupt()
_left_list_delim()
_lessthan_symbol()
_local_tmpfile()
_next_var_name()
_object_class()

EXAMPLES:

sage: from sage.interfaces.expect import Expect
sage: Expect._object_class(maxima)
<class 'sage.interfaces.expect.ExpectElement'>
_post_interact()
_post_process_from_file(s)
_pre_interact()
_quit_string()
_read_in_file_command(filename)
_relation_symbols()

Returns a dictionary with operators as the keys and their string representation as the values.

EXAMPLES:

sage: import operator
sage: symbols = mathematica._relation_symbols()
sage: symbols[operator.eq]
'=='
_remote_tmpdir()
_remote_tmpfile()
_remove_tmpfile_from_server()
_repr_()
_right_list_delim()
_send(cmd)
_send_tmpfile_to_server(local_file=None, remote_file=None)
_sendstr(str)

Send a string to the pexpect interface, autorestarting the expect interface if anything goes wrong.

INPUT:

  • str - a string

EXAMPLES: We illustrate this function using the R interface:

sage: r._sendstr('a <- 10;\n')
sage: r.eval('a')
'[1] 10'

We illustrate using the singular interface:

sage: singular._sendstr('int i = 5;')
sage: singular('i')
5
_so_far(wait=0.10000000000000001, alternate_prompt=None)
Return whether done and output so far and new output since last time called.
_start(alt_message=None, block_during_init=True)
_synchronize(cmd='1+%s;n')

Synchronize pexpect interface.

This put a random integer (plus one!) into the output stream, then waits for it, thus resynchronizing the stream. If the random integer doesn’t appear within 1 second, the interface is sent interrupt signals.

This way, even if you somehow left the interface in a busy state computing, calling _synchronize gets everything fixed.

EXAMPLES: We observe nothing, just as it should be:

sage: r._synchronize()

TESTS: This illustrates a synchronization bug being fixed (thanks to Simon King and David Joyner for tracking this down):

sage: R.<x> = QQ[]; f = x^3 + x + 1;  g = x^3 - x - 1; r = f.resultant(g); gap(ZZ); singular(R)
Integers
//   characteristic : 0
//   number of vars : 1
//        block   1 : ordering lp
//                  : names    x 
//        block   2 : ordering C
_true_symbol()
call(function_name, *args, **kwds)
clear(var)
Clear the variable named var.
clear_prompts()
console()
cputime()
CPU time since this process started running.
eval(code, strip=True, synchronize=False, locals=None, **kwds)

INPUT:

  • code - text to evaluate
  • strip - bool; whether to strip output prompts, etc. (ignored in the base class).
  • locals - None (ignored); this is used for compatibility with the Sage notebook’s generic system interface.
  • **kwds - All other arguments are passed onto the _eval_line method. An often useful example is reformat=False.
execute(*args, **kwds)
expect()
function_call(function, args=None, kwds=None)

EXAMPLES:

sage: maxima.quad_qags(x, x, 0, 1, epsrel=1e-4)
[0.5,5.5511151231257...e-15,21,0]
sage: maxima.function_call('quad_qags', [x, x, 0, 1], {'epsrel':'1e-4'})
[0.5,5.5511151231257...e-15,21,0]
get(var)
Get the value of the variable var.
get_using_file(var)

Return the string representation of the variable var in self, possibly using a file. Use this if var has a huge string representation, since it may be way faster.

Warning

In fact unless a special derived class implements this, it will not be any faster. This is the case for this class if you’re reading it through introspection and seeing this.

help(s)
interact()

This allows you to interactively interact with the child interpreter. Press Ctrl-D or type ‘quit’ or ‘exit’ to exit and return to Sage.

Note

This is completely different than the console() member function. The console function opens a new copy of the child interpreter, whereas the interact function gives you interactive access to the interpreter that is being used by Sage. Use sage(xxx) or interpretername(xxx) to pull objects in from sage to the interpreter.

interrupt(tries=20, timeout=0.29999999999999999, quit_on_fail=True)
is_local()
is_remote()
is_running()
Return True if self is currently running.
name(new_name=None)
new(code)
path()
pid()
quit(verbose=False, timeout=0.25)

EXAMPLES:

sage: a = maxima('y')
sage: maxima.quit()
sage: a._check_valid()
...
ValueError: The maxima session in which this object was defined is no longer running.
read(filename)

EXAMPLES:

sage: filename = tmp_filename()
sage: f = open(filename, 'w')
sage: f.write('x = 2\n')
sage: f.close()
sage: octave.read(filename)  #optional -- requires Octave
sage: octave.get('x')        #optional
' 2'
sage: import os
sage: os.unlink(filename)
set(var, value)
Set the variable var to the given value.
user_dir()
class sage.interfaces.expect.ExpectElement(parent, value, is_name=False, name=None)

Expect element.

__call__(*args)
__cmp__(other)
__contains__(x)
__del__()
__float__()

EXAMPLES:

sage: m = maxima('1/2')
sage: m.__float__()
0.5
sage: float(m)
0.5
__getattr__(attrname)
__getitem__(n)
__hash__()
Returns the hash of self. This is a default implementation of hash which just takes the hash of the string of self.
__init__(parent, value, is_name=False, name=None)
__int__()

EXAMPLES:

sage: int(maxima('1'))
1
sage: type(_)
<type 'int'>
__iter__()
__len__()
__long__()

EXAMPLES:

sage: m = maxima('1')
sage: long(m)
1L
__nonzero__()

EXAMPLES:

sage: bool(maxima(0))
False
sage: bool(maxima(1))
True
__pow__(n)

EXAMPLES:

sage: a = maxima('2')
sage: a^(3/4)
2^(3/4)
__reduce__()
__repr__()
__weakref__
list of weak references to the object (if defined)
_add_(right)

EXAMPLES:

sage: f = maxima.cos(x)
sage: g = maxima.sin(x)
sage: f + g
sin(x)+cos(x)
sage: f + 2
cos(x)+2
sage: 2 + f
cos(x)+2
_check_valid()
Check that this object is valid, i.e., the session in which this object is defined is still running. This is relevant for interpreters that can’t be interrupted via ctrl-C, hence get restarted.
_div_(right)

EXAMPLES:

sage: f = maxima.cos(x)
sage: g = maxima.sin(x)
sage: f/g
cos(x)/sin(x)
sage: f/2
cos(x)/2
_integer_(ZZ=None)

EXAMPLES:

sage: m = maxima('1')
sage: m._integer_()
1
sage: _.parent()
Integer Ring
sage: QQ(m)
1
_latex_()
_matrix_(R)
_mul_(right)

EXAMPLES:

sage: f = maxima.cos(x)
sage: g = maxima.sin(x)
sage: f*g
cos(x)*sin(x)
sage: 2*f
2*cos(x)
_operation(operation, right)
_r_action(x)
_rational_()

EXAMPLES:

sage: m = maxima('1/2')
sage: m._rational_()
1/2
sage: _.parent()
Rational Field
sage: QQ(m)
1/2
_reduce()
_sage_()

Attempt to return a Sage version of this object. This is a generic routine that just tries to evaluate the repr(self).

EXAMPLES:

sage: gp(1/2)._sage_()
1/2
sage: _.parent()
Rational Field
_sage_doc_()

EXAMPLES:

sage: gp(2)._sage_doc_()
'2'
_sub_(right)

EXAMPLES:

sage: f = maxima.cos(x)
sage: g = maxima.sin(x)
sage: f - g
cos(x)-sin(x)
sage: f - 2
cos(x)-2
sage: 2 - f
2-cos(x)
_vector_(R)
attribute(attrname)

If this wraps the object x in the system, this returns the object x.attrname. This is useful for some systems that have object oriented attribute access notation.

EXAMPLES:

sage: g = gap('SO(1,4,7)')
sage: k = g.InvariantQuadraticForm()
sage: k.attribute('matrix')
[ [ 0*Z(7), Z(7)^0, 0*Z(7), 0*Z(7) ], [ 0*Z(7), 0*Z(7), 0*Z(7), 0*Z(7) ], 
  [ 0*Z(7), 0*Z(7), Z(7), 0*Z(7) ], [ 0*Z(7), 0*Z(7), 0*Z(7), Z(7)^0 ] ]
sage: e = gp('ellinit([0,-1,1,-10,-20])')
sage: e.attribute('j')
-122023936/161051
bool()
gen(n)
get_using_file()

Return this element’s string representation using a file. Use this if self has a huge string representation. It’ll be way faster.

EXAMPLES:

sage: a = maxima(str(2^1000))
sage: a.get_using_file()
'10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376'
hasattr(attrname)

Returns whether the given attribute is already defined by this object, and in particular is not dynamically generated.

EXAMPLES:

sage: m = maxima('2')
sage: m.hasattr('integral')
True
sage: m.hasattr('gcd')
False
name(new_name=None)

Returns the name of self. If new_name is passed in, then this function returns a new object identical to self whose name is new_name.

Note that this can overwrite existing variables in the system.

EXAMPLES:

sage: x = r([1,2,3]); x
[1] 1 2 3
sage: x.name()
'sage3'
sage: x = r([1,2,3]).name('x'); x
[1] 1 2 3
sage: x.name()
'x'
sage: s5 = gap.SymmetricGroup(5).name('s5')
sage: s5
SymmetricGroup( [ 1 .. 5 ] )
sage: s5.name()
's5'
sage()

Attempt to return a Sage version of this object.

EXAMPLES:

sage: gp(1/2).sage()
1/2
sage: _.parent()
Rational Field
class sage.interfaces.expect.ExpectFunction(parent, name)

Expect function.

__call__(*args, **kwds)
__init__(parent, name)
__repr__()
__weakref__
list of weak references to the object (if defined)
_sage_doc_()

EXAMPLES:

sage: gp.gcd._sage_doc_()
'gcd(x,{y}): greatest common divisor of x and y.'
class sage.interfaces.expect.FunctionElement(obj, name)

Expect function element.

__call__(*args, **kwds)
__init__(obj, name)
__repr__()
__weakref__
list of weak references to the object (if defined)
_sage_doc_()

EXAMPLES:

sage: gp(2).gcd._sage_doc_()
'gcd(x,{y}): greatest common divisor of x and y.'
help()
exception sage.interfaces.expect.PropTypeError
__weakref__
list of weak references to the object (if defined)
sage.interfaces.expect.console(cmd)
class sage.interfaces.expect.gc_disabled

This is a “with” statement context manager. Garbage collection is disabled within its scope. Nested usage is properly handled.

EXAMPLES:

sage: import gc
sage: from sage.interfaces.expect import gc_disabled
sage: gc.isenabled()
True
sage: with gc_disabled():
...       print gc.isenabled()
...       with gc_disabled():
...           print gc.isenabled()
...       print gc.isenabled()
False
False
False
sage: gc.isenabled()
True
__enter__()
__exit__(ty, val, tb)
__weakref__
list of weak references to the object (if defined)
sage.interfaces.expect.is_ExpectElement(x)
sage.interfaces.expect.reduce_load(parent, x)
sage.interfaces.expect.tmp_expect_interface_local()

Previous topic

Interpreter Interfaces

Next topic

Interface to Axiom

This Page