如何在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
相关产品推荐
相关产品推荐

