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

如何用Python doit框架根据配置文件仅运行指定任务?

解决doit模块通过配置文件控制仅运行指定任务的问题

你的代码问题在于doit默认会执行所有以task_前缀命名的任务,因此即使task_entry只依赖某一个任务,另外两个任务依然会被自动运行。以下是两种可行的解决方法:

方案1:设置默认任务并通过依赖触发指定任务

通过DOIT_CONFIG指定默认只运行entry任务,利用task_entry的依赖关系触发配置文件中指定的任务,未被依赖的任务不会被执行。

修改后的dodo.py代码:

# dodo.py
import configparser

config = configparser.ConfigParser()
config.read("config.ini")

# 配置默认仅运行entry任务
DOIT_CONFIG = {'default_tasks': ['entry']}

def choose_task():
    task_to_run = config.get("config", "task_to_run")
    return {"task_dep": [task_to_run]}

def task_entry():
    return {
        "actions": None,
        "calc_dep": choose_task,
    }

def task_a():
    return {
        "actions": ["echo 'Task A'"]
    }

def task_b():
    return {
        "actions": ["echo 'Task B'"]
    }

def task_c():
    return {
        "actions": ["echo 'Task C'"]
    }

对应的config.ini示例:

[config]
task_to_run = task_a

运行doit命令后,只会执行task_entry和配置中指定的task_a,另外两个任务不会被触发。

方案2:动态生成指定任务

根据配置文件的内容,仅定义需要运行的任务函数,未被指定的任务不会被doit检测到,从根源避免多余任务执行。

修改后的dodo.py代码:

# dodo.py
import configparser

config = configparser.ConfigParser()
config.read("config.ini")

task_to_run = config.get("config", "task_to_run")

def task_entry():
    return {
        "actions": None,
        "task_dep": [task_to_run],
    }

# 仅动态生成配置指定的任务
if task_to_run == 'task_a':
    def task_a():
        return {"actions": ["echo 'Task A'"]}
elif task_to_run == 'task_b':
    def task_b():
        return {"actions": ["echo 'Task B'"]}
elif task_to_run == 'task_c':
    def task_c():
        return {"actions": ["echo 'Task C'"]}

# 设置默认运行entry任务
DOIT_CONFIG = {'default_tasks': ['entry']}

这种方法下,未被配置指定的任务函数不会被定义,doit自然不会执行它们。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 07:00:06