Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sage
Path: blob/develop/src/bin/math-readline
4052 views
#!/usr/bin/env python3

# Cleverly run Mathematica with the benefit of readline, which
# is something the usual commercial mathematica doesn't provide!
# See
#    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363500

import signal
import subprocess
import sys

from sage.cpython.string import str_to_bytes


def child_exited(*args):
    global child
    status = child.poll()
    if status is not None:
        sys.exit(status)

signal.signal(signal.SIGCHLD, child_exited)

child = subprocess.Popen('math', shell=True, stdin=subprocess.PIPE)
pipe = child.stdin
while True:
    try:
        line = input()
        pipe.write(str_to_bytes(line + '\n'))
        pipe.flush()
    except KeyboardInterrupt:
        pipe.close()
    except EOFError:
        break
sys.stdout.write('\n')