A notebook CLI that breaks cell magics
Cell magics like %%writefile and %%bash only work on the first line of a cell. A tool that adds lines before your code breaks them, and plain Python is the fix.
I ran code through a command line tool that executes notebook cells. It worked until I tried to write a file with %%writefile. The cell failed and no file appeared. The cause is a rule of IPython that is easy to miss, and the fix is simple.
The rule
A cell magic starts with two percent signs, as in %%bash or %%writefile. IPython only treats it as a cell magic when it is the first line of the cell. The magic then receives the rest of the cell as plain text.
If anything comes before it, the line is no longer special. Some tools add setup lines at the top of every cell, such as an import, a working directory change or a logging call. Those added lines push your magic down to line two. Your cell then breaks without any change on your side.
What I saw
I reproduced this with IPython in a scratch virtual environment. Three cells, run through the shell object.
A cell that starts with the magic works.
%%writefile m1.txt
hello
The file m1.txt appears. Now the same cell with one line in front of it.
import os
%%writefile m2.txt
hello
The run fails with this message, and no file is written.
UsageError: Line magic function `%%writefile` not found.
The wording is a little confusing. IPython sees a percent sign in the middle of a cell and looks for a line magic with that name. There is none, because %%writefile is a cell magic.
The %%bash magic fails in a different way. When it is first in the cell, it prints the output as expected. With one line before it, the result is a syntax error.
x=1
%%bash
echo hi
SyntaxError: invalid syntax
Here IPython passes the text to Python, and Python does not know what echo hi means.
The fix: write files from plain Python
If you cannot control what a tool adds to your cells, stop relying on cell magics. Plain Python has no position rule, so it works in any cell.
from pathlib import Path
Path("m3.txt").write_text("hello\n")
I ran this form in the same shell object, and it worked and wrote m3.txt. The same file appeared on disk, and the cell reported success.
For shell commands, use the standard library.
import subprocess
result = subprocess.run(["echo", "hi"], capture_output=True, text=True, check=True)
print(result.stdout, end="")
This needs no magic. It also fails loudly when the command fails, because of check=True, and it gives you the output as a value that you can inspect.
A note on multi-line text
A file written from Python needs a string. For a long file, a triple-quoted string works. Take care with backslashes and with text that itself contains triple quotes. A raw string, written r"""...""", keeps backslashes as they are.
from pathlib import Path
Path("notes.txt").write_text(r"""first line
second line with a \ in it
""")
Check what a tool adds
Before you use any cell magic through a wrapper, find out whether the wrapper changes your code. Send a cell with a deliberate error on line one. Then read the traceback. If it points to a line that you did not write, something sits in front of your code.
The cheaper habit is to avoid magics in anything that runs through a tool. A magic is a convenience for a person at a keyboard, in a notebook where the cell is exactly what they typed. A script that other tools run needs code that does not depend on where a line sits.
A habit that helps
When a cell fails in a way that makes no sense, count the lines. Compare the line number in the error with the line number in your own cell. A gap between the two is the quickest sign that a tool changed your code before it ran.
Summary
- Cell magics work only on the first line of a cell.
- A tool that prepends lines to cells breaks them, and the error messages do not point at the cause.
- Plain Python, with
pathlibfor files andsubprocessfor commands, works in every position.