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

Snakemake通配符报错:AttributeError及通配符定义疑问

Snakemake通配符困惑与错误解决

问题背景

你在使用Snakemake时遇到通配符相关错误,需求是通过expand获取由其他规则生成的输入文件列表,其中{output_name}已在rule all中通过配置项config["output_name_prefix"]定义,认为{split_index}才是动态通配符:

# rule all中的expand定义
expand(["results/{output_name}_1/{output_name}_1.bed",
        "results/{output_name}_2/{output_name}_2.bed",
        "results/{output_name}.txt"],
output_name=config["output_name_prefix"])

你编写了如下规则用于合并文件,但运行时抛出错误:

def get_values(wildcards):
    expand(
        "results/{output_name}_{split_index}/{output_name}_{split_index}.bed",
    output_name=wildcards.output_name, split_index=wildcards.split_index)

rule merge_file_list:
    input: 
        get_values
    output: 
        "results/{output_name}.txt"
    shell:
        "for s in {input}; do ${{s}} > {output}; done"

错误信息:

Error:
  AttributeError: 'Wildcards' object has no attribute 'split_index'
Wildcards:
  output_name=Homo_sapiens_ch19

你想明确两个问题:Snakemake中如何定义通配符?此错误的原因是什么?

错误原因分析

这个错误的核心是规则merge_file_list的输出仅包含{output_name}这一个通配符:

  • Snakemake处理规则时,只会从规则的输出路径中解析通配符值并生成wildcards对象。你的输出是results/{output_name}.txt,所以wildcards里只有output_name属性。
  • 你的get_values函数试图访问wildcards.split_index,但这个属性根本不存在,直接触发AttributeError。

Snakemake通配符的定义逻辑

Snakemake中的通配符本质是文件路径里的占位符,用来批量匹配/生成结构相似的文件,核心规则:

  1. 规则的通配符集合由输出路径决定:当Snakemake需要生成某个具体输出文件时,会将输出路径中的占位符替换为实际值,这些值就是当前规则的wildcards对象的属性。
  2. 输入通配符必须可推导:如果输入路径包含额外通配符,要么能通过当前规则的wildcards推导(比如从配置、固定列表中获取),要么是关联规则传递过来的,不能凭空访问未定义的通配符属性。

修正后的代码

针对你的场景,split_index是固定的1和2,可以在get_values中直接指定其取值,无需从wildcards读取:

def get_values(wildcards):
    return expand(
        "results/{output_name}_{split_index}/{output_name}_{split_index}.bed",
        output_name=wildcards.output_name,
        split_index=[1, 2]  # 直接指定split_index的可能取值
    )

rule merge_file_list:
    input: 
        get_values
    output: 
        "results/{output_name}.txt"
    shell:
        # 用cat合并更高效,或循环追加避免覆盖
        "cat {input} > {output}"
        # 若需要逐文件处理可改为:for s in {input}; do cat "${s}" >> {output}; done

这样修改后,get_values会基于当前的output_name,生成对应的两个.bed文件路径作为输入,Snakemake能正确解析依赖关系,不会再出现通配符错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:42:33