def test_capture_output_no_stderr(): """test capture_output(stderr=False)""" rich = capture.RichOutput(data=full_data) # add nested capture_output so stderr doesn't make it to nose output with capture.capture_output(), capture.capture_output(stderr=False) as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() assert hello_stdout == cap.stdout assert "" == cap.stderr assert len(cap.outputs) == 1
def test_capture_output_no_stderr(): """test capture_output(stderr=False)""" rich = capture.RichOutput(data=full_data) # add nested capture_output so stderr doesn't make it to nose output with capture.capture_output(), capture.capture_output(stderr=False) as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() yield nt.assert_equal, hello_stdout, cap.stdout yield nt.assert_equal, "", cap.stderr yield nt.assert_equal, len(cap.outputs), 1
def test_capture_output_no_stderr(): """test capture_output(stderr=False)""" rich = capture.RichOutput(data=full_data) # add nested capture_output so stderr doesn't make it to nose output with capture.capture_output(), capture.capture_output(stderr=False) as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() yield nt.assert_equal, hello_stdout, cap.stdout yield nt.assert_equal, "", cap.stderr yield nt.assert_equal, len(cap.outputs), 1
def test_2_install(self): kc = self.kc with capture_output() as io: reply = kc.execute_interactive("!pip install multiprocess", timeout=TIMEOUT) assert 'Successfully installed' in io.stdout assert reply['content']['status'] == 'ok' with capture_output() as io: reply = kc.execute_interactive("import multiprocess", timeout=TIMEOUT) assert '' == io.stderr assert reply['content']['status'] == 'ok'
def stan(self, line, cell): """ Allow jupyter notebook cells create a pystan.StanModel object from Stan code in a cell that begins with %%stan. The pystan.StanModel gets assigned to a variable in the notebook's namespace, either named _stan_model (the default), or a custom name (specified by writing %%stan <variable_name>). """ variable_name, stan_opts = parse_args(line) pystan.logger.debug("StanModel options: {!r}".format(stan_opts)) start = datetime.datetime.now() try: with capture_output(display=False) as capture: stan_model, created = StanModelCache.get_or_create(model_code=cell, **stan_opts) except Exception: pystan.logger.error("Error creating Stan model: {}".format(capture)) raise end = datetime.datetime.now() delta = humanize.naturaldelta(end - start) self.shell.user_ns[variable_name] = stan_model if created: pystan.logger.info(f"StanModel available as '{variable_name}' ({delta} compilation time).") else: stan_model.model_name = stan_opts.get('model_name') pystan.logger.info(f"StanModel available as '{variable_name}' (got from cache).")
def test_execute_interactive(self): kc = self.kc with capture_output() as io: reply = kc.execute_interactive("print('hello')", timeout=TIMEOUT) assert 'hello' in io.stdout assert reply['content']['status'] == 'ok'
def send(self, msg): with capture_output() as captured: self._console.push(msg) print(captured.stdout) print(captured.stderr) return captured.stdout
def test_execute_interactive(self): kc = self.kc with capture_output() as io: reply = kc.execute_interactive("print('hello')", timeout=TIMEOUT) assert 'hello' in io.stdout assert reply.content['status'] == 'ok'
def __init__(self, graph, variables, edgeLabels=None, nodeLabels=None): """ Initialization of the class Parameters: ----------- graph : the graph to draw variables : (type=list(dict())) the variables defining possible colors and labels for the nodes and edges edgeLabels : (type=dict()) Labels for edges to keep throught the entire algorithm nodeLabels : (type=dict()) Labels for nodes to keep throught the entire algorithm """ if not isinstance(graph, (networkx.Graph, networkx.DiGraph)): graph = graph.networkx() self.__graph = graph self.__nodeLabels = nodeLabels self.__pos = networkx.spring_layout(self.__graph) self.__variables = variables self.__edgeLabels = edgeLabels ipywidgets.Output.__init__(self) with capture.capture_output() as c: self.make() self.clear_output(wait=True) with self: c()
def test_nbconvert_script(): with capture_output(): Path('informal_script.py').write_text( exporter.from_filename(__file__)[0]) import informal_script assert informal_script, """The script was not created.""" print('nbconvert is complete.')
async def on_message(message): if message.content.startswith('>'): pyth_w = open("pythscord_code.py", "w+") pyth_r = open("pythscord_code.py", "r") pyth_a = open("pythscord_code.py", "a+") msg = await client.wait_for_message(author=message.author) while msg.content != 'stop': if msg.content.startswith('tab'): #you can identent by tapping tab count = msg.content.count('tab') pyth_a.write(' ' * count + str(msg.content)[3 * count:] + '\n') print(str(msg.content)) msg = await client.wait_for_message(author=message.author) #elif msg.content.startswith ('del'): #i'm not sure of how to do that else: pyth_a.write(str(msg.content) + '\n') print(str(msg.content)) msg = await client.wait_for_message(author=message.author) pyth_a.close() with capture_output() as c: code = str(exec(open("pythscord_code.py").read())) await client.send_message( message.channel, c.stdout + '\n---------------- \n end \n----------------')
def test_no_widget_view(): with capture_output() as cap: w = Widget() display(w) assert len(cap.outputs) == 0 assert len(cap.stdout) == 0 assert len(cap.stderr) == 0
def stan(self, line, cell): """ Allow jupyter notebook cells create a pystan.StanModel object from Stan code in a cell that begins with %%stan. The pystan.StanModel gets assigned to a variable in the notebook's namespace, either named _stan_model (the default), or a custom name (specified by writing %%stan <variable_name>). """ variable_name, stan_opts = parse_args(line) print( f"Creating pystan model & assigning it to variable " f'name "{variable_name}".' ) print(f"Stan options:\n", stan_opts) start = datetime.datetime.now() try: with capture_output(display=False) as capture: _stan_model = pystan.StanModel(model_code=cell, **stan_opts) except Exception: print(f"Error creating Stan model:") print(capture) raise end = datetime.datetime.now() delta = humanize.naturaldelta(end - start) self.shell.user_ns[variable_name] = _stan_model print( f'StanModel now available as variable "{variable_name}"!\n' f"Compilation took {delta}." )
def submit(): try: problem = request.json['problem'] code = request.json['code'] files = os.listdir("static/levels/" + problem) test_outputs = [] result = {"error": "Timeout"} for i in range(len(files) / 2): try: input_file = "static/levels/%s/input%02d.txt" % (problem, i) output_file = "static/levels/%s/output%02d.txt" % (problem, i) expected = open(output_file).read() with capture_output() as c: exec code actual = c.stdout test_output = expected == actual test_outputs.append(test_output) except Exception, e: test_outputs.append(False) test_outputs = all(test_outputs) if test_outputs: if levels_flow[problem] == "graduation": result = {"graduation": "graduation"} else: result = {"success": "success", "next": levels_flow[problem]} else: result = {"error": "Wrong Answer"}
def test_no_widget_view(): with capture_output() as cap: w = Widget() display(w) assert len(cap.outputs) == 0 assert len(cap.stdout) == 0 assert len(cap.stderr) == 0
def test_plain_text_only(self): ip = get_ipython() formatter = ip.display_formatter assert formatter.active_types == ['text/plain'] assert not formatter.ipython_display_formatter.enabled class Test(object): def __repr__(self): return "<Test %i>" % id(self) def _repr_html_(self): return '<html>' # verify that HTML repr isn't computed obj = Test() data, _ = formatter.format(obj) self.assertEqual(data, {'text/plain': repr(obj)}) class Test2(Test): def _ipython_display_(self): from IPython.display import display display('<custom>') # verify that _ipython_display_ shortcut isn't called obj = Test2() with capture_output() as captured: data, _ = formatter.format(obj) self.assertEqual(data, {'text/plain': repr(obj)}) assert captured.stdout == ''
def serve(self, args): print(ansi_highlight("\nserve %s\n" % args, '38;5;206')) with capture_output() as c: self.parse(args) c() return c.stdout
def test_plain_text_only(self): ip = get_ipython() formatter = ip.display_formatter assert formatter.active_types == ['text/plain'] assert not formatter.ipython_display_formatter.enabled class Test(object): def __repr__(self): return "<Test %i>" % id(self) def _repr_html_(self): return '<html>' # verify that HTML repr isn't computed obj = Test() data, _ = formatter.format(obj) self.assertEqual(data, {'text/plain': repr(obj)}) class Test2(Test): def _ipython_display_(self): from IPython.display import display display('<custom>') # verify that _ipython_display_ shortcut isn't called obj = Test2() with capture_output() as captured: data, _ = formatter.format(obj) self.assertEqual(data, {'text/plain': repr(obj)}) assert captured.stdout == ''
def test_execute_interactive(self): kc = self.kc with capture_output() as io: reply = kc.execute_interactive("print('hello')", timeout=TIMEOUT) assert "hello" in io.stdout assert reply["content"]["status"] == "ok"
def test_alias_args_commented(): """Check that alias correctly ignores 'commented out' args""" _ip.magic('alias commetarg echo this is %%s a commented out arg') with capture_output() as cap: _ip.run_cell('commetarg') nt.assert_equal(cap.stdout, 'this is %s a commented out arg')
def validate_ast(program_ast): ''' returns boolean indicating if program_ast (abstract syntax tree representation) generates code that runs ''' try: with capture_output() as c: c = exec(ar.to_source(program_ast)) return True except: return False
def test_alias_args_error(): """Error expanding with wrong number of arguments""" _ip.alias_manager.define_alias('parts', 'echo first %s second %s') # capture stderr: with capture_output() as cap: _ip.run_cell('parts 1') assert cap.stderr.split(":")[0] == "UsageError"
def test_alias_args_error(): """Error expanding with wrong number of arguments""" _ip.alias_manager.define_alias('parts', 'echo first %s second %s') # capture stderr: with capture_output() as cap: _ip.run_cell('parts 1') nt.assert_equal(cap.stderr.split(':')[0], 'UsageError')
def test_alias_args_commented(): """Check that alias correctly ignores 'commented out' args""" _ip.magic('alias commetarg echo this is %%s a commented out arg') with capture_output() as cap: _ip.run_cell('commetarg') nt.assert_equal(cap.stdout, 'this is %s a commented out arg')
def test_alias_args_error(): """Error expanding with wrong number of arguments""" _ip.alias_manager.define_alias("parts", "echo first %s second %s") # capture stderr: with capture_output() as cap: _ip.run_cell("parts 1") nt.assert_equal(cap.stderr.split(":")[0], "UsageError")
def test_capture_output(): """capture_output works""" rich = capture.RichOutput(data=full_data) with capture.capture_output() as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() yield nt.assert_equal, hello_stdout, cap.stdout yield nt.assert_equal, hello_stderr, cap.stderr
def test_capture_output(): """capture_output works""" rich = capture.RichOutput(data=full_data) with capture.capture_output() as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() yield nt.assert_equal, hello_stdout, cap.stdout yield nt.assert_equal, hello_stderr, cap.stderr
def test_package(self): kc = self.kc with capture_output() as io: reply = kc.execute_interactive("import multiprocess", timeout=TIMEOUT) assert '' == io.stderr and '' == io.stdout assert reply['content']['status'] == 'ok'
def test_capture_output_no_stdout(): """test capture_output(stdout=False)""" rich = capture.RichOutput(data=full_data) with capture.capture_output(stdout=False) as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() nt.assert_equal("", cap.stdout) nt.assert_equal(hello_stderr, cap.stderr) nt.assert_equal(len(cap.outputs), 1)
def test_capture_output_no_display(): """test capture_output(display=False)""" rich = capture.RichOutput(data=full_data) with capture.capture_output(display=False) as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() yield nt.assert_equal, hello_stdout, cap.stdout yield nt.assert_equal, hello_stderr, cap.stderr yield nt.assert_equal, cap.outputs, []
def test_capture_output_no_display(): """test capture_output(display=False)""" rich = capture.RichOutput(data=full_data) with capture.capture_output(display=False) as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() assert hello_stdout == cap.stdout assert hello_stderr == cap.stderr assert cap.outputs == []
def test_exits_gracefully_if_columns_not_same_len(): filename = 'test_write_columns_not_same_len.txt' with capture_output() as c: writecol(filename=filename, data=[['1', '2', '3'], ['.1', '.2', '.3', '.4']], header=['x', 'y', 'z']) c() out = c.stdout assert out.split('\n')[1] == "Error: columns not all same length."
def pytest_result(test_path): ''' runs specified pytest test-file, returns captured result as string ''' try: import pytest with capture_output() as c: pytest.main([test_path]) return c.stdout except ImportError: print("failed to import pytest") return None
def execute_code(self, source): with capture_output() as io: reply = self.client.execute_interactive(source, timeout=TIMEOUT) print(io.stdout, file=sys.stdout) sys.stdout.flush() print(io.stderr, file=sys.stderr) sys.stderr.flush() # reply['content']['status'] == 'ok' results = None ## FIXME: how to get output from capture_output()? return results
def test_capture_output_no_display(): """test capture_output(display=False)""" rich = capture.RichOutput(data=full_data) with capture.capture_output(display=False) as cap: print(hello_stdout, end="") print(hello_stderr, end="", file=sys.stderr) rich.display() yield nt.assert_equal, hello_stdout, cap.stdout yield nt.assert_equal, hello_stderr, cap.stderr yield nt.assert_equal, cap.outputs, []
def show_geometry_1d(sim): # raise NotImplementedError('1D Not supported yet') with capture_output(): sim.run(until=0.1) eps_data = sim.get_array(center=mp.Vector3(), size=sim.cell_size, component=mp.Dielectric) plt.figure(dpi=100) plt.plot(eps_data) return eps_data
def main(argv): try: opts, args = getopt.getopt(argv, 's:l:h:', ['snp=', 'low=', 'high=']) except getopt.GetoptError: sys.exit(2) for opt, arg in opts: if opt in ('-s', '--snp'): snp_file = arg elif opt in ('-l', '--low'): low = float(arg) # low bound elif opt in ('-h', '--high'): high = float(arg) # high bound df = pd.read_csv(snp_file, sep="\t", header=None) df.columns = ['chr', 'pos', 'fq'] arr = df.loc[:, 'fq'] top = 0 bot = len(df) # find index for lower bound if low <= 0: low_i = 1 else: while top <= bot: mid = int(top + (bot - top) / 2) if float(arr[mid]) >= low: if float(arr[mid - 1]) < low: low_i = mid + 1 break else: bot = mid - 1 else: top = mid + 1 top = 0 bot = len(df) # find index for upper bound if high >= 1: high_i = len(df) else: while top <= bot: mid = int(top + (bot - top) / 2) if float(arr[mid]) <= high: if float(arr[mid + 1]) > high: high_i = mid + 1 break else: top = mid + 1 else: if arr[mid - 1]: bot = mid - 1 with capture_output() as c: print(low_i, high_i) c()
def exec_module_capture(Loader, module): from IPython.utils.capture import capture_output with capture_output(stdout=False, stderr=False) as output: try: super().exec_module(module) except type("pass", (BaseException, ), {}): ... finally: module.__output__ = output return module
def test_no_widget_view(): # ensure IPython shell is instantiated # otherwise display() just calls print shell = InteractiveShell.instance() with capture_output() as cap: w = Widget() display(w) assert cap.outputs == [], repr(cap.outputs) assert cap.stdout == '', repr(cap.stdout) assert cap.stderr == '', repr(cap.stderr)
def test_rich_output_display(): """test RichOutput.display This is a bit circular, because we are actually using the capture code we are testing to test itself. """ data = full_data rich = capture.RichOutput(data=data) with capture.capture_output() as cap: rich.display() yield nt.assert_equal, len(cap.outputs), 1 rich2 = cap.outputs[0] yield nt.assert_equal, rich2.data, rich.data yield nt.assert_equal, rich2.metadata, rich.metadata
def test_widget_view(): # ensure IPython shell is instantiated # otherwise display() just calls print shell = InteractiveShell.instance() with capture_output() as cap: w = Button() display(w) assert len(cap.outputs) == 1, "expect 1 output" mime_bundle = cap.outputs[0].data assert mime_bundle['text/plain'] == repr(w), "expected plain text output" assert 'application/vnd.jupyter.widget-view+json' in mime_bundle, "widget should have have a view" assert cap.stdout == '', repr(cap.stdout) assert cap.stderr == '', repr(cap.stderr)
def run_stateful_cell(self, cell, context): specific_context = context["in:locals"] assert isinstance(specific_context, dict) if specific_context: # TODO Context aggregation from different sources # TODO currently the last available context is used via popitem() self.apply_context(specific_context.popitem()[1], self.shell) else: self.shell.reset() if type(cell.source) is list: cell.source = "".join(cell.source) with capture_output() as out: execution_result = self.shell.run_cell(cell.source) results_dict = self.get_context(self.shell) # TODO Distinction among different types of cell evaluation return {'out:locals': {'result': execution_result, 'state': results_dict, 'outputs': out.outputs}}
""" # cell = """ # %matplotlib inline # from bokeh.plotting import figure, output_file, show # from bokeh.io import output_notebook # output_notebook() # p = figure(plot_width=400, plot_height=400) # # # add a circle renderer with a size, color, and alpha # p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5) # # # show the results # show(p) # """ # # cell = """ # %matplotlib qt5 # import matplotlib # import matplotlib.pyplot as plt # import sys # print(matplotlib.pyplot.get_backend()) # """ with capture_output() as out: result = shell.run_cell(cell) assert shell.ns_table['user_local'] == shell.user_ns a = shell.user_ns.copy() shell.reset()