Communitygithub.com

biopython

全面的分子生物学工具包。用于序列操作、文件解析(FASTA/GenBank/PDB)、系统发育学以及程序化访问NCBI/PubMed(Bio.Entrez)。最适合批量处理、自定义生物信息学流程和BLAST自动化。快速查询请使用gget;多服务集成请使用bioservices。

biopython 是什么?

Biopython是一个全面的Python生物信息学库,专为序列操作、文件解析(FASTA/GenBank/PDB)、系统发育学以及程序化访问NCBI/PubMed(通过Bio.Entrez)而设计。它适用于批量处理、自定义生物信息学流程和BLAST自动化,是分子生物学计算的瑞士军刀。该工具支持Python 3.10-3.14及PyPy3.10,需要NumPy,当前稳定版本为Biopython 1.87。其核心功能包括序列处理(Bio.Seq/SegIO)、比对分析(Bio.Align)、NCBI数据库访问、BLAST操作、结构生物信息学(Bio.PDB)、系统发育学(Bio.Phylo)以及模体分析、群体遗传学和限制性酶切分析等高级特性。对于开发者和AI代理用户,Biopython的最佳实践是显式导入模块、在访问NCBI时设置邮件地址、对大文件使用迭代器、缓存数据避免重复下载等。参考文档按功能区域组织,便于快速查找;常见问题包括解析错误、BLAST速度慢和版本兼容性问题(如1.86中PairwiseAligner的默认gap评分变化)。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/biopython

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Biopython:Python 中的计算分子生物学

概述

Biopython 是一套全面的免费 Python 工具,用于生物计算。它提供序列操作、文件 I/O、数据库访问、结构生物信息学、系统发育学和许多其他生物信息学任务的功能。当前版本为 Biopython 1.87(发布于 2026 年 3 月 30 日)。它支持 Python 3.10-3.14 和 PyPy3.10,并且需要 NumPy。Biopython 1.87 还解决了在解析不受信任文件时 Bio.Entrez.Parser 中的 CVE-2025-68463 问题,因此对于需要解析外部提供的 Entrez XML 的工作流程,建议使用 1.87 或更高版本。

何时使用此技能

在以下情况下使用此技能:

  • 处理生物序列(DNA、RNA 或蛋白质)
  • 读取、写入或转换生物文件格式(FASTA、GenBank、FASTQ、PDB、mmCIF 等)
  • 通过 Entrez 访问 NCBI 数据库(GenBank、PubMed、Protein、Gene 等)
  • 运行 BLAST 搜索或解析 BLAST 结果
  • 执行序列比对(成对比对或多序列比对)
  • 分析 PDB 文件中的蛋白质结构
  • 创建、操作或可视化系统发育树
  • 查找序列模体或分析模体模式
  • 计算序列统计信息(GC 含量、分子量、熔解温度等)
  • 执行结构生物信息学任务
  • 处理群体遗传学数据
  • 任何其他计算分子生物学任务

核心能力

Biopython 组织成模块化的子包,每个子包针对特定的生物信息学领域:

  1. 序列处理 - Bio.Seq 和 Bio.SeqIO 用于序列操作和文件 I/O
  2. 比对分析 - Bio.Align 和 Bio.AlignIO 用于成对和多序列比对
  3. 数据库访问 - Bio.Entrez 用于程序化访问 NCBI 数据库
  4. BLAST 操作 - Bio.Blast 用于运行和解析 BLAST 搜索
  5. 结构生物信息学 - Bio.PDB 用于处理 3D 蛋白质结构
  6. 系统发育学 - Bio.Phylo 用于系统发育树的操作和可视化
  7. 高级特性 - 模体、群体遗传学、序列实用工具等

安装与设置

安装当前稳定的 Biopython 版本,并明确锁定版本以确保可重复性:

uv pip install "biopython==1.87"

对于 NCBI 数据库访问,始终设置您的电子邮件地址(NCBI 要求)。对于可重用软件,请设置一个稳定的 Entrez.tool 值,并向 NCBI 注册该工具/电子邮件。要获得更高的速率限制(10 请求/秒而不是 3 请求/秒),仅从环境变量读取 NCBI_API_KEY —— 不要硬编码密钥或加载不相关的环境变量:

import os
from Bio import Entrez

Entrez.email = "[email protected]"  # 必需 —— 使用您的真实电子邮件
Entrez.tool = "your_tool_name"  # 可选,但对于可重用软件推荐设置

# 可选:在 https://www.ncbi.nlm.nih.gov/account/settings/ 注册
if api_key := os.environ.get("NCBI_API_KEY"):
    Entrez.api_key = api_key

使用此技能

此技能提供按功能领域组织的全面文档。处理任务时,请查阅相关的参考文档:

1. 序列处理 (Bio.Seq & Bio.SeqIO)

参考文档: references/sequence_io.md

用于:

  • 创建和操作生物序列
  • 读取和写入序列文件(FASTA、GenBank、FASTQ 等)
  • 在文件格式之间转换
  • 从大文件中提取序列
  • 序列翻译、转录和反向互补
  • 处理 SeqRecord 对象

快速示例:

from Bio import SeqIO

# 从 FASTA 文件读取序列
for record in SeqIO.parse("sequences.fasta", "fasta"):
    print(f"{record.id}: {len(record.seq)} bp")

# 将 GenBank 转换为 FASTA
SeqIO.convert("input.gb", "genbank", "output.fasta", "fasta")

2. 比对分析 (Bio.Align & Bio.AlignIO)

参考文档: references/alignment.md

用于:

  • 成对序列比对(全局和局部)
  • 读取和写入多序列比对
  • 使用替代矩阵(BLOSUM、PAM)
  • 计算比对统计信息
  • 自定义比对参数

快速示例:

from Bio import Align

# 成对比对
aligner = Align.PairwiseAligner()
aligner.mode = 'global'
alignments = aligner.align("ACCGGT", "ACGGT")
print(alignments[0])

3. 数据库访问 (Bio.Entrez)

参考文档: references/databases.md

用于:

  • 搜索 NCBI 数据库(PubMed、GenBank、Protein、Gene 等)
  • 下载序列和记录
  • 获取出版物信息
  • 跨数据库查找相关记录
  • 使用适当的速率限制进行批量下载

快速示例:

from Bio import Entrez
Entrez.email = "[email protected]"

# 搜索 PubMed
handle = Entrez.esearch(db="pubmed", term="biopython", retmax=10)
results = Entrez.read(handle)
handle.close()
print(f"找到 {results['Count']} 条结果")

4. BLAST 操作 (Bio.Blast)

参考文档: references/blast.md

用于:

  • 通过 NCBI 网络服务运行 BLAST 搜索
  • 运行本地 BLAST 搜索
  • 解析 BLAST XML 输出
  • 按 E-value 或一致性过滤结果
  • 提取命中序列

快速示例:

from Bio.Blast import NCBIWWW, NCBIXML

# 运行 BLAST 搜索
result_handle = NCBIWWW.qblast("blastn", "nt", "ATCGATCGATCG")
blast_record = NCBIXML.read(result_handle)

# 显示前几个命中
for alignment in blast_record.alignments[:5]:
    print(f"{alignment.title}: E-value={alignment.hsps[0].expect}")

5. 结构生物信息学 (Bio.PDB)

参考文档: references/structure.md

用于:

  • 解析 PDB 和 mmCIF 结构文件
  • 导航蛋白质结构层次(SMCRA:结构/模型/链/残基/原子)
  • 计算距离、角度和二面角
  • 二级结构分配 (DSSP)
  • 结构叠加和 RMSD 计算
  • 从结构中提取序列

快速示例:

from Bio.PDB import PDBParser

# 解析结构
parser = PDBParser(QUIET=True)
structure = parser.get_structure("1crn", "1crn.pdb")

# 计算两个α碳之间的距离
chain = structure[0]["A"]
distance = chain[10]["CA"] - chain[20]["CA"]
print(f"距离: {distance:.2f} Å")

6. 系统发育学 (Bio.Phylo)

参考文档: references/phylogenetics.md

用于:

  • 读取和写入系统发育树(Newick、NEXUS、phyloXML)
  • 从距离矩阵或比对构建树
  • 树操作(修剪、重定根、阶梯化)
  • 计算系统发育距离
  • 创建共识树
  • 可视化树

快速示例:

from Bio import Phylo

# 读取并可视化树
tree = Phylo.read("tree.nwk", "newick")
Phylo.draw_ascii(tree)

# 计算距离
distance = tree.distance("Species_A", "Species_B")
print(f"距离: {distance:.3f}")

7. 高级特性

参考文档: references/advanced.md

用于:

  • 序列模体 (Bio.motifs) - 查找和分析模体模式
  • 群体遗传学 (Bio.PopGen) - GenePop 文件、Fst 计算、Hardy-Weinberg 检验
  • 序列实用工具 (Bio.SeqUtils) - GC 含量、熔解温度、分子量、蛋白质分析
  • 限制性酶切分析 (Bio.Restriction) - 查找限制性酶切位点
  • 聚类 (Bio.Cluster) - K-means 和层次聚类
  • 基因组图谱 (GenomeDiagram) - 可视化基因组特征

快速示例:

from Bio.SeqUtils import gc_fraction, molecular_weight
from Bio.Seq import Seq

seq = Seq("ATCGATCGATCG")
print(f"GC 含量: {gc_fraction(seq):.2%}")
print(f"分子量: {molecular_weight(seq, seq_type='DNA'):.2f} g/mol")

通用工作流程指南

阅读文档

当用户询问特定的 Biopython 任务时:

  1. 根据任务描述确定相关模块
  2. 使用 Read 工具阅读适当的参考文件
  3. 提取相关代码模式并根据用户的具体需求进行调整
  4. 在任务需要时组合多个模块

参考文件的搜索模式示例:

# 查找特定函数的信息
rg -n "SeqIO.parse" references/sequence_io.md

# 查找特定任务的示例
rg -n "BLAST" references/blast.md

# 查找特定概念的信息
rg -n "alignment" references/alignment.md

编写 Biopython 代码

编写 Biopython 代码时遵循以下原则:

  1. 显式导入模块

    from Bio import SeqIO, Entrez
    from Bio.Seq import Seq
    
  2. 使用 NCBI 数据库时设置 Entrez.email;如果存在,仅从环境变量加载 NCBI_API_KEY

    import os
    from Bio import Entrez
    
    Entrez.email = "[email protected]"
    Entrez.tool = "your_tool_name"
    if api_key := os.environ.get("NCBI_API_KEY"):
        Entrez.api_key = api_key
    
  3. 使用适当的文件格式 - 检查哪种格式最适合任务

    # 常见格式:"fasta"、"genbank"、"fastq"、"clustal"、"phylip"
    
  4. 正确处理文件 - 使用后关闭句柄或使用上下文管理器

    with open("file.fasta") as handle:
        records = SeqIO.parse(handle, "fasta")
    
  5. 对大文件使用迭代器 - 避免将所有内容加载到内存中

    for record in SeqIO.parse("large_file.fasta", "fasta"):
        # 一次处理一条记录
    
  6. 优雅地处理错误 - 网络操作和文件解析可能失败

    from urllib.error import HTTPError
    
    try:
        handle = Entrez.efetch(db="nucleotide", id=accession)
    except HTTPError as e:
        print(f"错误: {e}")
    

常见模式

模式 1:从 GenBank 获取序列

from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# 获取序列
handle = Entrez.efetch(db="nucleotide", id="EU490707", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()

print(f"描述: {record.description}")
print(f"序列长度: {len(record.seq)}")

模式 2:序列分析流程

from Bio import SeqIO
from Bio.SeqUtils import gc_fraction

for record in SeqIO.parse("sequences.fasta", "fasta"):
    # 计算统计信息
    gc = gc_fraction(record.seq)
    length = len(record.seq)

    # 查找 ORF、翻译等
    protein = record.seq.translate()

    print(f"{record.id}: {length} bp, GC={gc:.2%}")

模式 3:BLAST 并获取顶级命中

from Bio.Blast import NCBIWWW, NCBIXML
from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# 运行 BLAST
result_handle = NCBIWWW.qblast("blastn", "nt", sequence)
blast_record = NCBIXML.read(result_handle)

# 获取顶级命中的登录号
accessions = [aln.accession for aln in blast_record.alignments[:5]]

# 获取序列
for acc in accessions:
    handle = Entrez.efetch(db="nucleotide", id=acc, rettype="fasta", retmode="text")
    record = SeqIO.read(handle, "fasta")
    handle.close()
    print(f">{record.description}")

模式 4:从序列构建系统发育树

from Bio import AlignIO, Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor

# 读取比对
alignment = AlignIO.read("alignment.fasta", "fasta")

# 计算距离
calculator = DistanceCalculator("identity")
dm = calculator.get_distance(alignment)

# 构建树
constructor = DistanceTreeConstructor()
tree = constructor.nj(dm)

# 可视化
Phylo.draw_ascii(tree)

最佳实践

  1. 在编写代码前始终阅读相关参考文档
  2. 使用 grep 搜索参考文件查找特定函数或示例
  3. 在解析前验证文件格式
  4. 优雅地处理缺失数据 - 并非所有记录都有所有字段
  5. 缓存下载的数据 - 不要重复下载相同的序列
  6. 遵守 NCBI 速率限制 - 对于可重用软件,使用 API 密钥、注册工具/电子邮件值,并使用 Entrez 历史记录/批处理处理大型任务
  7. 先用小数据集测试,再处理大文件
  8. 保持 Biopython 更新以获取最新功能和错误修复
  9. 使用适当的遗传密码表进行翻译
  10. 记录分析参数以确保可重复性

常见问题排查

问题:"No handlers could be found for logger 'Bio.Entrez'"

解决方案: 这只是警告。设置 Entrez.email 即可消除。

问题:来自 NCBI 的 "HTTP Error 400"

解决方案: 检查 ID/登录号是否有效且格式正确。

问题:解析文件时出现 "ValueError: EOF"

解决方案: 验证文件格式是否与指定的格式字符串匹配。

问题:比对失败,提示 "sequences are not the same length"

解决方案: 确保在使用 AlignIO 或 MultipleSeqAlignment 之前序列已经比对。

问题:BLAST 搜索速度慢

解决方案: 对于大规模搜索,使用本地 BLAST,或缓存结果。

问题:PDB 解析器警告

解决方案: 使用 PDBParser(QUIET=True) 抑制警告,或调查结构质量。

问题:Bio.HMM、Bio.MarkovModel 或 Bio.Application 的 ImportError

解决方案: 这些模块已在 Biopython 1.86 中移除。对于 HMM,请使用 hmmlearn;对于 CLI 包装器,请使用标准库 subprocess 模块替代 Bio.Application。

问题:升级到 1.86+ 后 PairwiseAligner 返回的比对数量减少

解决方案: 在 1.86 中,默认空位评分从 0 变为 -1,从而消除了无关紧要的比对。如果需要恢复旧行为,请设置 aligner.gap_score = 0(请参阅 references/alignment.md)。

附加资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

cobrapy

Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis.

相关技能