+++
id = “run-contexts”
title = “Scripts, notebooks and juno.ui windows”
index = “what differs between a script, a notebook and a juno.ui window”
keywords = [“script”, “notebook”, “cell”, “run”, “run button”, “working directory”, “current directory”, “cwd”, “name”, “main”, “file”, “argv”, “blocks”, “window”, “app”, “difference”]
contexts = [“script”, “notebook”, “window”]
see_also = [“juno.ui.run”, “saving-data”, “open-urls”, “show-files”, “ui-patterns”, “ui-patterns/test-without-window”]
+++
Python runs in Juno in three shapes: a script you run with the Run button, the cells of a notebook, and a juno.ui window that either of them opens with ui.run.
A script runs with __name__ set to "__main__", __file__ set to the script’s path, and sys.argv[0] set to the same path. Find files the script ships with through __file__: pathlib.Path(__file__).parent / "words.txt".
In a project, a script’s working directory is the project folder unless you choose another one when you configure the run, so a relative path such as "data.csv" starts there.
A notebook’s cells share one interpreter, the kernel, so a name defined in one cell is there in the next. A cell runs with __name__ set to "__main__" and has no __file__.
A notebook in a project starts in the project’s working directory, the same one its scripts use.
ui.run(body, state) blocks the script, or the notebook cell, until the window closes. Close returns normally; Stop raises KeyboardInterrupt. Only one window runs at a time: calling ui.run while a window is open raises UIError.
A window’s callbacks run one at a time, on the thread that called ui.run. Keep each one short, and split long work into steps with ui.after (see ui-patterns/long-work).
Put ui.run(...) under if __name__ == "__main__":. A script and a notebook cell both run that block, and other code can still load the file without opening a window, to check that body builds (see ui-patterns/test-without-window).