Running old jupyter notebooks - jupyter-notebook

I am trying to use a Jupyter notebook that was written by somebody else around 8 years ago. And the contents are written in Python2 and not Python3 that I am using. I am new to it and I can't figure out the reason for the syntax error.
The following are the contents of the first cells that is giving a syntax error.
`# Always run this first
# NOTE: Do not define new basic variables in this notebook;
# define them in Variables_Q.ipynb. Use this notebook
# to define new expressions built from those variables.
from __future__ import division # This needs to be here, even though it's in Variables_Q.ipynb
import sys
import os
sys.path.append(os.path.join(os.path.dirname('/home/khushal/Desktop/Python/Git Repositories/PostNewtonian/PNTerms'
)) # Look for modules in directory above this one
exec(open('../Utilities/ExecNotebook.ipy').read(),{})
from ExecNotebook.ipy import execnotebook
try: execnotebook(VariablesNotebook)
except: execnotebook('Variables_Q.ipynb')`
The error is
File "/tmp/ipykernel_31372/53020713.py", line 11
exec(open('../Utilities/ExecNotebook.ipy').read(),{})
^
SyntaxError: invalid syntax
I tried to use a 2to3 jupter notebook converter but it didn't change the jupyter notebook at all and it is giving the same result.

Related

Unable to import Python file in VSCode Julia notebook

I'm trying to import a Python file containing a single function into my Julia notebook in VSCode.
The file is called helloPython.py and contains a single function called helloFromPython.
It contains the following code.
def helloFromPython():
print("Hello Julia, it's me Python!")
It is located in the same directory as my notebook file.
My first cell looks as follows.
import Pkg
Pkg.add("PyCall")
Pkg.build("PyCall")
using PyCall
Importing inbuilt Python functions works as expected, e.g.
math = pyimport("math")
math.sin(math.pi / 4)
Defining and calling Python code on the fly also works as expected, for example
begin
py"""
def f(x):
return x**3
"""
f = py"f"
end
f(2) # prints 8
However, importing my local Python file does not work. My cell looks as follows.
pushfirst!(PyVector(pyimport("sys")."path"), "")
x = pyimport("helloPython")
x.helloFromPython()
There is no error message. The cell executes successfully and that's it.
I've tried the same using the inbuild terminal in VSCode starting the Julia command prompt and it works as expected.
What am I doing wrong here?
Edit: #alex338207 had a good idea here, so I'm updating my question.
Writing to a file works. Here is a minimal working example. The file helloPython.py contains the following code.
def helloFromPython():
f = open("test.txt", "a")
f.write("Hello Julia!")
f.close()
Calling the above in VSCode as describe above, works as expected. A file is created with the provided content "Hello Julia!".
However, returning stuff doesn't work. Here is another example.
def helloFromPython():
return "Hello Julia!"
Calling the above yields to the output nothing.
I've updated my issue on Github.

Script display from an external file in Jupyter Notebook with syntax-highlighting

I am making a tutorial using Jupyter and I would like to display the content of an external Python script. Printing the content of the file is trivial, but I am interested in a color-coded/syntax-highlighted text (either in a markdown cell or as an output).
Use Ipython's Markdown module:
from IPython.display import Markdown as md
script = """
x = 2
if x*2 > 2:
print('x > 2')
else:
x = None
"""
md("```Python" + script + "```")
Will output:
One method is to use the magic command: %load
%load testLoad.py
This is assuming the external file is in your Jupyter Notebook starting directory
If you only want specific lines (say between lines 5 and 10 and also line 15) of your python code to be displayed then:
%load -r 5-10,15 testLoad.py
You can find out the options of a magic command by adding a '?' at the end of the magic command:
%load?
Magic commands are shortcuts that are used to help do things much faster in Jupyter Notebook. They are great for beginners as they generally contain everything a beginner needs to display and test Jupyter Notebook
Here is a link to all magic commands in IPython for Jupyter Notebook:
https://ipython.readthedocs.io/en/stable/interactive/magics.html
The following magic command (starting with %) can be used to output the contents of a python script with highlighting.
%pycat script.py
Alternatively, it is possible to run shell commands by prepending them with !. If you have pygmentize installed, it is possible to use that (though I recommend %pycat for notebooks):
!pygmentize -g script.py
You can also use the old but good UNIX tool cat on all POSIX compliant systems (Unix, Mac, Linux, BSD). Then you won't get highlighting, but it might be more suitable for text files:
!cat data.txt
On POSIX compliant systems notebooks also come with an alias to cat in the form of a magic command:
%cat data.txt

python 3.6 and tdl "console is not defined error"

I'm trying to make a roguelike with python 3 and tdl, but when I try to run
it there's a 'console not defined' error (see image below) I tried to do things like import console or import win32console as console. But it shows the same error
This is the code I'm using:
Well, console appears to be a part of the tdl package, so you should try replacing console.draw_char with tdl.console.draw_char or add from tdl import console as one of your import statments.

Plotting in Python Notebook (Docs)

Attempting to go through the pandas doc at http://pandas.pydata.org/pandas-docs/stable/visualization.html#basic-plotting-plot I get an error :
NameError: name 'Series' is not defined
I can import pandas and supply 'pandas.Series', but I want to know how to set up notebook, as in the docs, so that it's already included.
You can customize Ipython notebook profile file ipython_config.py typically located in ~/.ipython/profile_default/ by adding something like :
c.InteractiveShellApp.exec_lines = [
'import pandas',
]
You can read the documentation for ipython latest version here

Unicode error with IPython rmagic; (%%R seems to work but not %R fully)

I am trying to recreate the demo examples on the IPython Notebook rmagic page. I am getting partial success with a specific error that comes up every time I try to use %Rpush or try to exchange data between R and numpy via the Rpush and Rpull mechanisms (which push/pull data between R and the Py namespaces )
%%R cell magic works reasonably well - I am able to define R vecs X and Y and do a print (lm(X~Y)) which successfully prints output in an IPython Notebook. This also works identically on the qtconsole, and the terminal.
Now if I do a plot(X,Y) inside the cell - I successfully get a plot.
If I start a new Notebook line and try plot(X,Y) I get the following error
[....]
TypeError: coercing to Unicode: need string or buffer, dict found
full stack trace at http://pastebin.com/Pb56Tmgc
a) Why is this successful inside a cell but not working in a line?
b) Any suggestions?
(Env: Python 2.7 (Anaconda 2.7.3 CE) R 2.15 rpy2 2.3 MacOSX 10.7.5 on a 2010 MBP 15"
http://www.soundfrost.org/ >youtube to mp3
This is a bug - the R magic was getting the local namespace as the argument where it was expecting the cell.
Digging into IPython.core.interactiveshell with git blame, it looks like it was fixed as part of pull request #2130 a few months ago.

Resources