def main(): quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' print_version(is_server=False) print_license() print u"Quit by pressing %s" % quit_command print '' definitions = Definitions(add_builtin=True) try: while True: input = raw_input('>> ') def out_callback(out): print to_output(unicode(out)) evaluation = Evaluation(input, definitions, timeout=30, out_callback=out_callback) for result in evaluation.results: if result.result is not None: print ' = %s' % to_output(unicode(result.result)) except (KeyboardInterrupt, SystemExit): print "\n\nGood bye!\n"
def query(request): global definitions from mathics.core.parser import MultiLineFeeder input = request.POST.get("query", "") if settings.DEBUG and not input: input = request.GET.get("query", "") if settings.LOG_QUERIES: query_log = Query( query=input, error=True, browser=request.META.get("HTTP_USER_AGENT", ""), remote_user=request.META.get("REMOTE_USER", ""), remote_addr=request.META.get("REMOTE_ADDR", ""), remote_host=request.META.get("REMOTE_HOST", ""), meta=str(request.META), log="", ) query_log.save() evaluation = get_session_evaluation(request.session) feeder = MultiLineFeeder(input, "<notebook>") results = [] try: while not feeder.empty(): expr = evaluation.parse_feeder(feeder) if expr is None: results.append(Result(evaluation.out, None, None)) # syntax errors evaluation.out = [] continue result = evaluation.evaluate(expr, timeout=settings.TIMEOUT) if result is not None: results.append(result) except SystemExit as e: results = [] result = None definitions = Definitions(add_builtin=True, extension_modules=default_pymathics_modules) evaluation.definitions = definitions except Exception as exc: if settings.DEBUG and settings.DISPLAY_EXCEPTIONS: info = traceback.format_exception(*sys.exc_info()) info = "\n".join(info) msg = "Exception raised: %s\n\n%s" % (exc, info) results.append( Result([Message("System", "exception", msg)], None, None)) else: raise result = { "results": [result.get_data() for result in results], } if settings.LOG_QUERIES: query_log.timeout = evaluation.timeout query_log.result = str(result) # evaluation.results query_log.error = False query_log.save() return JsonResponse(result)
def __init__(self, **kwargs): Kernel.__init__(self, **kwargs) self.definitions = Definitions(add_builtin=True) # TODO Cache self.definitions.set_ownvalue('$Line', Integer(0)) # Reset the line number self.establish_comm_manager() # needed for ipywidgets and Manipulate[] self.web_engine = None
def __init__( self, definitions=None, output=None, format="text", catch_interrupt=True ) -> None: from mathics.core.definitions import Definitions from mathics.core.expression import Symbol if definitions is None: definitions = Definitions() self.definitions = definitions self.recursion_depth = 0 self.timeout = False self.timeout_queue = [] self.stopped = False self.out = [] self.output = output if output else Output() self.listeners = {} self.options = None self.predetermined_out = None self.quiet_all = False self.format = format self.catch_interrupt = catch_interrupt self.SymbolNull = Symbol("Null") # status of last evaluate self.exc_result = self.SymbolNull self.last_eval = None
def get_session_evaluation(session): evaluation = _evaluations.get(session.session_key) if evaluation is None: definitions = Definitions(add_builtin=True) evaluation = Evaluation(definitions, format='xml', output=WebOutput()) _evaluations[session.session_key] = evaluation return evaluation
def __init__(self, add_builtin=True, catch_interrupt=False, form="InputForm"): self.definitions = Definitions(add_builtin) self.evaluation = Evaluation(definitions=self.definitions, catch_interrupt=catch_interrupt) self.form = form self.last_result = None
def __init__(self, **kwargs): self.mathjax_initialized = False Kernel.__init__(self, **kwargs) if self.log is None: # This occurs if we call as a stand-alone kernel # (eg, not as a process) # FIXME: take care of input/output, eg StringIO # make work without a session self.log = logging.Logger("NotebookApp") self.definitions = Definitions(add_builtin=True) # TODO Cache self.definitions.set_ownvalue('$Line', Integer(0)) # Reset the line number
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): if not silent: from mathics.core.parser import MultiLineFeeder definitions = Definitions(add_builtin=True) evaluation = Evaluation(definitions, format='xml') feeder = MultiLineFeeder(code, '<notebook>') results = [] try: while not feeder.empty(): expr = evaluation.parse_feeder(feeder) if expr is None: results.append(Result(evaluation.out, None, None)) evaluation.out = [] continue result = evaluation.evaluate(expr, timeout=20) if result is not None: results.append(result) except Exception as exc: raise for result in results: result_data = result.get_data() result_html = self.preprocess_output(result_data['result']) display_data = { 'data': { 'text/html': result_html }, 'metadata': {}, } self.send_response(self.iopub_socket, 'display_data', display_data) return { 'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}, }
def get_session_evaluation(session): evaluation = _evaluations.get(session.session_key) if evaluation is None: definitions = Definitions(add_builtin=True) # We set the formatter to "unformatted" so that we can use # our own custom formatter that understand better how to format # in the context of mathics-django. # Previously, one specific format, like "xml" had to fit all. evaluation = Evaluation(definitions, format="unformatted", output=WebOutput()) _evaluations[session.session_key] = evaluation evaluation.format_output = lambda expr, format: format_output( evaluation, expr, format) autoload_files(definitions, ROOT_DIR, "autoload") return evaluation
def do_complete(self, code, cursor_pos): definitions = Definitions(add_builtin=True) matches_raw = definitions.get_matching_names(code + '*') matches = [] for match in matches_raw: matches.append(match.replace('System`', '')) return { 'matches': matches, 'cursor_start': cursor_pos - len(code), 'cursor_end': cursor_pos, 'metadata': {}, 'status': 'ok', }
def __init__(self, input=None, definitions=None, timeout=None, out_callback=None, format='text', catch_interrupt=True): from mathics.core.definitions import Definitions if definitions is None: definitions = Definitions() self.definitions = definitions self.recursion_depth = 0 self.timeout = False self.stopped = False self.out = [] self.out_callback = out_callback self.listeners = {} self.options = None self.quiet_all = False self.quiet_messages = set() self.format = format queries = [] last_parse_error = None if input is not None: from mathics.core.parser import parse, TranslateError lines = input.splitlines() query = '' for line in lines: if line: query += line try: expression = parse(query) if expression is not None: queries.append(expression) query = '' last_parse_error = None except TranslateError, exc: last_parse_error = exc else: query += ' '
def __init__(self, definitions=None, output=None, format='text', catch_interrupt=True): from mathics.core.definitions import Definitions if definitions is None: definitions = Definitions() self.definitions = definitions self.recursion_depth = 0 self.timeout = False self.stopped = False self.out = [] self.output = output if output else Output() self.listeners = {} self.options = None self.predetermined_out = None self.quiet_all = False self.format = format self.catch_interrupt = catch_interrupt
def __init__(self, definitions=None, out_callback=None, format='text', catch_interrupt=True): from mathics.core.definitions import Definitions if definitions is None: definitions = Definitions() self.definitions = definitions self.recursion_depth = 0 self.timeout = False self.stopped = False self.out = [] self.out_callback = out_callback self.listeners = {} self.options = None self.quiet_all = False self.quiet_messages = set() self.format = format self.catch_interrupt = catch_interrupt
def main(): argparser = argparse.ArgumentParser( prog='mathics', usage='%(prog)s [options] [FILE]', add_help=False, description="Mathics is a general-purpose computer algebra system.", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument('FILE', nargs='?', type=argparse.FileType('r'), help='execute commands from FILE') argparser.add_argument('--help', '-h', help='show this help message and exit', action='help') argparser.add_argument( '--persist', help='go to interactive shell after evaluating FILE or -e', action='store_true') argparser.add_argument('--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument('-script', help='run a mathics file in script mode', action='store_true') argparser.add_argument( '--execute', '-e', action='append', metavar='EXPR', help='evaluate EXPR before processing any input files (may be given ' 'multiple times)') argparser.add_argument('--colors', nargs='?', help='interactive shell colors') argparser.add_argument('--no-completion', help="disable tab completion", action='store_true') argparser.add_argument( '--no-readline', help="disable line editing (implies --no-completion)", action='store_true') argparser.add_argument('--version', '-v', action='version', version='%(prog)s ' + __version__) args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-D' definitions = Definitions(add_builtin=True) definitions.set_line_no(0) shell = TerminalShell(definitions, args.colors, want_readline=not (args.no_readline), want_completion=not (args.no_completion)) if args.execute: for expr in args.execute: print(shell.get_in_prompt() + expr) evaluation = Evaluation(shell.definitions, output=TerminalOutput(shell)) result = evaluation.parse_evaluate(expr, timeout=settings.TIMEOUT) shell.print_result(result) if not args.persist: return if args.FILE is not None: feeder = FileLineFeeder(args.FILE) try: while not feeder.empty(): evaluation = Evaluation(shell.definitions, output=TerminalOutput(shell), catch_interrupt=False) query = evaluation.parse_feeder(feeder) if query is None: continue evaluation.evaluate(query, timeout=settings.TIMEOUT) except (KeyboardInterrupt): print('\nKeyboardInterrupt') if args.persist: definitions.set_line_no(0) else: return if not args.quiet: print() print(version_string + '\n') print(license_string + '\n') print("Quit by pressing {0}\n".format(quit_command)) while True: try: evaluation = Evaluation(shell.definitions, output=TerminalOutput(shell)) query = evaluation.parse_feeder(shell) if query is None: continue result = evaluation.evaluate(query, timeout=settings.TIMEOUT) if result is not None: shell.print_result(result) except (KeyboardInterrupt): print('\nKeyboardInterrupt') except (SystemExit, EOFError): print("\n\nGoodbye!\n") break finally: shell.reset_lineno()
def main(): argparser = argparse.ArgumentParser( prog='mathics', usage='%(prog)s [options] [FILE]', add_help=False, description="Mathics is a general-purpose computer algebra system.", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument('FILE', nargs='?', type=argparse.FileType('r'), help='execute commands from FILE') argparser.add_argument('--help', '-h', help='show this help message and exit', action='help') argparser.add_argument( '--persist', help='go to interactive shell after evaluating FILE', action='store_true') argparser.add_argument('--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument('-script', help='run a mathics file in script mode', action='store_true') argparser.add_argument('--execute', '-e', nargs='?', help='execute a command') argparser.add_argument('--colors', nargs='?', help='interactive shell colors') argparser.add_argument('--version', '-v', action='version', version=get_version_string(False)) args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-D' definitions = Definitions(add_builtin=True) definitions.set_ownvalue('$Line', Integer(1)) #Reset the line number to 1 shell = TerminalShell(definitions, args.colors) if not (args.quiet or args.script): print_version(is_server=False) print_license() print u"Quit by pressing {0}\n".format(quit_command) if args.execute: total_input = args.execute.decode(sys.stdin.encoding) # check encoding print shell.get_in_prompt() + total_input shell.evaluate(total_input) return if args.FILE is not None: total_input = '' for line_no, line in enumerate(args.FILE): try: line = line.decode('utf-8') # TODO: other encodings if args.script and line_no == 0 and line.startswith('#!'): continue print shell.get_in_prompt( continued=(total_input != '')) + line, total_input += ' ' + line if line != "" and wait_for_line(total_input): continue shell.evaluate(total_input) total_input = "" except (KeyboardInterrupt): print '\nKeyboardInterrupt' except (SystemExit, EOFError): print "\n\nGood bye!\n" break if not args.persist: return total_input = "" while True: try: line = raw_input(shell.get_in_prompt(continued=total_input != '')) line = line.decode(sys.stdin.encoding) total_input += line if line != "" and wait_for_line(total_input): continue shell.evaluate(total_input) total_input = "" except (KeyboardInterrupt): print '\nKeyboardInterrupt' except (SystemExit, EOFError): print "\n\nGood bye!\n" break
def main( full_form, persist, quiet, readline, completion, unicode, prompt, pyextensions, execute, run, style, pygments_tokens, strict_wl_output, file, ) -> int: """A command-line interface to Mathics. Mathics is a general-purpose computer algebra system """ exit_rc = 0 quit_command = "CTRL-BREAK" if sys.platform == "win32" else "CONTROL-D" extension_modules = [] if pyextensions: for ext in pyextensions: extension_modules.append(ext) definitions = Definitions(add_builtin=True) definitions.set_line_no(0) # Set a default value for $ShowFullFormInput to False. # Then, it can be changed by the settings file (in WL) # and overwritten by the command line parameter. definitions.set_ownvalue( "Settings`$ShowFullFormInput", from_python(True if full_form else False) ) definitions.set_ownvalue( "Settings`$PygmentsShowTokens", from_python(True if pygments_tokens else False) ) readline = "none" if (execute or file and not persist) else readline.lower() if readline == "prompt": shell = TerminalShellPromptToolKit( definitions, style, completion, unicode, prompt ) else: want_readline = readline == "gnu" shell = TerminalShellGNUReadline( definitions, style, want_readline, completion, unicode, prompt ) load_settings(shell) if run: with open(run, "r") as ifile: feeder = MathicsFileLineFeeder(ifile) try: while not feeder.empty(): evaluation = Evaluation( shell.definitions, output=TerminalOutput(shell), catch_interrupt=False, format="text", ) query = evaluation.parse_feeder(feeder) if query is None: continue evaluation.evaluate(query, timeout=settings.TIMEOUT) except (KeyboardInterrupt): print("\nKeyboardInterrupt") definitions.set_line_no(0) if execute: for expr in execute: evaluation = Evaluation( shell.definitions, output=TerminalOutput(shell), format="text" ) shell.terminal_formatter = None result = evaluation.parse_evaluate(expr, timeout=settings.TIMEOUT) shell.print_result(result, prompt, "text", strict_wl_output) # After the next release, we can remove the hasattr test. if hasattr(evaluation, "exc_result"): if evaluation.exc_result == Symbol("Null"): exit_rc = 0 elif evaluation.exc_result == Symbol("$Aborted"): exit_rc = -1 elif evaluation.exc_result == Symbol("Overflow"): exit_rc = -2 else: exit_rc = -3 if not persist: return exit_rc if file is not None: with open(file, "r") as ifile: feeder = MathicsFileLineFeeder(ifile) try: while not feeder.empty(): evaluation = Evaluation( shell.definitions, output=TerminalOutput(shell), catch_interrupt=False, format="text", ) query = evaluation.parse_feeder(feeder) if query is None: continue evaluation.evaluate(query, timeout=settings.TIMEOUT) except (KeyboardInterrupt): print("\nKeyboardInterrupt") if not persist: return exit_rc if not quiet and prompt: print(f"\nMathicscript: {__version__}, {version_string}\n") print(license_string + "\n") print(f"Quit by evaluating Quit[] or by pressing {quit_command}.\n") # If defined, full_form and style overwrite the predefined values. definitions.set_ownvalue( "Settings`$ShowFullFormInput", SymbolTrue if full_form else SymbolFalse ) definitions.set_ownvalue( "Settings`$PygmentsStyle", from_python(shell.pygments_style) ) definitions.set_ownvalue( "Settings`$PygmentsShowTokens", from_python(pygments_tokens) ) definitions.set_ownvalue("Settings`MathicsScriptVersion", from_python(__version__)) definitions.set_attribute("Settings`MathicsScriptVersion", "System`Protected") definitions.set_attribute("Settings`MathicsScriptVersion", "System`Locked") TeXForm = Symbol("System`TeXForm") definitions.set_line_no(0) while True: try: if have_readline and shell.using_readline: import readline as GNU_readline last_pos = GNU_readline.get_current_history_length() full_form = definitions.get_ownvalue( "Settings`$ShowFullFormInput" ).replace.to_python() style = definitions.get_ownvalue("Settings`$PygmentsStyle") fmt = lambda x: x if style: style = style.replace.get_string_value() if shell.terminal_formatter: fmt = lambda x: highlight( str(query), mma_lexer, shell.terminal_formatter ) evaluation = Evaluation(shell.definitions, output=TerminalOutput(shell)) query, source_code = evaluation.parse_feeder_returning_code(shell) if ( have_readline and shell.using_readline and hasattr(GNU_readline, "remove_history_item") ): current_pos = GNU_readline.get_current_history_length() for pos in range(last_pos, current_pos - 1): GNU_readline.remove_history_item(pos) wl_input = source_code.rstrip() if unicode: wl_input = replace_wl_with_plain_text(wl_input) GNU_readline.add_history(wl_input) if query is None: continue if hasattr(query, "head") and query.head == TeXForm: output_style = "//TeXForm" else: output_style = "" if full_form: print(fmt(query)) result = evaluation.evaluate( query, timeout=settings.TIMEOUT, format="unformatted" ) if result is not None: shell.print_result( result, prompt, output_style, strict_wl_output=strict_wl_output ) except ShellEscapeException as e: source_code = e.line if len(source_code) and source_code[1] == "!": try: print(open(source_code[2:], "r").read()) except: print(str(sys.exc_info()[1])) else: subprocess.run(source_code[1:], shell=True) # Should we test exit code for adding to history? GNU_readline.add_history(source_code.rstrip()) # FIXME add this... when in Mathics core updated # shell.defintions.increment_line(1) except (KeyboardInterrupt): print("\nKeyboardInterrupt") except EOFError: if prompt: print("\n\nGoodbye!\n") break except SystemExit: print("\n\nGoodbye!\n") # raise to pass the error code on, e.g. Quit[1] raise finally: # Reset the input line that would be shown in a parse error. # This is not to be confused with the number of complete # inputs that have been seen, i.e. In[] shell.reset_lineno() return exit_rc
def __init__(self, **kwargs): super().__init__(**kwargs) self.definitions = Definitions(add_builtin=True) self.evaluation = Evaluation(self.definitions, format='xml')
def main(): from mathics.doc import documentation as main_mathics_documentation global definitions global documentation global logfile global check_partial_enlapsed_time definitions = Definitions(add_builtin=True) documentation = main_mathics_documentation parser = ArgumentParser(description="Mathics test suite.", add_help=False) parser.add_argument("--help", "-h", help="show this help message and exit", action="help") parser.add_argument("--version", "-v", action="version", version="%(prog)s " + mathics.__version__) parser.add_argument( "--chapters", "-c", dest="chapters", metavar="CHAPTER", help="only test CHAPTER(s). " "You can list multiple chapters by adding a comma (and no space) in between chapter names.", ) parser.add_argument( "--sections", "-s", dest="sections", metavar="SECTION", help="only test SECTION(s). " "You can list multiple sections by adding a comma (and no space) in between section names.", ) parser.add_argument( "--exclude", "-X", default="", dest="exclude", metavar="SECTION", help="excude SECTION(s). " "You can list multiple sections by adding a comma (and no space) in between section names.", ) parser.add_argument( "--logfile", "-f", dest="logfilename", metavar="LOGFILENAME", help="stores the output in [logfilename]. ", ) parser.add_argument( "--pymathics", "-l", dest="pymathics", action="store_true", help="also checks pymathics modules.", ) parser.add_argument( "--time-each", "-d", dest="enlapsed_times", action="store_true", help= "check the time that take each test to parse, evaluate and compare.", ) parser.add_argument( "--output", "-o", dest="output", action="store_true", help="generate LaTeX pickled internal data", ) parser.add_argument( "--doc-only", dest="doc_only", action="store_true", help= "generate LaTeX pickled internal data without running tests; Can't be used with --section or --reload.", ) parser.add_argument( "--latex-only", dest="latex_only", action="store_true", help= "generate LaTeX output from internal data without running tests; assumes --reload", ) parser.add_argument( "--reload", "-r", dest="reload", action="store_true", help="reload LaTeX pickled internal data, before possibly adding to it", ) parser.add_argument( "--tex", "-t", dest="tex", action="store_true", help="include LaTeX document generation file at the end of other steps", ) parser.add_argument("--quiet", "-q", dest="quiet", action="store_true", help="hide passed tests") parser.add_argument( "--keep-going", "-k", dest="keep_going", action="store_true", help="create documentation even if there is a test failure", ) parser.add_argument("--stop-on-failure", "-x", action="store_true", help="stop on failure") parser.add_argument( "--skip", metavar="N", dest="skip", type=int, default=0, help="skip the first N tests", ) parser.add_argument( "--count", metavar="N", dest="count", type=int, default=MAX_TESTS, help="run only N tests", ) args = parser.parse_args() if args.enlapsed_times: check_partial_enlapsed_time = True # If a test for a specific section is called # just test it if args.logfilename: logfile = open(args.logfilename, "wt") if args.sections: sections = set(args.sections.split(",")) if args.pymathics: # in case the section is in a pymathics module... documentation.load_pymathics_doc() test_sections(sections, stop_on_failure=args.stop_on_failure, reload=args.reload) elif args.chapters: chapters = set(args.chapters.split(",")) if args.pymathics: # in case the section is in a pymathics module... documentation.load_pymathics_doc() test_chapters(chapters, stop_on_failure=args.stop_on_failure, reload=args.reload) else: # if we want to check also the pymathics modules if args.pymathics: print("Building pymathics documentation object") documentation.load_pymathics_doc() elif args.latex_only: write_latex() elif args.doc_only: extract_doc_from_source( quiet=args.quiet, reload=args.reload, ) else: excludes = set(args.exclude.split(",")) start_at = args.skip + 1 start_time = datetime.now() test_all( quiet=args.quiet, generate_output=args.output, stop_on_failure=args.stop_on_failure, start_at=start_at, count=args.count, doc_even_if_error=args.keep_going, excludes=excludes, ) end_time = datetime.now() print("Tests took ", end_time - start_time) # If TeX output requested, try to build it: if args.tex: write_latex() if logfile: logfile.close()
response = json.dumps(result) super(JsonResponse, self).__init__(response, content_type=JSON_CONTENT_TYPE) def require_ajax_login(func): def new_func(request, *args, **kwargs): if not request.user.is_authenticated(): return JsonResponse({'requireLogin': True}) return func(request, *args, **kwargs) return new_func from mathics.settings import default_pymathics_modules definitions = Definitions(add_builtin=True, extension_modules=default_pymathics_modules) def require_ajax_login(f): return f def main_view(request): context = { 'login_form': LoginForm(), 'save_form': SaveForm(), 'require_login': settings.REQUIRE_LOGIN, } return render(request, 'main.html', context)
def main(): argparser = argparse.ArgumentParser( prog='mathics', usage='%(prog)s [options] [FILE]', add_help=False, description="Mathics is a general-purpose computer algebra system.", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument('FILE', nargs='?', type=argparse.FileType('r'), help='execute commands from FILE') argparser.add_argument('--help', '-h', help='show this help message and exit', action='help') argparser.add_argument( '--persist', help='go to interactive shell after evaluating FILE', action='store_true') argparser.add_argument('--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument('-script', help='run a mathics file in script mode', action='store_true') argparser.add_argument('--version', '-v', action='version', version=get_version_string(False)) args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-D' if not (args.quiet or args.script): print_version(is_server=False) print_license() print u"Quit by pressing %s" % quit_command print '' definitions = Definitions(add_builtin=True) trailing_ops = ['+', '-', '/', '*'] # TODO all binary operators? if args.FILE is not None: total_input = "" for line in args.FILE: if args.script and line.startswith('#!'): continue if total_input == "": print '>> ', line, else: print ' ', line, total_input += line if line == "": pass elif any(line.rstrip().endswith(op) for op in trailing_ops) or not brackets_balanced(total_input): continue evaluation = Evaluation(total_input, definitions, timeout=30, out_callback=out_callback) for result in evaluation.results: if result.result is not None: print ' = %s' % to_output(unicode(result.result)) total_input = "" if not args.persist: return while True: try: total_input = "" line_input = raw_input('>> ') while line_input != "": total_input += ' ' + line_input if any( [line_input.rstrip().endswith(op) for op in trailing_ops]): pass elif brackets_balanced(total_input): break line_input = raw_input(' ') evaluation = Evaluation(total_input, definitions, timeout=30, out_callback=out_callback) for result in evaluation.results: if result.result is not None: print ' = %s' % to_output(unicode(result.result)) except (KeyboardInterrupt): print '\nKeyboardInterrupt' except (SystemExit, EOFError): print "\n\nGood bye!\n" break
def main(): argparser = argparse.ArgumentParser( prog='mathics', usage='%(prog)s [options] [FILE]', add_help=False, description="Mathics is a general-purpose computer algebra system.", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument('FILE', nargs='?', type=argparse.FileType('r'), help='execute commands from FILE') argparser.add_argument('--help', '-h', help='show this help message and exit', action='help') argparser.add_argument( '--persist', help='go to interactive shell after evaluating FILE or -e', action='store_true') argparser.add_argument('--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument('-script', help='run a mathics file in script mode', action='store_true') argparser.add_argument( '--execute', '-e', action='append', metavar='EXPR', help='evaluate EXPR before processing any input files (may be given ' 'multiple times)') argparser.add_argument('--colors', nargs='?', help='interactive shell colors') argparser.add_argument('--no-completion', help="disable tab completion", action='store_true') argparser.add_argument( '--no-readline', help="disable line editing (implies --no-completion)", action='store_true') argparser.add_argument('--version', '-v', action='version', version='%(prog)s ' + __version__) args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-D' definitions = Definitions(add_builtin=True) definitions.set_line_no(0) # Reset the line number shell = TerminalShell(definitions, args.colors, want_readline=not (args.no_readline), want_completion=not (args.no_completion)) if not (args.quiet or args.script): print() print(version_string + '\n') print(license_string + '\n') print("Quit by pressing {0}\n".format(quit_command)) if args.execute: for expr in args.execute: print(shell.get_in_prompt() + expr) evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback) exprs = evaluation.parse(expr) results = evaluation.evaluate(exprs, timeout=settings.TIMEOUT) shell.print_results(results) if not args.persist: return if args.FILE is not None: lines = args.FILE.readlines() if args.script and lines[0].startswith('#!'): lines[0] = '' results = [] query_gen = parse_lines(lines, shell.definitions) evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback) try: for query in query_gen: results.extend( evaluation.evaluate([query], timeout=settings.TIMEOUT)) except TranslateError as exc: evaluation.recursion_depth = 0 evaluation.stopped = False evaluation.message('Syntax', exc.msg, *exc.args) except (KeyboardInterrupt): print('\nKeyboardInterrupt') except (SystemExit, EOFError): print("\n\nGood bye!\n") if not args.persist: return total_input = "" while True: try: evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback) line = shell.read_line( shell.get_in_prompt(continued=total_input != '')) total_input += line try: query = parse(total_input, shell.definitions) except TranslateError as exc: if line == '' or not isinstance(exc, IncompleteSyntaxError): evaluation.message('Syntax', exc.msg, *exc.args) total_input = "" continue total_input = "" if query is None: continue results = evaluation.evaluate([query], timeout=settings.TIMEOUT) shell.print_results(results) except (KeyboardInterrupt): print('\nKeyboardInterrupt') except (SystemExit, EOFError): print("\n\nGood bye!\n") break
def main(): from mathics.doc import documentation as main_mathics_documentation global definitions global documentation definitions = Definitions(add_builtin=True) documentation = main_mathics_documentation parser = ArgumentParser(description="Mathics test suite.", add_help=False) parser.add_argument("--help", "-h", help="show this help message and exit", action="help") parser.add_argument("--version", "-v", action="version", version="%(prog)s " + mathics.__version__) parser.add_argument("--section", "-s", dest="section", metavar="SECTION", help="only test SECTION") parser.add_argument('--pymathics', '-l', dest="pymathics", action="store_true", help="also checks pymathics modules.") parser.add_argument( "--output", "-o", dest="output", action="store_true", help="generate TeX and XML output data", ) parser.add_argument( "--tex", "-t", dest="tex", action="store_true", help="generate TeX documentation file", ) parser.add_argument("--quiet", "-q", dest="quiet", action="store_true", help="hide passed tests") parser.add_argument("--stop-on-failure", action="store_true", help="stop on failure") parser.add_argument( "--skip", metavar="N", dest="skip", type=int, default=0, help="skip the first N tests", ) args = parser.parse_args() # If a test for a specific section is called # just test it if args.section: if args.pymathics: # in case the section is in a pymathics module... documentation.load_pymathics_doc() test_section(args.section, stop_on_failure=args.stop_on_failure) else: # if we want to check also the pymathics modules if args.pymathics: print("Building pymathics documentation object") documentation.load_pymathics_doc() else: start_at = args.skip + 1 test_all(quiet=args.quiet, generate_output=args.output, stop_on_failure=args.stop_on_failure, start_at=start_at) # If it was asked for tex output, try to build it: if args.tex: write_latex()
def main(): from mathics.doc import documentation as main_mathics_documentation global definitions global documentation definitions = Definitions(add_builtin=True) documentation = main_mathics_documentation parser = ArgumentParser(description="Mathics test suite.", add_help=False) parser.add_argument("--help", "-h", help="show this help message and exit", action="help") parser.add_argument("--version", "-v", action="version", version="%(prog)s " + mathics.__version__) parser.add_argument("--section", "-s", dest="section", metavar="SECTION", help="only test SECTION") parser.add_argument('--pymathics', '-l', dest="pymathics", action="store_true", help="also checks pymathics modules.") parser.add_argument( "--output", "-o", dest="output", action="store_true", help="generate TeX and XML output data", ) parser.add_argument( "--tex", "-t", dest="tex", action="store_true", help="generate TeX documentation file", ) parser.add_argument("--quiet", "-q", dest="quiet", action="store_true", help="hide passed tests") parser.add_argument("--stop-on-failure", action="store_true", help="stop on failure") parser.add_argument( "--skip", metavar="N", dest="skip", type=int, default=0, help="skip the first N tests", ) args = parser.parse_args() print("This needs to be gone over") return if args.tex: write_latex() elif args.section: test_section(args.section, stop_on_failure=args.stop_on_failure) else: documentation.load_pymathics_doc() if args.section: test_section(args.section, stop_on_failure=args.stop_on_failure) else: start_at = args.skip + 1 test_all(quiet=args.quiet, generate_output=args.output, stop_on_failure=args.stop_on_failure, start_at=start_at)
def main() -> int: """ Command-line entry. Return exit code we want to give status of """ exit_rc = 0 argparser = argparse.ArgumentParser( prog="mathics", usage="%(prog)s [options] [FILE]", add_help=False, description="Mathics is a general-purpose computer algebra system.", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""", ) argparser.add_argument( "FILE", nargs="?", type=argparse.FileType("r"), help="execute commands from FILE", ) argparser.add_argument( "--help", "-h", help="show this help message and exit", action="help" ) argparser.add_argument( "--full-form", "-F", help="Show how input was parsed to FullForm", action="store_true", ) argparser.add_argument( "--pyextensions", "-l", action="append", metavar="PYEXT", help="directory to load extensions in python", ) argparser.add_argument( "--persist", help="go to interactive shell after evaluating FILE or -e", action="store_true", ) # --initfile is different from the combination FILE --persist since the first one # leaves the history empty and sets the current $Line to 1. argparser.add_argument( "--initfile", help="the same that FILE and --persist together", type=argparse.FileType("r"), ) argparser.add_argument( "--quiet", "-q", help="don't print message at startup", action="store_true" ) argparser.add_argument( "-script", help="run a mathics file in script mode", action="store_true" ) argparser.add_argument( "--execute", "-e", action="append", metavar="EXPR", help="evaluate EXPR before processing any input files (may be given " "multiple times)", ) argparser.add_argument("--colors", nargs="?", help="interactive shell colors") argparser.add_argument( "--no-completion", help="disable tab completion", action="store_true" ) argparser.add_argument( "--no-readline", help="disable line editing (implies --no-completion)", action="store_true", ) argparser.add_argument( "--version", "-v", action="version", version="%(prog)s " + __version__ ) args, script_args = argparser.parse_known_args() quit_command = "CTRL-BREAK" if sys.platform == "win32" else "CONTROL-D" extension_modules = [] if args.pyextensions: for ext in args.pyextensions: extension_modules.append(ext) else: from mathics.settings import default_pymathics_modules extension_modules = default_pymathics_modules definitions = Definitions(add_builtin=True, extension_modules=extension_modules) definitions.set_line_no(0) shell = TerminalShell( definitions, args.colors, want_readline=not (args.no_readline), want_completion=not (args.no_completion), ) if args.initfile: feeder = FileLineFeeder(args.initfile) try: while not feeder.empty(): evaluation = Evaluation( shell.definitions, output=TerminalOutput(shell), catch_interrupt=False, ) query = evaluation.parse_feeder(feeder) if query is None: continue evaluation.evaluate(query, timeout=settings.TIMEOUT) except (KeyboardInterrupt): print("\nKeyboardInterrupt") definitions.set_line_no(0) if args.execute: for expr in args.execute: evaluation = Evaluation(shell.definitions, output=TerminalOutput(shell)) result = evaluation.parse_evaluate(expr, timeout=settings.TIMEOUT) shell.print_result(result, no_out_prompt=True) if evaluation.exc_result == Symbol("Null"): exit_rc = 0 elif evaluation.exc_result == Symbol("$Aborted"): exit_rc = -1 elif evaluation.exc_result == Symbol("Overflow"): exit_rc = -2 else: exit_rc = -3 if not args.persist: return exit_rc if args.FILE is not None: feeder = FileLineFeeder(args.FILE) try: while not feeder.empty(): evaluation = Evaluation( shell.definitions, output=TerminalOutput(shell), catch_interrupt=False, ) query = evaluation.parse_feeder(feeder) if query is None: continue evaluation.evaluate(query, timeout=settings.TIMEOUT) except (KeyboardInterrupt): print("\nKeyboardInterrupt") if args.persist: definitions.set_line_no(0) else: return exit_rc if not args.quiet: print() print(version_string + "\n") print(license_string + "\n") print("Quit by pressing {0}\n".format(quit_command)) while True: try: evaluation = Evaluation(shell.definitions, output=TerminalOutput(shell)) query, source_code = evaluation.parse_feeder_returning_code(shell) if len(source_code) and source_code[0] == "!": subprocess.run(source_code[1:], shell=True) shell.definitions.increment_line_no(1) continue if query is None: continue if args.full_form: print(query) result = evaluation.evaluate(query, timeout=settings.TIMEOUT) if result is not None: shell.print_result(result) except (KeyboardInterrupt): print("\nKeyboardInterrupt") except EOFError: print("\n\nGoodbye!\n") break except SystemExit: print("\n\nGoodbye!\n") # raise to pass the error code on, e.g. Quit[1] raise finally: shell.reset_lineno() return exit_rc
def setUpModule(): global definitions definitions = Definitions(add_builtin=True)
import unittest import random import sys from mathics_scanner import ( IncompleteSyntaxError, InvalidSyntaxError, ScanError, SingleLineFeeder, ) from mathics.core.definitions import Definitions from mathics.core.parser import parse from mathics.core.expression import Symbol, Integer, Expression, Real, Rational, String definitions = Definitions(add_builtin=True) class ConvertTests(unittest.TestCase): def parse(self, code): return parse(definitions, SingleLineFeeder(code)) def check(self, expr1, expr2): if isinstance(expr1, str): expr1 = self.parse(expr1) if isinstance(expr2, str): expr2 = self.parse(expr2) if expr1 is None: assert expr2 is None else:
def setUp(self): definitions = Definitions(add_builtin=True) self.evaluation = Evaluation(definitions, format="xml")
def main(): argparser = argparse.ArgumentParser( prog='mathics', usage='%(prog)s [options] [FILE]', add_help=False, description="Mathics is a general-purpose computer algebra system.", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument('FILE', nargs='?', type=argparse.FileType('r'), help='execute commands from FILE') argparser.add_argument('--help', '-h', help='show this help message and exit', action='help') argparser.add_argument( '--persist', help='go to interactive shell after evaluating FILE', action='store_true') argparser.add_argument('--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument('-script', help='run a mathics file in script mode', action='store_true') argparser.add_argument('--execute', '-e', nargs='?', help='execute a command') argparser.add_argument('--colors', nargs='?', help='interactive shell colors') argparser.add_argument('--version', '-v', action='version', version=get_version_string(False)) args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-D' definitions = Definitions(add_builtin=True) # TODO all binary operators? #Reset the line number to 1 definitions.set_ownvalue('$Line', Integer(1)) shell = TerminalShell(definitions, args.colors) if args.execute: print get_in_prompt() + args.execute evaluation = Evaluation(args.execute, definitions, timeout=30, out_callback=out_callback) for result in evaluation.results: if result.result is not None: print shell.get_out_prompt() + to_output(unicode( result.result)) + '\n' return if not (args.quiet or args.script): print_version(is_server=False) print_license() print u"Quit by pressing %s" % quit_command print '' if args.FILE is not None: total_input = "" for line in args.FILE: if args.script and line.startswith('#!'): continue if total_input == "": print shell.get_in_prompt() + line, else: print ' ', line, total_input += line if line == "": pass elif wait_for_line(total_input): continue evaluation = Evaluation(total_input, definitions, timeout=30, out_callback=out_callback) for result in evaluation.results: if result.result is not None: print shell.get_out_prompt() + to_output( unicode(result.result)) + '\n' total_input = "" if not args.persist: return while True: try: total_input = "" line_input = raw_input(shell.get_in_prompt()) while line_input != "": total_input += ' ' + line_input if not wait_for_line(total_input): break line_input = raw_input(' ') evaluation = Evaluation(total_input, definitions, timeout=30, out_callback=out_callback) for result in evaluation.results: if result.result is not None: print shell.get_out_prompt() + to_output( unicode(result.result)) + '\n' except (KeyboardInterrupt): print '\nKeyboardInterrupt' except (SystemExit, EOFError): print "\n\nGood bye!\n" break
def main(): from mathics.doc import documentation as main_mathics_documentation global definitions global documentation definitions = Definitions(add_builtin=True) documentation = main_mathics_documentation parser = ArgumentParser(description="Mathics test suite.", add_help=False) parser.add_argument("--help", "-h", help="show this help message and exit", action="help") parser.add_argument("--version", "-v", action="version", version="%(prog)s " + mathics.__version__) parser.add_argument( "--sections", "-s", dest="section", metavar="SECTION", help="only test SECTION(s). " "You can list multiple sections by adding a comma (and no space) in between section names." ) parser.add_argument( "--pymathics", "-l", dest="pymathics", action="store_true", help="also checks pymathics modules.", ) parser.add_argument( "--output", "-o", dest="output", action="store_true", help="generate TeX and XML output data", ) parser.add_argument( "--doc-only", dest="doc_only", action="store_true", help="generate TeX and XML output data without running tests", ) parser.add_argument( "--tex", "-t", dest="tex", action="store_true", help="generate TeX documentation file", ) parser.add_argument("--quiet", "-q", dest="quiet", action="store_true", help="hide passed tests") parser.add_argument( "--keep-going", "-k", dest="keep_going", action="store_true", help="create documentation even if there is a test failure", ) parser.add_argument("--stop-on-failure", action="store_true", help="stop on failure") parser.add_argument( "--skip", metavar="N", dest="skip", type=int, default=0, help="skip the first N tests", ) parser.add_argument( "--count", metavar="N", dest="count", type=int, default=MAX_TESTS, help="run only N tests", ) args = parser.parse_args() # If a test for a specific section is called # just test it if args.section: sections = set(args.section.split(",")) if args.pymathics: # in case the section is in a pymathics module... documentation.load_pymathics_doc() test_section(sections, stop_on_failure=args.stop_on_failure) else: # if we want to check also the pymathics modules if args.pymathics: print("Building pymathics documentation object") documentation.load_pymathics_doc() elif args.doc_only: make_doc(quiet=args.quiet, ) else: start_at = args.skip + 1 start_time = datetime.now() test_all( quiet=args.quiet, generate_output=args.output, stop_on_failure=args.stop_on_failure, start_at=start_at, count=args.count, doc_even_if_error=args.keep_going, ) end_time = datetime.now() print("Tests took ", end_time - start_time) # If TeX output requested, try to build it: if args.tex: write_latex()
import sys import re import pickle import os from argparse import ArgumentParser import mathics from mathics.core.definitions import Definitions from mathics.core.evaluation import Evaluation, Output from mathics.core.parser import SingleLineFeeder from mathics.builtin import builtins from mathics.doc import documentation from mathics import version_string from mathics import settings definitions = Definitions(add_builtin=True, extension_modules=['pymathics.natlang']) class TestOutput(Output): def max_stored_size(self, settings): return None sep = "-" * 70 + "\n" # Global variables definitions = None documentation = None def compare(result, wanted):