Python Files in Jupyter

Jupyterlab allows one to create a python file by clicking on the plus sign and the selecting python file. Now if I want to run that file in the lab, how do i do it ?

Create a notebook that references it:
def print_something():
    print("hello world")
import something as S


… if they’re in the same folder, it’s as simple as that.

1 Like

For the sake of discussion, imagine you created a Python script named, You do this in your cell in your notebook:


If you want to run that script in the namespace of the current notebook, then you add the interactive flag in your %run call. For example, imagine in the notebook in previous cells that you’ve assigned s = "Hello world." If you want the script you are calling to be able to use the assigned s string as it runs, for example imagine you have a line in the Python .py file of print(s), then you do this:

%run -i

See more about the flags available with the magic %run command here.
The interactive flag is particularly useful for developing a script in conjunction with notebook use, or when using the literate programming to guide the user in defining variables and settings and then using those settings and variables to run code without overwhelming the user with a large code block in the actual notebook.

The magic %run command full-featured handling of output from the running script that you don’t get with doing !python in a cell in your notebook. Meaning that std.err and other advanced output will be handled and displayed in a rich way.

The magic %run command also works with .ipy IPython script files so that you run magic commands in scripts as well.

1 Like

Note that one can also choose Create Console for Editor from the context menu on almost any file. One can then use shift + enter to select some code and run it, showing the results (along with what was run) in the Console.

Files like .md which contain embedded python fenced code blocks can be run, albeit very intentionally, by selecting code chunks (e.g. not the fence)


This extension may be of interest Enhanced Script Support — Elyra 3.16.0.dev0 documentation
There is an issue for merging this feature into JupyterLab directly Run scripts from file editor · Issue #12172 · jupyterlab/jupyterlab · GitHub, I believe it is free for anyone to pickup as Elyra was moved to Linux Fundation rather than Project Jupyter.

1 Like