Force Jupyter to print and not display - python

I am using Jupyter notebooks in Visual Studio Code to present lab sessions for my Python programming course, albeit I am recommending students to work with .py files for themselves and their submissions. Ideally I would like the output of my Python cells to be identical to a Python console, and not pretty-printed by display.
I have already added
"jupyter.runStartupCommands": [
"from IPython.core.interactiveshell import InteractiveShell",
"InteractiveShell.ast_node_interactivity = 'all'"
]
to settings.json to ensure I get all output but it is still passed to display. However, in a Python console, running int shows the representation <class 'int'>, whereas in the notebook it just shows int. Is there a way to force the Python cells to print and not display, so that the output is identical?

Related

Notebook in VSCode displays no output for some stored variables

Consider the following code:
import pandas as pd
import os
csv = """Country,Total Cases,New Cases,Total Deaths,New Deaths,Recovered,Serious
China,74187,1751,2006,138,14796,12017
Diamond Princess,621,79,,,17,20
Singapore,81,,,,29,4
Japan,80,6,1,,20,4
Hong Kong,63,1,2,1,5,6
S. Korea,51,20,,,16,
Thailand,35,,,,17,2
USA,29,,,,3,
Taiwan,23,1,1,,2,
Malaysia,22,,,,15,
Vietnam,16,,,,14,
Germany,16,,,,9,
Australia,15,,,,10,
France,12,,1,,7,
Macao,10,,,,5,
U.A.E.,9,,,,3,1
U.K.,9,,,,8,
Canada,8,,,,1,
Philippines,3,,1,,2,
Italy,3,,,,,2
India,3,,,,3,
Russia,2,,,,2,
Spain,2,,,,2,
Nepal,1,,,,1,
Belgium,1,,,,1,
Sri Lanka,1,,,,1,
Finland,1,,,,1,
Egypt,1,,,,,
Cambodia,1,,,,1,
Sweden,1,,,,,"""
with open("data/covid.csv", "w") as file:
file.write(csv)
df = pd.read_csv("data/covid.csv").fillna(0).astype(dtype = int, errors='ignore')\
.sort_values(by='Total Cases', ascending=False)
latest = df.to_dict('list')
some_var = latest.keys()
print(latest.keys()) # It's a notebook. Printing or calling a variable does not matter.
latest.keys()
Please see the attached image to see the issue
It works in a jupyter notebook on conda and if I run it via a normal python file. Which highlights that the issue lies with how VSCode displays notebook outputs
As you can see, VSCode does not display some outputs after running a cell, but does display others after running a cell.
If I try this in a conda environment, it works just fine:
Any suggestions for why this issue only happens in VSCode & How I might go about fixing it? Is it a kernel thing?
This issue was caused by an extension within vscode called Leaflet Map.
It changed the default renderer for notebook cells in vscode.
If anyone else has issues with VSCode outputs in future, you can click the elipsis on the output cell -> Click Change Presentation & ensure you're using an up to date renderer:

Use imshow with Matlab Python engine

After building and installing the Python engine shipped with Matlab 2019b in Anaconda
(TestEnvironment) PS C:\Program Files\MATLAB\R2019b\extern\engines\python> C:\Users\USER\Anaconda3\envs\TestEnvironment\python.exe .\setup.py build -b C:\Users\USER\MATLAB\build_temp install
for Python 3.7 I wrote a simple script to test a couple of features I'm interested in:
import matlab.engine as ml_e
# Start Matlab engine
eng = ml_e.start_matlab()
# Load MAT file into engine. The result is a dictionary
mat_file = "samples/lena.mat"
lenaMat = eng.load("samples/lena.mat")
print("Variables found in \"" + mat_file + "\"")
for key in lenaMat.keys():
print(key)
# print(lenaMat["lena512"])
# Use the variable from the MAT file to display it as an image
eng.imshow(lenaMat["lena512"], [])
I have a problem with imshow() (or any similar function that displays a figure in the Matlab GUI on the screen) namely that it shows quickly and then disappears, which - I guess - at least confirms that it is possible to use it. The only possibility to keep it on the screen is to add an infinite loop at the end:
while True:
continue
For obvious reasons this is not a good solution. I am not looking for a conversion of Matlab data to NumPy or similar and displaying it using matplotlib or similar third party libraries (I am aware that SciPy can load MAT files for example). The reason is simple - I would like to use Matlab (including loading whole environments) and for debugging purposes I'd like to be able to show this and that result without having to go through loops and hoops of converting the data manually.

Using rpy2 in jupyter notebook but there is no output. Error in withVisible({ : object 'returns' not found

the screenshot for jupyternotebook
I've successfully installed ryp2 using wheel. I'm using Python 3.7.6 and rpy2 2.9.5.
I can get the output from jupter notebook when running python code but it doesn't work when using R magic. I tried to see if I can really use R by installing 'ggplot2' and it worked with installation bar poped out.
However, I cannot get any output when I use R magic.
Errors will come out like this. The error is so weird Error in withVisible({ : object 'returns' not found. returns is a python dataframe and was not converted to r object.
Error in withVisible({
Other error like below. Error in eval(predvars, data, env) : object 'p' not found. Neither p nor q is initialized.
Error in eval(predvars, data, env)
Anyone encountered the same problem?
Thank you very much in advance!
FYI:
packages version
This is only a partial answer; I do not know why you cannot see output of 1 for:
%%R
a = 1
a
but I know that the "errors" you see are there because the variables are indeed not defined - you still need to tell rpy2 to import (-i for input) or export (-o for output) variables between R and Python namespaces, this does not happen automatically (if it did you would end up with each object taking up twice as much space!). This is done using:
%R -i variable_to_import_from_python
And
%R -o variable_to_export_to_python
(or equivalently using %%R). It means that in your examples in order to Python print(a) you first need to:
%%R -o a
a = 1
a
And to have Python variable b, say b = 1 in R you would need to:
%%R -i b
cat(b)
Please read the documentation for using rpy2 in notebooks (magics are covered near the end) and the documentation of RMagic, as it is already explained in there.
I hope you will get an answer on the non-functioning R output soon. If you do not get one in the next few days please consider opening a bug report on rpy2 GitHub.

Print Variable In Jupyter Notebook Markdown Cell Python

Can I print the value of a variable in Markdown Cell Jupyter Notebook?
Tried Code:
value = 5.3
Markdown cell --> Value is {{ value }}
I want that the Markdown cell should display the value of variable
SCREENSHOT
#nilansh bansal's answer works great for Jupyter Notebooks. Unfortunately, it doesn't work for JupyterLab because the plugin is no longer supported (as is the case for all nbextension plugins). Since JupyterLab gains popularity, I wanted to complement the answers so far because it took me quite some time to find a solution. This is because until now there is no plugin compatible with JupyterLab. I have found the following solution for myself by combining this and this SO answers:
from IPython.display import Markdown as md
# Instead of setting the cell to Markdown, create Markdown from withnin a code cell!
# We can just use python variable replacement syntax to make the text dynamic
n = 10
md("The data consists of {} observations. Bla, Bla, ....".format(n))
Alternatively, the last line can be simplified as suggested by #Igor Fobia for Python >3.6:
md(f"The data consists of {n} observations. Bla, Bla, ....")
This leads to the desired output. However, it has the huge disadvantage that the code cell will still be visible when exporting the NB. This can be solved though:
Add a tag to the code cell, i.e. name it "hide"
Configure nbconvert to ignore the tagged cells, e.g. by adding this c.TagRemovePreprocessor.remove_input_tags = {"hide"} to your ~/.jupyter/jupyter_notebook_config.py config file
I have written a detailed blog-post about how I implemented this solution for publishing Notebooks on my blog. If you use JupyterLab < 2.0, you could install the jupyterlab-celltags plugin for JupyterLab to simplify the cell tagging.
So After going through all the links I was able to resolve the problem by referring to nbextension jupyter notebook docs : https://github.com/ipython-contrib/jupyter_contrib_nbextensions
Steps Taken:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable python-markdown/main
After the above commands started a jupyter notebook and to print the value of a variable in the markdown cells works like charm!
You just have to use {{ ac_score }} within a markdown cell.
Screenshot
Thanks!
You can overwrite %%markdown IPython magic to substitute variables from the global environment:
from IPython.display import Markdown
from IPython.core.magic import register_cell_magic
#register_cell_magic
def markdown(line, cell):
return Markdown(cell.format(**globals()))
This has the advantage of allowing for Markdown linting when used with JupyterLab-LSP.
If developing a documentation with nbsphinx you can hide the input (source of the cell) by setting {"hide_input": true} in cell metadata:
(note the Jupyter[Lab] and LSP underlined as those are not in the English dictionary - linting works!)
which results in smooth docs like this:
For a better experience when in JupyterLab you can always collapse the input cell by clicking on the blue bar to the left of it (visible when you hover over the cell).

Using Hydrogen, how do I save they python script with output included like a jupyter notebook?

I'm new to Atom and Jupyter. I've only installed Hydrogen and I'm testing on a simple script. I can make some data and, shift+Enter shows the plot inline! I'd like to save the file w/ the output blocks I see in the Atom+Hydrogen GUI. I've seen other Jupyter notebooks like this. Can I do it and how?
You can use Pandoctools for this. It can export hydrogen *.py / *.md documents to any Pandoc output format or to Jupyter notebook.
For example you can create and register Jupyter kernel. For example is can be named "nn". That should be the same kernel that you selected in Atom/Hydrogen. Then add hat to the Python file, split Hydrogen to cells, provide settings and set Markdown cells (commented metadata line would export to ipynb that can be opened in nteract native app):
"""
---
kernels-map:
py: nn
jupyter:
kernelspec:
display_name: nn
language: python
name: nn
pandoctools:
out: "*.pdf"
# out: "*.ipynb"
...
# Markdown section title 1
Some **static** Markdown text.
"""
# %% {echo=False}
import IPython.display as ds
import math
import sugartex as stex
# %% {markdown}
"""
# Markdown section title 2
The quick brown Fox jumps over the lazy dog.
"""
# %%
ds.Markdown(stex.pre(f'''
Some **dynamic** Markdown text with SugarTeX formula: ˎα^˱{math.pi:1.3f}˲ˎ.
It works because of the `Markdown` display option and `sugartex` Pandoc filter.
Acually `stex.pre` is redundant here but it is needed when the text is imported
or read from somewhere instead of being written in the same document.
'''))
Then convert the file via pandoctools: drag and drop file to pandoctools shortcut/executable or "open with" pandoctools executable.
Also see:
introduction article: convenient and easily tweakable Atom+Markdown+Pandoc+Jupyter experience,
examples of input to output conversion that have cross-references!
how to use Pandoctools and it's CLI,
how to use Knitty that collects Jupyter outputs and change it's settings.

Categories