You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jupyter Notebook中运行路径存为字符串列表的.py文件?

Understanding IPython's %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 named os.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:52:57