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

如何在Python的nbconvert指令中用变量替换固定文件名?

解决Colab中nbconvert命令引用Python变量的问题

你之前的错误在于:! 之后的是Shell命令,不能直接用Python的字符串拼接语法(+)来引用变量,Shell会把+ filename +当成普通字符串处理,自然无法识别变量。

以下两种可行的实现方式:

方法1:用Python字符串格式化构建命令后执行

先通过f-string拼接出完整的Shell命令,再用get_ipython().system()执行(!本质上是这个方法的快捷方式):

# get filename of the current notebook
from requests import get
from socket import gethostname, gethostbyname
ip = gethostbyname(gethostname())
filename = get(f"http://{ip}:9000/api/sessions").json()[0]["name"]
print(filename)

# mount Drive to access data files
from google.colab import drive
drive.mount('./mount')

# 构建并执行转换命令
convert_command = f"jupyter nbconvert --to html 'mount/My Drive/Colab Notebooks/{filename}'"
get_ipython().system(convert_command)

方法2:直接在魔术命令中引用Python变量

Colab支持在!开头的魔术命令里,用{变量名}直接引用Python变量,注意路径包含空格时,用引号包裹整个路径:

# get filename of the current notebook
from requests import get
from socket import gethostname, gethostbyname
ip = gethostbyname(gethostname())
filename = get(f"http://{ip}:9000/api/sessions").json()[0]["name"]
print(filename)

# mount Drive to access data files
from google.colab import drive
drive.mount('./mount')

# 直接引用变量执行转换
!jupyter nbconvert --to html "mount/My Drive/Colab Notebooks/{filename}"

两种方法都能正确将filename变量代入nbconvert命令,避免手动修改固定文件名的麻烦。

内容的提问来源于stack exchange,提问作者Rapsta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:53:36