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

Jupyter Notebook的for循环中能否用%run批量调用脚本生成多分辨率ASCII图?

解决方案

你原本的写法存在问题:%run 魔法命令不会自动识别你代码里定义的Python变量,直接写input_name/output_name/size会被当做普通字符串传入脚本,无法正常执行。
你可以选择以下任意一种方案实现需求:

方案1:沿用%run魔法命令,使用变量注入语法

Jupyter的魔法命令支持通过$符号注入当前命名空间的Python变量,你只需要修改%run行的参数写法即可,完整可运行代码如下:

import os
img_src = 'data/input/'
img_dest = 'data/output/'
# 确保输出目录存在
os.makedirs(img_dest, exist_ok=True)

for image in os.listdir(img_src):
    # 跳过目录,只处理文件
    if not os.path.isfile(os.path.join(img_src, image)):
        continue
    for size in range(100,1000,100):
        input_name = os.path.join(img_src, image)
        output_name = os.path.join(img_dest, f"{image.split('.')[0]}_out_{size}.jpg")
        # 用$引用Python变量
        %run img2img.py --input $input_name --output $output_name --num_cols $size

方案2:使用subprocess模块调用脚本(兼容性更好)

如果后续需要把代码迁移出Jupyter环境,推荐用标准库的subprocess调用,更可控还能捕获执行日志:

import os
import subprocess

img_src = 'data/input/'
img_dest = 'data/output/'
os.makedirs(img_dest, exist_ok=True)

for image in os.listdir(img_src):
    if not os.path.isfile(os.path.join(img_src, image)):
        continue
    for size in range(100,1000,100):
        input_name = os.path.join(img_src, image)
        output_name = os.path.join(img_dest, f"{image.split('.')[0]}_out_{size}.jpg")
        subprocess.run(
            ["python", "img2img.py", "--input", input_name, "--output", output_name, "--num_cols", str(size)],
            check=True
        )

方案3:直接导入脚本函数调用(效率最高)

如果img2img.py是你自己编写的脚本,建议把核心转换逻辑封装成可调用的函数,直接在Jupyter中导入使用,避免每次循环都启动新的Python进程,大幅提升运行速度:

  1. 先修改img2img.py,新增函数封装:
# img2img.py 新增内容
def convert_image(input_path, output_path, num_cols):
    # 把你原来的脚本处理逻辑放到这里
    pass

# 保留原来的命令行调用逻辑,不影响原有使用
if __name__ == "__main__":
    # 原有解析argparse、调用转换的代码不变
  1. 在Jupyter中直接导入调用:
import os
from img2img import convert_image

img_src = 'data/input/'
img_dest = 'data/output/'
os.makedirs(img_dest, exist_ok=True)

for image in os.listdir(img_src):
    if not os.path.isfile(os.path.join(img_src, image)):
        continue
    for size in range(100,1000,100):
        input_name = os.path.join(img_src, image)
        output_name = os.path.join(img_dest, f"{image.split('.')[0]}_out_{size}.jpg")
        convert_image(input_name, output_name, size)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:18:03