Example #1
0
def test_install():
    console = Console(file=io.StringIO())
    dh = sys.displayhook
    install(console)
    sys.displayhook("foo")
    assert console.file.getvalue() == "'foo'\n"
    assert sys.displayhook is not dh
Example #2
0
    def _read(self, stream):
        status = 'unknown'
        line_number = 0
        for line in stream:
            line_number += 1
            # print(line_number, line,sep='\t', end='')
            if re.match(self._identifier_node, line):
                status = 'node'
                continue
            if re.match(self._identifier_element, line):
                status = 'element'
                self._process_element_identifier(line)
                continue
            if re.match(self._identifier, line):
                status = 'unknown'
                continue
            if re.match(self._identifier_comment, line):
                continue

            try:
                self._process_line(line, status)
            except Exception:
                sys.displayhook(sys.exc_info())
                sys.stderr.write(
                    'Error when processing line {line_number}\n'.format(
                        line_number=line_number))
                sys.stderr.write(line + '\n')
                res = input('Continue?(Y/N)')
                if res.upper() == 'Y':
                    continue
                else:
                    raise
Example #3
0
    def complete_from_context(self, completion_context, old_completer_args=None):
        trace = XSH.env.get("XONSH_TRACE_COMPLETIONS")
        if trace:
            print("\nTRACE COMPLETIONS: Getting completions with context:")
            sys.displayhook(completion_context)
        lprefix = 0
        completions = set()
        query_limit = XSH.env.get("COMPLETION_QUERY_LIMIT")

        for comp in self.generate_completions(
            completion_context,
            old_completer_args,
            trace,
        ):
            completion, lprefix = comp
            completions.add(completion)
            if query_limit and len(completions) >= query_limit:
                if trace:
                    print(
                        "TRACE COMPLETIONS: Stopped after $COMPLETION_QUERY_LIMIT reached."
                    )
                break

        def sortkey(s):
            return s.lstrip(''''"''').lower()

        # the last completer's lprefix is returned. other lprefix values are inside the RichCompletions.
        return tuple(sorted(completions, key=sortkey)), lprefix
Example #4
0
    def execute(self, inputfield, output):
        source = get_text(inputfield)
        self.namespace['__output__'] = output
        self.counter += 1
        name = 'In[%s]' % self.counter

        sys_backup = {}
        for key, value in self.namespace_sys.items():
            sys_backup[key] = getattr(sys, key)
            setattr(sys, key, value)

        is_expression = False
        self.ans = None
        self.aborted = False
        ok = False
        try:
            try:
                try:
                    code = compile(source, name, 'eval')
                    is_expression = True
                except SyntaxError:
                    code = compile(source, name, 'exec')
                sys.settrace(self.trace_fun)
                self.ans = eval(code, self.namespace)
                if is_expression:
                    sys.displayhook(self.ans)
                ok = True
            except Exception, e:
                self.show_traceback(name)
        finally:
            # restore global values
            sys.settrace(None)
            for key, value in sys_backup.items():
                self.namespace_sys[key] = getattr(sys, key)
                setattr(sys, key, value)
    def out_graph_show(self, col_name, process, lower, upper, df_old, df_new):
        self.win = pg.GraphicsLayoutWidget(show=True)
        self.win.resize(1200, 760)
        self.win.setWindowTitle(col_name + " " + str(process))
        plt1 = self.win.addPlot(title='Before ')
        plt2 = self.win.addPlot(title='Processed ')

        s1 = pg.ScatterPlotItem(pen=pg.mkPen(None),
                                brush=pg.mkBrush(255, 255, 255, 120))
        pos = df_old[col_name]
        s1.addPoints(x=pos.index, y=pos[:])
        plt1.addItem(s1)

        lr_low = pg.LinearRegionItem([lower, df_old[col_name].min()],
                                     movable=False,
                                     brush=(150, 0, 0, 150),
                                     orientation='horizontal')
        lr_low.setZValue(-10)
        plt1.addItem(lr_low)
        lr_upper = pg.LinearRegionItem([upper, df_old[col_name].max()],
                                       movable=False,
                                       brush=(150, 0, 0, 150),
                                       orientation='horizontal')
        lr_upper.setZValue(-10)
        plt1.addItem(lr_upper)

        s2 = pg.ScatterPlotItem(pen=pg.mkPen(None),
                                brush=pg.mkBrush(255, 255, 255, 120))
        pos2 = df_new[col_name]
        s2.addPoints(x=pos2.index, y=pos2[:])
        plt2.addItem(s2)

        sys.displayhook(self.win)
Example #6
0
    def edit_syntax_error(self):
        """The bottom half of the syntax error handler called in the main loop.

        Loop until syntax error is fixed or user cancels.
        """

        while self.SyntaxTB.last_syntax_error:
            # copy and clear last_syntax_error
            err = self.SyntaxTB.clear_err_state()
            if not self._should_recompile(err):
                return
            try:
                # may set last_syntax_error again if a SyntaxError is raised
                self.safe_execfile(err.filename, self.user_ns)
            except:
                self.showtraceback()
            else:
                try:
                    f = open(err.filename)
                    try:
                        # This should be inside a display_trap block and I
                        # think it is.
                        sys.displayhook(f.read())
                    finally:
                        f.close()
                except:
                    self.showtraceback()
Example #7
0
    def edit_syntax_error(self):
        """The bottom half of the syntax error handler called in the main loop.

        Loop until syntax error is fixed or user cancels.
        """

        while self.SyntaxTB.last_syntax_error:
            # copy and clear last_syntax_error
            err = self.SyntaxTB.clear_err_state()
            if not self._should_recompile(err):
                return
            try:
                # may set last_syntax_error again if a SyntaxError is raised
                self.safe_execfile(err.filename,self.user_ns)
            except:
                self.showtraceback()
            else:
                try:
                    f = open(err.filename)
                    try:
                        # This should be inside a display_trap block and I
                        # think it is.
                        sys.displayhook(f.read())
                    finally:
                        f.close()
                except:
                    self.showtraceback()
Example #8
0
 def test_init_pprint(self):
     self.assertEqual(sys.displayhook.__name__, 'pprint_callback')
     with patch('sys.stdout', new_callable=StringIO) as mock_stdout:
         sys.displayhook(42)
         sys.displayhook({'spam': 42})
         self.assertEquals(
             sys.stdout.getvalue(), ("%s\n"
                                     "{%s42}\n") %
             (pythonrc.blue('42'), pythonrc.purple("'spam': ")))
Example #9
0
 def pre_prompt(self, ip):
     ec = self.shell.execution_count
     try:
         for num, result in self.delayed:
             self.shell.execution_count = num
             sys.displayhook(result)
         self.delayed = []
     finally:
         self.shell.execution_count = ec
Example #10
0
    def preprocess_dataframe(self):
        df = self.raw_df
        # TotalCharges must be numeric
        df.TotalCharges = pd.to_numeric(df.TotalCharges, errors="coerce")
        # Fill NAs with 0
        df.TotalCharges = df.TotalCharges.fillna(0)
        # Let’s make it uniform by lowercasing everything and replacing spaces with underscores
        df.columns = df.columns.str.lower().str.replace(' ', '_')
        # Our target Column Churn should be numeric as well
        df.churn = (df.churn == "Yes").astype(int)
        displayhook(df.head().T)
        print(f'Churn Values:{df.churn.value_counts()}')

        return df
Example #11
0
def pretty_print(thing):
    if isinstance(thing, str):
        py_print(thing)
    elif not isinstance(thing, (Mapping, Sequence)) and isinstance(thing, Iterable):
        sliced = []
        for n, item in enumerate(thing):
            if n < 5:
                sliced.append(item)
            else:
                sliced.append(raw('...'))
                break
        py_print("<iterable {}>".format(repr(sliced)))
    else:
        sys.displayhook(thing)
Example #12
0
 def main(argv=None):
     parser = ArgumentParser()
     parser.add_argument('function')
     parser.add_argument('args', nargs=REMAINDER)
     args = parser.parse_args(argv)
     try:
         func = pydoc.locate(args.function)
     except pydoc.ErrorDuringImport as exc:
         raise exc.value from None
     if func is None:
         raise ImportError('Failed to locate {!r}'.format(args.function))
     argparse_kwargs = (
         {'prog': ' '.join(sys.argv[:2])} if argv is None else {})
     retval = run(func, argv=args.args, argparse_kwargs=argparse_kwargs)
     sys.displayhook(retval)
Example #13
0
def pretty_print(thing):
    if isinstance(thing, str):
        py_print(thing)
    elif not isinstance(thing,
                        (Mapping, Sequence)) and isinstance(thing, Iterable):
        sliced = []
        for n, item in enumerate(thing):
            if n < 5:
                sliced.append(item)
            else:
                sliced.append(raw('...'))
                break
        py_print("<iterable {}>".format(repr(sliced)))
    else:
        sys.displayhook(thing)
Example #14
0
def pretty_print(thing):
    if isinstance(thing, str):
        _write(thing)
        _write('\n')
    elif not isinstance(thing, (Mapping, Sequence)) and isinstance(thing, Iterable):
        sliced = []
        for n, item in enumerate(thing):
            if n < 5:
                sliced.append(repr(item))
            else:
                sliced.append('...')
                break
        py_print("<iterable [{}]>".format(', '.join(sliced)))
    else:
        sys.displayhook(thing)
    return thing
Example #15
0
def test_init_python_printing():
    original_display_hook = sys.displayhook

    def new_display_hook(*_):
        new_display_hook.called = True

    sys.displayhook = new_display_hook

    try:
        _init_python_printing(str)
        # check for correct overwriting of displayhook
        assert getattr(sys.displayhook, 'is_sympy_displayhook', False)
        # call displayhook with none-sympy object
        sys.displayhook(object())
        # check whether original display hook has been called
        assert getattr(new_display_hook, 'called', False)
    finally:
        sys.displayhook = original_display_hook
Example #16
0
def showcmd(args, stdin=None):
    """usage: showcmd [-h|--help|cmd args]

    Displays the command and arguments as a list of strings that xonsh would
    run in subprocess mode. This is useful for determining how xonsh evaluates
    your commands and arguments prior to running these commands.

    optional arguments:
      -h, --help            show this help message and exit

    example:
      >>> showcmd echo $USER can't hear "the sea"
      ['echo', 'I', "can't", 'hear', 'the sea']
    """
    if len(args) == 0 or (len(args) == 1 and args[0] in {'-h', '--help'}):
        print(showcmd.__doc__.rstrip().replace('\n    ', '\n'))
    else:
        sys.displayhook(args)
Example #17
0
def showcmd(args, stdin=None):
    """usage: showcmd [-h|--help|cmd args]

    Displays the command and arguments as a list of strings that xonsh would
    run in subprocess mode. This is useful for determining how xonsh evaluates
    your commands and arguments prior to running these commands.

    optional arguments:
      -h, --help            show this help message and exit

    example:
      >>> showcmd echo $USER can't hear "the sea"
      ['echo', 'I', "can't", 'hear', 'the sea']
    """
    if len(args) == 0 or (len(args) == 1 and args[0] in {"-h", "--help"}):
        print(showcmd.__doc__.rstrip().replace("\n    ", "\n"))
    else:
        sys.displayhook(args)
Example #18
0
	def excepthook(_, error, __):
		if (
			type(error) is not SyntaxError
			or error.lineno != 1  # we don't have all the code
			or error.text is None
		):
			return sys.__excepthook__(type(error), error, error.__traceback__)

		try:
			result = ie_eval(error.text, globals)
		except SyntaxError:
			try:
				ie_exec(error.text, globals)
			except BaseException as error:
				return sys.__excepthook__(type(error), error, error.__traceback__)
		except BaseException as error:
			return sys.__excepthook__(type(error), error, error.__traceback__)
		else:
			sys.displayhook(result)
Example #19
0
def pyevalAndDisplay(expr, *args, **kw):
    """
    Evaluate expr and args, then display the result with sys.displayhook.

    If the displayhook keyword is given and None, sys.displayhook is not
    modified.  Otherwise it is temporarily assigned to sys.displayhook
    and restored before returning.  It not given, it defaults to
    pyeval.display.displayPretty.
    """
    displayhook = kw.pop('displayhook', displayPretty)
    if len(kw) > 0:
        raise TypeError('pyevalAndDisplay() got unexpected keywords: %r' % (kw.keys(),))

    if displayhook is None:
        displayhook = sys.displayhook

    with patch(sys, 'displayhook', displayhook):
        result = pyeval(expr, *args)
        sys.displayhook(result)
    def scale_graph_show(self, col_name, process, df_old, df_new):
        self.win = pg.GraphicsLayoutWidget(show=True)
        self.win.resize(1200, 760)
        self.win.setWindowTitle(col_name + " " + str(process))
        plt1 = self.win.addPlot(title='Before ')
        plt2 = self.win.addPlot(title='Processed ')

        s1 = pg.ScatterPlotItem(pen=pg.mkPen(None),
                                brush=pg.mkBrush(255, 255, 255, 120))
        pos = df_old[col_name]
        s1.addPoints(x=pos.index, y=pos[:])
        plt1.addItem(s1)

        s2 = pg.ScatterPlotItem(pen=pg.mkPen(None),
                                brush=pg.mkBrush(255, 255, 255, 120))
        pos2 = df_new[col_name]
        s2.addPoints(x=pos2.index, y=pos2[:])
        plt2.addItem(s2)

        sys.displayhook(self.win)
Example #21
0
    def shell_substitute_run_ast_nodes(
                self,
                nodelist, cellname, interactivity='last_expr',
                compiler=compile, # ignored
                result=None,
            ):
        """
        Replaces get_ipython().run_ast_nodes
        """
        if not nodelist:
            return

        try:
            result_val = self.exec_ast_nodes(nodelist)
            if interactivity == 'last_expr':
                sys.displayhook(result_val)
            return False
        except:
            if result:
                result.error_before_exec = sys.exc_info()[1]
            self.shell.showtraceback()
            return True
Example #22
0
    def perform_EDA(self, df):
        # Check for null values
        displayhook(df.isnull().sum())
        # Check number of unique values on each categorical columns
        displayhook(df[self.categorical].nunique())
        # Churn Rates:  calculate the risk for each category
        global_mean = round(df.churn.mean(), 3)
        print(f'global churn mean:{global_mean}')

        for col in self.categorical:
            df_group = df.groupby(by=col).churn.agg(['mean'])
            df_group['diff'] = df_group['mean'] - global_mean
            df_group['risk'] = df_group['mean'] / global_mean
            displayhook(df_group)

        def calculate_mi(series):
            return mutual_info_score(series, df.churn)

        # Mutual info
        df_mi = df[self.categorical].apply(calculate_mi)
        df_mi = df_mi.sort_values(ascending=False).to_frame(name='MI')
        displayhook(df_mi)
        # Correlation
        displayhook(df[self.numerical].corrwith(df.churn))
Example #23
0
    def test_pprint_compact(self):
        with patch('sys.stdout', new_callable=StringIO) as mock_stdout:

            # - test compact pprint-ing with 80x25 terminal
            with patch.object(pythonrc.subprocess, 'check_output',
                              return_value='25 80'):
                sys.displayhook(list(range(22)))
                self.assertIn('20, 21]', sys.stdout.getvalue())
                sys.displayhook(list(range(23)))
                self.assertIn('21,\n 22]', sys.stdout.getvalue())

            # - test compact pprint-ing with resized 100x25 terminal
            with patch.object(pythonrc.subprocess, 'check_output',
                              return_value=('25 100')):
                sys.displayhook(list(range(23)))
                self.assertIn('21, 22]', sys.stdout.getvalue())
Example #24
0
 def eval(self, id, control_vals, displayhook):
     f, controls = self._interacts[id]
     assert len(controls) == len(control_vals)
     displayhook(f(*[c.eval(v) for c, v in zip(controls, control_vals)]))
Example #25
0
 def describe_data(self):
     print(f'number of rows:{len(self.raw_df)}')
     print(f'types :{self.raw_df}')
     displayhook(self.raw_df.head().T)
Example #26
0
# print(sys.exit(2))  # 打印程序返回代码
print(sys.version)  # 打印python版本
print(sys.maxsize)  # 打印最大值
print(sys.path)  # 返回当前PYTHONPATH环境变量
print(sys.platform)  # 返回操作系统平台名称
print(sys.stdout.write("inpu9t"))  # 返回标准输出长度
# print(sys.stdin.readlin()[:-1])  # 标准输入,并分片取开头到倒数第一个(不包含)的内容
print(sys.modules.keys())  # 打印所有模块名
print(sys.modules.values())  # 打印所有模块位置
print(
    sys.exc_info())  # 获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息
print(sys.hexversion)  # 获取十六进制的版本值
print(sys.api_version)  # 获取Cpython API版本
print(sys.version_info)  # 打印版本详细信息
print(
    sys.displayhook(2)
)  # 如果value非空,这个函数会把他输出到sys.stdout,并且将他保存进__builtin__._.指在python的交互式解释器里,’_’ 代表上次你输入得到的结果,hook是钩子的意思,将上次的结果钩过来
print(sys.getdefaultencoding())  # 获取当前默认编码格式
print(sys.getfilesystemencoding())  # 获取文件系统编码
print(sys.builtin_module_names)  # 打印内置模块名
print(sys.executable)  # 打印python解释权程序路径
print(sys.getprofile())
print(sys.getallocatedblocks())
# print(sys.copyright)  # 打印python版权信息
print(sys.byteorder
      )  # 本地字节规则的指示器,big-endian平台的值是’big’,little-endian平台的值是’little’
# print(sys.exc_value)
print(sys.stdin)  # 标准输入
print(sys.stdout)  # 标准输出
print(sys.stderr)  # 标准错误输出
print(sys.maxunicode)  #   打印最大unicode值
Example #27
0
    def evaluate(self, statement, session, printer=None, stream=None):
        """Evaluate the statement in sessions's globals. """
        # the Python compiler doesn't like network line endings
        source = statement.replace('\r\n', '\n').rstrip()

        # split source code into 'exec' and 'eval' parts
        exec_source, eval_source = self.split(source)

        try:
            self.compile(eval_source, 'eval')
        except (OverflowError, SyntaxError, ValueError):
            exec_source, eval_source = source, None

        if exec_source is not None:
            exec_source += '\n'
        if eval_source is not None:
            eval_source += '\n'

        # create a dedicated module to be used as this statement's __main__
        statement_module = new.module('__main__')

        # use this request's __builtin__, since it changes on each request.
        # this is needed for import statements, among other things.
        import __builtin__
        statement_module.__builtin__ = __builtin__

        # create customized display hook
        stringify_func = printer or sstr

        def displayhook(arg):
            if arg is not None:
                __builtin__._ = None
                print stringify_func(arg)
                __builtin__._ = arg

        old_displayhook = sys.displayhook
        sys.displayhook = displayhook

        # swap in our custom module for __main__. then unpickle the session
        # globals, run the statement, and re-pickle the session globals, all
        # inside it.
        old_main = sys.modules.get('__main__')

        try:
            sys.modules['__main__'] = statement_module
            statement_module.__name__ = '__main__'

            # re-evaluate the unpicklables
            for code in session.unpicklables:
                exec code in statement_module.__dict__

            old_globals = dict(statement_module.__dict__)

            # re-initialize the globals
            session_globals_dict = session.globals_dict()

            for name, val in session_globals_dict.items():
                try:
                    statement_module.__dict__[name] = val
                except:
                    session.remove_global(name)

            # re-initialize '_' special variable
            __builtin__._ = session_globals_dict.get('_')

            # run!
            offset = 0

            try:
                old_stdout = sys.stdout
                old_stderr = sys.stderr

                try:
                    if stream is not None:
                        sys.stdout = stream
                        sys.stderr = stream

                    if exec_source is not None:
                        try:
                            exec_code = self.compile(exec_source, 'exec')
                        except (OverflowError, SyntaxError, ValueError):
                            return self.error(stream, self.syntaxerror())

                        eval(exec_code, statement_module.__dict__)

                    if eval_source is not None:
                        if exec_source is not None:
                            offset = len(exec_source.split('\n'))

                        result = eval(eval_source, statement_module.__dict__)
                        sys.displayhook(result)
                finally:
                    sys.stdout = old_stdout
                    sys.stderr = old_stderr
            except:
                return self.error(stream, self.traceback(offset))

            # extract the new globals that this statement added
            new_globals = {}

            for name, val in statement_module.__dict__.items():
                if name not in old_globals or val != old_globals[name]:
                    new_globals[name] = val

            if True in [isinstance(val, UNPICKLABLE_TYPES) for val in new_globals.values()]:
                # this statement added an unpicklable global. store the statement and
                # the names of all of the globals it added in the unpicklables
                source = ""

                if exec_source:
                    source += exec_source
                if eval_source:
                    source += eval_source

                source += "\n"

                session.add_unpicklable(source, new_globals.keys())
                logging.debug('Storing this statement as an unpicklable.')
            else:
                # this statement didn't add any unpicklables. pickle and store the
                # new globals back into the datastore
                for name, val in new_globals.items():
                    if not name.startswith('__'):
                        try:
                            session.set_global(name, val)
                        except (TypeError, pickle.PicklingError):
                            pass

            # save '_' special variable into the datastore
            val = getattr(__builtin__, '_', None)

            try:
                session.set_global('_', val)
            except (TypeError, pickle.PicklingError):
                session.set_global('_', None)
        finally:
            sys.modules['__main__'] = old_main
            sys.displayhook = old_displayhook

            try:
                del __builtin__._
            except AttributeError:
                pass

        session.put()
def finished(outfile):
    """Print a closing message"""
    sys.displayhook("Fixed pseudoscaffold can be found at " + os.getcwd() + "/" + outfile)
    sys.exit(0)
Example #29
0
    def evaluate(self, source):
        """Evaluate a piece of Python source code. """
        source = source.replace('\r', '').rstrip()

        # XXX: make all this SIGINT aware

        if '\n' in source:
            exec_source, eval_source = self.split(source)
        else:
            exec_source, eval_source = None, source

        eval_source += '\n'

        try:
            self.compile(eval_source, 'eval')
        except (OverflowError, SyntaxError, ValueError):
            if '\n' not in source and self.is_inspect(source):
                return self.inspect(source)

            exec_source = source
            eval_source = None

        try:
            del self.namespace['__plots__']
        except KeyError:
            pass

        interrupted = False
        traceback = False
        result = None

        start = time.clock()

        try:
            if exec_source is not None:
                try:
                    exec_code = self.compile(exec_source, 'exec')
                except (OverflowError, SyntaxError, ValueError):
                    traceback = self.syntaxerror()
                    eval_source = None
                else:
                    eval(exec_code, self.namespace)

            if eval_source is not None:
                result = eval(eval_source, self.namespace)
                sys.displayhook(result)
        except SystemExit:
            raise
        except KeyboardInterrupt:
            traceback = self.traceback()
            interrupted = True
        except:
            traceback = self.traceback()

        end = time.clock()

        try:
            plots = self.namespace['__plots__']
        except KeyError:
            plots = []

        self.index += 1

        if result is not None:
            self.namespace['_%d' % self.index] = result

            self.namespace['___'] = self.namespace.get('__')
            self.namespace['__'] = self.namespace.get('_')
            self.namespace['_'] = result

        result = {
            'source': source,
            'index': self.index,
            'time': end - start,
            'plots': plots,
            'traceback': traceback,
            'interrupted': interrupted,
        }

        return result
Example #30
0
# ............................................
sys.byteorder   # An indicator of the native byte order. This will have the value 'big' on big-endian (most-significant byte first) platforms, and 'little' on little-endian (least-significant byte first) platforms.
# ............................................
sys.builtin_module_names    # A tuple of strings giving the names of all modules that are compiled into this Python interpreter.
# ............................................
sys.call_tracing(func, args)    # Call func(*args), while tracing is enabled. The tracing state is saved, and restored afterwards. 
# ............................................
sys.copyright   # A string containing the copyright pertaining to the Python interpreter.
# ............................................
sys._clear_type_cache()     # Clear the internal type cache. The type cache is used to speed up attribute and method lookups.
# ............................................
sys._current_frames() 
# ............................................
sys.dllhandle   # Integer specifying the handle of the Python DLL. Availability: Windows.
# ............................................
sys.displayhook(value)  # If value is not None, this function prints it to sys.stdout, and saves it in __builtin__._.
# ............................................
sys.dont_write_bytecode 
# If this is true, Python won’t try to write .pyc or .pyo files on the import of source modules. 
# This value is initially set to True or False depending on the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable, 
# but you can set it yourself to control bytecode file generation.
# ............................................
sys.excepthook(type, value, traceback)  # This function prints out a given traceback and exception to sys.stderr.
# ............................................
sys.__displayhook__ 
sys.__excepthook__  # These objects contain the original values of displayhook and excepthook at the start of the program.
# ............................................
sys.exc_info()  # This function returns a tuple of three values that give information about the exception that is currently being handled
# ............................................
sys.exc_clear()     # This function clears all information relating to the current or last exception that occurred in the current thread
# ............................................
Example #31
0
    def loop(self):
        while True:
            try:
                if self.readMore:
                    sys.stdout.write("... ")
                    sys.stdout.flush()
                    self.single_input += sys.stdin.readline()
                else:
                    sys.stdout.write(">>> ")
                    sys.stdout.flush()
                    self.single_input = sys.stdin.readline()

                input_stream = antlr4.InputStream(self.single_input)

                # Instantiate and run generated lexer
                self.lexer = CustomLexer(input_stream)
                self.tokens = antlr4.CommonTokenStream(self.lexer)

                # Setting up error handling stuff
                error_handler = CustomErrorStrategy()
                error_listener = CustomErrorListener()
                buffered_errors = BufferedErrorListener()
                error_listener.addDelegatee(buffered_errors)

                # Run parser and set error handler
                self.parser = TinyPyParser(self.tokens)
                self.parser._errHandler = error_handler

                # Remove default terminal error listener & and our own
                self.parser.removeErrorListeners()
                self.parser.addErrorListener(error_listener)

                # Parse input
                parse_tree = self.parser.single_input()

                # Determine what to do next
                if error_listener.eof_received:
                    print()
                    exit(0)
                elif error_listener.input_unfinished or self.lexer.opened > 0:
                    # User has not finished his input yet, read the next line and repeat
                    self.readMore = True
                    continue
                elif error_listener.errors_encountered > 0:
                    # Errors encountered, start over
                    print(buffered_errors.buffer)
                    self.readMore = False
                    continue
                else:
                    # Successfully parsed the input, next time start over
                    self.readMore = False

                # Build a flattened syntax tree
                cst = CST.CstFiltered(tree=parse_tree)

                # Print some stuff... (if needed)
                if self.args.cst:
                    print(cst)

                if self.args.parse_tree:
                    parseTreeString = Trees.toStringTree(parse_tree, recog=self.parser)
                    print(parseTreeString)

                # Evaluate it...
                visitor = CustomVisitor()
                ast = visitor.visitSingle_input(parse_tree)
                if ast == None:
                    continue

                if self.args.parse_only:
                    continue

                results = ast.eval()

                #
                # ast.eval() returns list of statements; loop through them and print
                #
                if results != None:
                    for statement in results:
                        if statement != None and not isinstance(statement, ControlFlowMark):
                            sys.displayhook(statement)

                #if results != None:
                #    sys.displayhook(results)

            except KeyboardInterrupt as e:
                print("")
                exit(0)
            except antlr4.RecognitionException as e:
                print("Caught" + str(e) )
            except runtime.Errors.BaseRuntimeException as e:
                print(e.__class__.__name__ + ": " + str(e))
            except SystemExit as e:
                sys.exit(e)
            except BaseException as e:
                print(e.__class__.__name__ + ": " + str(e))
# -*- coding:utf-8 -*-
from sympy import pprint
from sympy import Symbol
from sympy.matrices import *
from random import *
import sys
sys.displayhook(pprint)
import time
import numpy as np
import matplotlib.pyplot as plt


print '''
****************************************************************************
6. Estime a complexidade do algoritmo de solução de sistemas lineares do pacote computacional de sua
preferência: registre os tempos que o pacote levou para resolver sistemas aleatórios nxn, com n =
16; 32; 64; 128; 256; 512; 1024; 2048. Faça um gráfico do log do número de colunas contra o log dos tempos
registrados. O algoritmo do pacote tem complexidade inferior a O(nˆ3)?
'''

def random_ints(num, lower=-100, upper=100):
    return [randrange(lower,upper+1) for i in range(num)]

def geraMatriz(n, l=-100, u=100):
    return Matrix(n, n, random_ints(n**2, l, u))

tempoGeracao = {}
tempoDeterminante = {}
for n in range(4,11):
    
    ''' Contagem de tempo para criação das matrizes '''
Example #33
0
def run(func=None, args=None, param_types=dict(), cli_result=False):
    """Invokes a function using CLI arguments
    
    func: Defaults to __main__.main
    args: Defaults to sys.argv[1:]
    param_types:  This mapping extends and overrides any "param_types"
        attribute of "func". The parameter and attribute both map parameter
        keywords to functions taking an argument string and returning the
        parameter's data type. By default, arguments are passed to "func" as
        unconverted strings. The special keywords "*" and "**" apply to any
        excess positional and keyword arguments.
    cli_result: If true, the function or context manager result will be
        displayed, or will have a method invoked as a subcommand. A
        subcommand is invoked by passing an extra positional argument.
    
    If the function has a "cli_context" attribute set to True, the return
    value is entered as a context manager. Any further return value handling
    uses the result returned when entering the context manager.
    
    If the function has the "subcommand_class" attribute set, a subcommand
    will be expected, and will invoke a method listed in the class on the
    function or context manager result.
    
    The CLI option names are the parameter keywords, and hyphenated (-)
    option names are interpreted as using underscores (_) instead. Options
    may be prefixed with either a single (-) or a double (--) dash. An
    option's argument may be separated by an equals sign (=) or may be in a
    separate argument word.
    
    For parameters that default to "False", the command option does not take
    an argument and sets the corresponding "func" argument to "True". For
    parameters that default to an empty list, tuple or set, the command
    option may be given multiple times and are combined into a sequence.
    
    Raises SystemExit() when the function was not actually run [TODO: when
    appropriate]
    """
    
    """Similar implementations:
    https://pypi.python.org/pypi/clize: adapts the function in two steps
    http://dev.kylealanhale.com/wiki/projects/quicli: very decorator-happy,
        with much "argparse" API and little automatic introspection
    """
    
    [func, sig, keywords, param_types] = prepare(func, param_types)
    varpos = param_kind(sig, Parameter.VAR_POSITIONAL)
    varkw = param_kind(sig, Parameter.VAR_KEYWORD)
    
    if args is None:
        args = sys.argv[1:]
    
    auto_help = list()
    if varkw is None:
        for opt in ("help", "h"):
            if opt not in keywords:
                auto_help.append(opt)
                param = Parameter(opt, Parameter.KEYWORD_ONLY, default=False)
                keywords[opt] = param
    
    if sig:
        pos_kinds = (
            Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD)
        pos_iter = (param for
            param in sig.parameters.values() if param.kind in pos_kinds)
    else:
        pos_iter = iter(())
    
    positional = list()
    opts = dict()
    args = iter(args)
    endopts = False
    while True:
        arg = next(args, None)
        if arg is None:
            break
        if arg == "--":
            endopts = True
            continue
        
        if not endopts and arg.startswith("-") and arg != "-":
            # Allow options to be preceded by two dashes
            if arg.startswith("--"):
                opt = arg[2:]
            else:
                opt = arg[1:]
            
            # Allow argument to be separated by equals sign
            try:
                [opt, arg] = opt.split("=")
            except ValueError:
                arg = None
            
            opt = opt.replace("-", "_")
            param = keywords.get(opt)
            if not param:
                if varkw is None:
                    raise SystemExit("Unexpected option {opt!r}".
                        format(**locals()))
                param = varkw
            
            if param.kind != param.VAR_KEYWORD and noarg_param(param):
                if arg is not None:
                    raise SystemExit("Option {opt!r} takes no argument".
                        format(**locals()))
                opts[opt] = True
            
            else:
                if arg is None:
                    try:
                        arg = next(args)
                    except StopIteration:
                        if sig:
                            msg = "Option {!r} requires an argument"
                            msg = msg.format(opt)
                        else:
                            msg = "Keyword options require arguments"
                        raise SystemExit(msg)
                
                arg = convert(param_types, param, arg)
                
                if param.kind != param.VAR_KEYWORD and multi_param(param):
                    opts.setdefault(opt, list()).append(arg)
                else:
                    opts[opt] = arg
        
        else:
            param = next(pos_iter, varpos)
            if (cli_result or hasattr(func, "subcommand_class")) and (
            param is varpos or param.default is not Parameter.empty):
                break
            if param is not None:
                arg = convert(param_types, param, arg)
            positional.append(arg)
    
    if any(opts.get(help, False) for help in auto_help):
        help(func, param_types=param_types)
        return
    
    if sig:
        try:
            sig.bind(*positional, **opts)
        except TypeError as err:
            raise SystemExit(err)
    
    result = func(*positional, **opts)
    with ExitStack() as cleanup:
        if getattr(func, "cli_context", False):
            result = cleanup.enter_context(result)
        if not cli_result and not hasattr(func, "subcommand_class"):
            return result
        if arg is None:
            sys.displayhook(result)
            return
        
        if arg is None:
            all = getattr(result, "__all__", None)
            if all is None:
                funcs = dir(result)
            else:
                funcs = all
            heading = False
            for name in funcs:
                if all is None and name.startswith("_"):
                    continue
                func = getattr(result, name)
                if not callable(func):
                    continue
                if not heading:
                    sys.stderr.write("public subcommands:\n")
                    heading = True
                sys.stderr.write(name)
                [summary, _] = splitdoc(inspect.getdoc(func))
                if summary:
                    sys.stderr.writelines((": ", summary))
                sys.stderr.write("\n")
            if not heading:
                sys.stderr.write("no public subcommands found\n")
        else:
            try:
                func = getattr(result, arg)
            except AttributeError as err:
                err = "Invalid subcommand {!r}: {}".format(arg, err)
                raise SystemExit(err)
            return run(func, args, cli_result=cli_result)
Example #34
0
print(sys.modules)  # 打印系统所有模块,字典形式返回
# print(sys.exit(2))  # 打印程序返回代码
print(sys.version)  # 打印python版本
print(sys.maxsize)  # 打印最大值
print(sys.path)  # 返回当前PYTHONPATH环境变量
print(sys.platform)  # 返回操作系统平台名称
print(sys.stdout.write("inpu9t"))  # 返回标准输出长度
# print(sys.stdin.readlin()[:-1])  # 标准输入,并分片取开头到倒数第一个(不包含)的内容
print(sys.modules.keys())  # 打印所有模块名
print(sys.modules.values())  # 打印所有模块位置
print(sys.exc_info())  # 获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息
print(sys.hexversion)  # 获取十六进制的版本值
print(sys.api_version)  # 获取Cpython API版本
print(sys.version_info)  # 打印版本详细信息
print(
    sys.displayhook(2)
)  # 如果value非空,这个函数会把他输出到sys.stdout,并且将他保存进__builtin__._.指在python的交互式解释器里,’_’ 代表上次你输入得到的结果,hook是钩子的意思,将上次的结果钩过来
print(sys.getdefaultencoding())  # 获取当前默认编码格式
print(sys.getfilesystemencoding())  # 获取文件系统编码
print(sys.builtin_module_names)  # 打印内置模块名
print(sys.executable)  # 打印python解释权程序路径
print(sys.getprofile())
print(sys.getallocatedblocks())
# print(sys.copyright)  # 打印python版权信息
print(sys.byteorder)  # 本地字节规则的指示器,big-endian平台的值是’big’,little-endian平台的值是’little’
# print(sys.exc_value)
print(sys.stdin)  # 标准输入
print(sys.stdout)  # 标准输出
print(sys.stderr)  # 标准错误输出
print(sys.maxunicode)  #   打印最大unicode值
Example #35
0
def test_init_printing(capsys):
    init_printing()
    sys.displayhook(sqrt(5))
    assert capsys.readouterr().out == 'sqrt(5)\n'
    sys.displayhook('xyz')
    assert capsys.readouterr().out == "'xyz'\n"
    sys.displayhook(None)
    assert capsys.readouterr().out == ''

    init_printing(pretty_print=True, no_global=True)
    sys.displayhook(sqrt(5))
    assert capsys.readouterr().out == \
        """\
  ___\n\
╲╱ 5 \n"""
    sys.displayhook(theta)
    assert capsys.readouterr().out == 'θ\n'

    init_printing(pretty_print=True, use_unicode=False, no_global=True)
    sys.displayhook(theta)
    assert capsys.readouterr().out == 'theta\n'

    init_printing(pretty_print=True, order='grevlex', no_global=True)
    sys.displayhook(y + x + y**2 + x**2)
    assert capsys.readouterr().out == \
        """\
Example #36
0
 def display(self):
     return sys.displayhook(self.value)
Example #37
0
# -*- coding:utf-8 -*-
from sympy import pprint
from sympy import Symbol
from sympy.matrices import *
import sys
sys.displayhook(pprint)

print '''
****************************************************************************
Exercício 01:
Asdrúbal acabou de receber um prêmio de 25 mil reais e deseja investir o 
dinheiro recebido. Ele deseja aplicar 6 mil reais em CDB, 3 mil reais em 
moeda estrangeira e 16 mil em ações. No entanto, no banco onde Asdrúbal 
pensa em investir só existe as seguintes opções de carteiras: 

opções de investimento Composição em cada quota
Carteira A 2 reais em CDB, 2 reais em moeda estrangeira, 2 reais em ações
Carteira B 1 real em CDB, nada em moeda estrangeira e 2 reais em ações
Carteira C 1 real em CDB, 1 real em moeda estrangeira e 3 reais em ações

(a) Mostre que as carteiras formam uma base do espaço das aplicações.

(b) Descreva a distribuição das aplicações desejada por Asdrúbal na base 
das carteiras.

(c) Quantas quotas de cada carteira Asdrúbal deve adquirir para compor a 
aplicação que deseja?

'''

print '''
Example #38
0
    def evaluate(self, statement, session, printer=None, stream=None):
        # def evaluate(self, statement, printer=None, stream=None):
        """Evaluate the statement in sessions's globals. """
        # the Python compiler doesn't like network line endings
        source = statement.replace('\r\n', '\n').rstrip()

        # allow spaces before one-liners (to emulate Python shell's behaviour)
        if '\n' not in source:
            source = source.lstrip()

        try:
            # check for a SyntaxError now; this way the user will see their
            # original statement and not the transformed one
            ast.parse(source)
        except SyntaxError:
            return self.error(stream, self.syntaxerror())

        # convert int to Integer (1/2 -> Integer(1)/Integer(2))
        # source = int_to_Integer(source)
        # print(getframeinfo(currentframe()).lineno, source)

        # split source code into 'exec' and 'eval' parts
        exec_source, eval_source = self.split(source)
        # print(getframeinfo(currentframe()).lineno, exec_source, eval_source)

        try:
            self.compile(eval_source, 'eval')
        except (OverflowError, SyntaxError, ValueError):
            exec_source, eval_source = source, None
        # print(getframeinfo(currentframe()).lineno, exec_source, eval_source)

        if exec_source is not None:
            exec_source += '\n'
        if eval_source is not None:
            eval_source += '\n'

        # create a dedicated module to be used as this statement's __main__
        statement_module = types.ModuleType('__main__')

        # use this request's __builtin__, since it changes on each request.
        # this is needed for import statements, among other things.
        import builtins
        statement_module.__builtins__ = __builtins__

        # create customized display hook
        stringify_func = printer

        def displayhook(arg):
            if arg is not None:
                __builtins__['_'] = None
                # print(stringify_func(arg))
                print(arg)
                __builtins__['_'] = arg

        old_displayhook = sys.displayhook
        sys.displayhook = displayhook

        # swap in our custom module for __main__. then unpickle the session
        # globals, run the statement, and re-pickle the session globals, all
        # inside it.
        old_main = sys.modules.get('__main__')

        try:
            old_globals = {}
            sys.modules['__main__'] = statement_module
            statement_module.__name__ = '__main__'

            # re-evaluate the unpicklables
            for code in session['unpicklables']: ##
                exec(code, statement_module.__dict__)
                exec(code, old_globals)

            # re-initialize the globals
            session_globals_dict = globals_dict(session)

            for name, val in list(session_globals_dict.items()):
                try:
                    statement_module.__dict__[name] = val
                    old_globals[name] = val
                except:
                    remove_global(session, name)

            # re-initialize '_' special variable
            __builtins__['_'] = session_globals_dict.get('_')
            # print(getframeinfo(currentframe()).lineno, __builtins__['_'])

            # run!
            offset = 0

            try:
                old_stdout = sys.stdout
                old_stderr = sys.stderr

                try:
                    if stream is not None:
                        sys.stdout = stream
                        sys.stderr = stream

                    if exec_source is not None:
                        try:
                            exec_code = self.compile(exec_source, 'exec')
                        except (OverflowError, SyntaxError, ValueError):
                            return self.error(stream, self.syntaxerror())

                        eval(exec_code, statement_module.__dict__)

                    # print('PR eval', eval_source, exec_source)
                    # if '=' not in exec_source and 'print' not in exec_source and 'import' not in exec_source:
                    # eval_source = exec_source
                    if eval_source is not None and 'print' not in eval_source:
                        if exec_source is not None:
                            offset = len(exec_source.split('\n'))

                        try:
                            result = eval(eval_source, statement_module.__dict__)
                            sys.displayhook(result)
                        except:
                            pass
                finally:
                    sys.stdout = old_stdout
                    sys.stderr = old_stderr
            # except DeadlineExceededError:
            #     logging.debug("is deadlineexceedederror in evaluate")
            #     raise DeadlineExceededError
            except:
                return self.error(stream, self.traceback(offset))

            # extract the new globals that this statement added
            new_globals = {}

            for name, val in list(statement_module.__dict__.items()):
                try:
                    if name not in old_globals or not val == old_globals[name]:
                    # if name not in old_globals:
                    #     if val != old_globals[name]:
                        new_globals[name] = val

                except:
                    comparison = val == old_globals[name]
                    equal_arrays = comparison.all()
                    if name not in old_globals or not equal_arrays:
                        new_globals[name] = val

            for name in old_globals:
                if name not in statement_module.__dict__:
                    remove_global(session, name)

            if True in [isinstance(val, UNPICKLABLE_TYPES) for val in list(new_globals.values())]:
                # this statement added an unpicklable global. store the statement and
                # the names of all of the globals it added in the unpicklables
                source = ""

                if exec_source:
                    source += exec_source
                if eval_source:
                    source += eval_source

                source += "\n"

                add_unpicklable(session, source, list(new_globals.keys()))
                logging.debug('Storing this statement as an unpicklable.')
            else:
                # this statement didn't add any unpicklables. pickle and store the
                # new globals back into the datastore
                for name, val in list(new_globals.items()):
                    if not name.startswith('__'):
                        try:
                            set_global(session, name, val)
                        except (TypeError, pickle.PicklingError):
                            pass

            # save '_' special variable into the datastore
            val = __builtins__['_']
            # print(getframeinfo(currentframe()).lineno, 'val', val)

            try:
                set_global(session, '_', val)
            except (TypeError, pickle.PicklingError):
                set_global(session, '_', None)
        finally:
            sys.modules['__main__'] = old_main
            sys.displayhook = old_displayhook

            try:
                del __builtins__['_']
            except AttributeError:
                pass

        try:
            # session.put()
            session.modified = True
        # except RequestTooLargeError:
        except:
            stream.truncate(0)  # clear output
            self.error(stream, ('Unable to process statement due to its excessive size.',))
Example #39
0
    def generate_completions(
        completion_context, old_completer_args, trace: bool
    ) -> tp.Iterator[tp.Tuple[Completion, int]]:
        for name, func in XSH.completers.items():
            try:
                if is_contextual_completer(func):
                    if completion_context is None:
                        continue
                    out = func(completion_context)
                else:
                    if old_completer_args is None:
                        continue
                    out = func(*old_completer_args)
            except StopIteration:
                # completer requested to stop collecting completions
                break
            except Exception as e:
                print_exception(
                    f"Completer {func.__name__} raises exception when gets "
                    f"old_args={old_completer_args[:-1]} / completion_context={completion_context!r}:\n"
                    f"{type(e)} - {e}"
                )
                continue

            completing_contextual_command = (
                is_contextual_completer(func)
                and completion_context is not None
                and completion_context.command is not None
            )
            if isinstance(out, cabc.Sequence):
                res, lprefix = out
                custom_lprefix = True
            else:
                res = out
                custom_lprefix = False
                if completing_contextual_command:
                    lprefix = len(completion_context.command.prefix)
                elif old_completer_args is not None:
                    lprefix = len(old_completer_args[0])
                else:
                    lprefix = 0

            if res is None:
                continue

            items = []
            for comp in res:
                comp = Completer._format_completion(
                    comp,
                    completion_context,
                    completing_contextual_command,
                    lprefix or 0,
                    custom_lprefix,
                )
                items.append(comp)
                yield comp

            if not items:  # empty completion
                continue

            if trace:
                print(
                    f"TRACE COMPLETIONS: Got {len(items)} results"
                    f" from {'' if is_exclusive_completer(func) else 'non-'}exclusive completer '{name}':"
                )
                sys.displayhook(items)

            if is_exclusive_completer(func):
                # we got completions for an exclusive completer
                break
Example #40
0
# The sys module contains interpreter-related tools:
# items related to the interpreter or its process
import sys

sys.argv  # Command-line argument strings list: [scriptname, argument1...]

sys.byteorder

sys.builtin_module_names

sys.displayhook(value)

sys.dont_write_bytecode

sys.excepthook(type, value, trackback)

sys.exc_info()

sys.executable

sys.exit([N])

sys.flags

sys.float_info

sys.getdefaultencoding()
sys.setdefaultencoding(name)

sys.getfilesystemencoding()
Example #41
0
    def __call__(self, tp, val, argin3):
        global _auto_quote_funcs_

        # We only handle SyntaxErrors
        if not isinstance(val, exceptions.SyntaxError):
            self._orig_ehook(tp, val, argin3)
            return

        # Complain if we're not at the top level
        if (val.text[0]).isspace():
            raise RuntimeError, \
                    "LazyPython shortcuts do not work in loops or functions."

        # Test for shell escape
        if val.text[0] == _SHELL_ESCAPE:
            os.system(val.text[1:])
            return

        # 0 -> normal exception, 1 -> auto-quote, 2 -> auto-paren
        lp_mode = 0

        iFun = _first_word_re_.match(val.text)
        if iFun is None:  #Hard to see how this could happen, but just in case
            self._orig_ehook(tp, val, argin3)
            return
        iFun = iFun.group(0)[:-1]

        if val.text[0] == _PAREN_ESCAPE:
            # Check for the auto-paren escape
            lp_mode = 2
            iFun = iFun[1:]
            text = val.text[1:]
        elif val.text[0] == _QUOTE_ESCAPE:
            # Check for the auto-quote escape
            lp_mode = 1
            iFun = iFun[1:]
            text = val.text[1:]
        else:
            # See if it's an auto-quote/paren function or a callable
            text = val.text
            if iFun in _auto_quote_funcs_:
                lp_mode = 1
            elif iFun in _auto_paren_funcs_:
                lp_mode = 2
            else:
                try:
                    if callable(eval(iFun, _ns_)):
                        lp_mode = 2
                except:
                    lp_mode = 0

        # Now decide what to do based on lp_mode
        if lp_mode == 0:
            # Normal Exception
            self._orig_ehook(tp, val, argin3)
            return

        if lp_mode == 1:
            theRest = text[len(iFun):].strip()
            # Auto-quote
            newcmd = iFun + '("' + '", "'.join(theRest.split()) + '")\n'
        elif lp_mode == 2:
            # Auto-paren
            #newcmd = iFun + '(' + ','.join(theRest.split()) + ')\n'
            theRest = text[len(iFun):].strip()
            newcmd = iFun + '(' + theRest + ')\n'
        elif lp_mode == 3:
            pass  # newcmd has already been set
        else:
            raise RuntimeError, 'Error in LazyPython.py!  Illegal lp_mode.'

        # Try to execute the new command
        try:
            print '-->', newcmd
            sys.displayhook(eval(newcmd, _ns_))
            #exec newcmd in _ns_
        except:
            traceback.print_exc()
Example #42
0
    def __call__(self, tp, val, argin3):
        global _auto_quote_funcs_

        # We only handle SyntaxErrors
        if not isinstance(val, exceptions.SyntaxError):
            self._orig_ehook(tp, val, argin3)
            return

        # Complain if we're not at the top level
        if (val.text[0]).isspace():
            raise RuntimeError, "LazyPython shortcuts do not work in loops or functions."

        # Test for shell escape
        if val.text[0] == _SHELL_ESCAPE:
            os.system(val.text[1:])
            return

        # 0 -> normal exception, 1 -> auto-quote, 2 -> auto-paren
        lp_mode = 0

        iFun = _first_word_re_.match(val.text)
        if iFun is None:  # Hard to see how this could happen, but just in case
            self._orig_ehook(tp, val, argin3)
            return
        iFun = iFun.group(0)[:-1]

        if val.text[0] == _PAREN_ESCAPE:
            # Check for the auto-paren escape
            lp_mode = 2
            iFun = iFun[1:]
            text = val.text[1:]
        elif val.text[0] == _QUOTE_ESCAPE:
            # Check for the auto-quote escape
            lp_mode = 1
            iFun = iFun[1:]
            text = val.text[1:]
        else:
            # See if it's an auto-quote/paren function or a callable
            text = val.text
            if iFun in _auto_quote_funcs_:
                lp_mode = 1
            elif iFun in _auto_paren_funcs_:
                lp_mode = 2
            else:
                try:
                    if callable(eval(iFun, _ns_)):
                        lp_mode = 2
                except:
                    lp_mode = 0

        # Now decide what to do based on lp_mode
        if lp_mode == 0:
            # Normal Exception
            self._orig_ehook(tp, val, argin3)
            return

        if lp_mode == 1:
            theRest = text[len(iFun) :].strip()
            # Auto-quote
            newcmd = iFun + '("' + '", "'.join(theRest.split()) + '")\n'
        elif lp_mode == 2:
            # Auto-paren
            # newcmd = iFun + '(' + ','.join(theRest.split()) + ')\n'
            theRest = text[len(iFun) :].strip()
            newcmd = iFun + "(" + theRest + ")\n"
        elif lp_mode == 3:
            pass  # newcmd has already been set
        else:
            raise RuntimeError, "Error in LazyPython.py!  Illegal lp_mode."

        # Try to execute the new command
        try:
            print "-->", newcmd
            sys.displayhook(eval(newcmd, _ns_))
            # exec newcmd in _ns_
        except:
            traceback.print_exc()
Example #43
0
    def evaluate(self, statement, session, printer=None, stream=None):
        """Evaluate the statement in sessions's globals. """
        # the Python compiler doesn't like network line endings
        source = statement.replace('\r\n', '\n').rstrip()

        try:
            # check for a SyntaxError now; this way the user will see their
            # original statement and not the transformed one
            ast.parse(source)
        except SyntaxError:
            return self.error(stream, self.syntaxerror())

        # convert int to Integer (1/2 -> Integer(1)/Integer(2))
        source = int_to_Integer(source)

        # split source code into 'exec' and 'eval' parts
        exec_source, eval_source = self.split(source)

        try:
            self.compile(eval_source, 'eval')
        except (OverflowError, SyntaxError, ValueError):
            exec_source, eval_source = source, None

        if exec_source is not None:
            exec_source += '\n'
        if eval_source is not None:
            eval_source += '\n'

        # create a dedicated module to be used as this statement's __main__
        statement_module = new.module('__main__')

        # use this request's __builtin__, since it changes on each request.
        # this is needed for import statements, among other things.
        import __builtin__
        statement_module.__builtin__ = __builtin__

        # create customized display hook
        stringify_func = printer or sstr

        def displayhook(arg):
            if arg is not None:
                __builtin__._ = None
                print stringify_func(arg)
                __builtin__._ = arg

        old_displayhook = sys.displayhook
        sys.displayhook = displayhook

        # swap in our custom module for __main__. then unpickle the session
        # globals, run the statement, and re-pickle the session globals, all
        # inside it.
        old_main = sys.modules.get('__main__')

        try:
            old_globals = {}
            sys.modules['__main__'] = statement_module
            statement_module.__name__ = '__main__'

            # re-evaluate the unpicklables
            for code in session.unpicklables:
                exec code in statement_module.__dict__
                exec code in old_globals

            # re-initialize the globals
            session_globals_dict = session.globals_dict()

            for name, val in session_globals_dict.items():
                try:
                    statement_module.__dict__[name] = val
                    old_globals[name] = val
                except:
                    session.remove_global(name)

            # re-initialize '_' special variable
            __builtin__._ = session_globals_dict.get('_')

            # run!
            offset = 0

            try:
                old_stdout = sys.stdout
                old_stderr = sys.stderr

                try:
                    if stream is not None:
                        sys.stdout = stream
                        sys.stderr = stream

                    if exec_source is not None:
                        try:
                            exec_code = self.compile(exec_source, 'exec')
                        except (OverflowError, SyntaxError, ValueError):
                            return self.error(stream, self.syntaxerror())

                        eval(exec_code, statement_module.__dict__)

                    if eval_source is not None:
                        if exec_source is not None:
                            offset = len(exec_source.split('\n'))

                        result = eval(eval_source, statement_module.__dict__)
                        sys.displayhook(result)
                finally:
                    sys.stdout = old_stdout
                    sys.stderr = old_stderr
            except DeadlineExceededError:
                logging.debug("is deadlineexceedederror in evaluate")
                raise DeadlineExceededError
            except:
                return self.error(stream, self.traceback(offset))

            # extract the new globals that this statement added
            new_globals = {}

            for name, val in statement_module.__dict__.items():
                if name not in old_globals or val != old_globals[name]:
                    new_globals[name] = val

            for name in old_globals:
                if name not in statement_module.__dict__:
                    session.remove_global(name)

            if True in [
                    isinstance(val, UNPICKLABLE_TYPES)
                    for val in new_globals.values()
            ]:
                # this statement added an unpicklable global. store the statement and
                # the names of all of the globals it added in the unpicklables
                source = ""

                if exec_source:
                    source += exec_source
                if eval_source:
                    source += eval_source

                source += "\n"

                session.add_unpicklable(source, new_globals.keys())
                logging.debug('Storing this statement as an unpicklable.')
            else:
                # this statement didn't add any unpicklables. pickle and store the
                # new globals back into the datastore
                for name, val in new_globals.items():
                    if not name.startswith('__'):
                        try:
                            session.set_global(name, val)
                        except (TypeError, pickle.PicklingError):
                            pass

            # save '_' special variable into the datastore
            val = getattr(__builtin__, '_', None)

            try:
                session.set_global('_', val)
            except (TypeError, pickle.PicklingError):
                session.set_global('_', None)
        finally:
            sys.modules['__main__'] = old_main
            sys.displayhook = old_displayhook

            try:
                del __builtin__._
            except AttributeError:
                pass

        try:
            session.put()
        except RequestTooLargeError:
            stream.truncate(0)  # clear output
            self.error(
                stream,
                ('Unable to process statement due to its excessive size.', ))
    def evaluate(self, source):
        """Evaluate a piece of Python source code. """
        source = source.replace('\r', '').rstrip()

        # XXX: make all this SIGINT aware

        if '\n' in source:
            exec_source, eval_source = self.split(source)
        else:
            exec_source, eval_source = None, source

        eval_source += '\n'

        try:
            self.compile(eval_source, 'eval')
        except (OverflowError, SyntaxError, ValueError):
            if '\n' not in source and self.is_inspect(source):
                return self.inspect(source)

            exec_source = source
            eval_source = None

        # If in debug mode, then don't setup output trap so that we can
        # run a debugger (e.g. pdb). Note that stdout and stderr won't
        # be captured and stored in the resulting dict object.
        if not self.debug:
            self.trap.set()

        try:
            try:
                del self.locals['__plots__']
            except KeyError:
                pass

            interrupted = False
            traceback = False
            result = None

            start = time.clock()

            try:
                if exec_source is not None:
                    try:
                        exec_code = self.compile(exec_source, 'exec')
                    except (OverflowError, SyntaxError, ValueError):
                        traceback = self.syntaxerror()
                        eval_source = None
                    else:
                        exec exec_code in self.locals

                if eval_source is not None:
                    result = eval(eval_source, self.locals)
                    sys.displayhook(result)
            except SystemExit:
                raise
            except KeyboardInterrupt:
                traceback = self.traceback()
                interrupted = True
            except:
                traceback = self.traceback()

            end = time.clock()

            try:
                plots = self.locals['__plots__']
            except KeyError:
                plots = []

            self.index += 1

            if result is not None:
                self.locals['_%d' % self.index] = result

                self.locals['___'] = self.locals.get('__')
                self.locals['__'] = self.locals.get('_')
                self.locals['_'] = result

            result = {
                'source': source,
                'index': self.index,
                'time': end - start,
                'out': self.trap.out,
                'err': self.trap.err,
                'plots': plots,
                'traceback': traceback,
                'interrupted': interrupted,
            }

            if traceback:
                result['traceback_html'] = self.highlight.traceback(traceback)

            return result
        finally:
            self.trap.reset()