如何在Jupyter Notebook中运行路径存为字符串列表的.py文件?
%run Magic Command Behavior Let me break down what's going on here and how to work around this quirk:
Why expressions don't work with %run directly
IPython magic commands have their own parsing logic that’s separate from regular Python code. When you use %run, the argument you pass is treated as a literal string by IPython’s magic command parser—not a Python expression to evaluate first. That’s why:
%run script.py(no quotes) works, since it’s a straightforward filename%run "my scripts/script.py"(double quotes) works, as the parser recognizes quoted strings as a single path- But something like
%run os.path.join("my scripts", "script.py")fails: IPython tries to look for a file literally namedos.path.join("my scripts", "script.py")instead of evaluating the expression to get the actual path.
How to use dynamic paths with %run
If you need to use a Python expression (like a variable holding a path, or a function that generates a path), you can bypass the magic command’s direct parsing by using IPython’s Python API instead:
import os script_path = os.path.join("my scripts", "script.py") get_ipython().run_line_magic('run', script_path)
The get_ipython() function gives you access to the underlying IPython instance, and run_line_magic() lets you execute the run magic with a properly evaluated Python string as its argument.
Where to find this in the docs
This behavior is covered in IPython’s documentation on magic commands—specifically noting that magic command arguments are parsed as shell-like strings by default, not Python expressions. The section on using magic commands programmatically (via run_line_magic) explains how to integrate them with regular Python code flow.
内容的提问来源于stack exchange,提问作者Calum You

