Creating a Simple Application
Putting it together: a small command-line application that takes a FASTA file, reports per-sequence statistics (length, GC, coding potential heuristics), and writes a summary table. It demonstrates the full arc - argument parsing, Biopython I/O, computation, and output - in a script you can actually run.
The Script
#!/usr/bin/env python3
'''seqstats.py - summarize a FASTA file.'''
import argparse
import sys
from Bio import SeqIO
def gc_content(seq):
s = str(seq).upper()
return (s.count("G") + s.count("C")) / len(s) if s else 0.0
def main():
parser = argparse.ArgumentParser(description="Summarize a FASTA file.")
parser.add_argument("fasta", help="path to a FASTA file")
parser.add_argument("-o", "--output", default=None,
help="write TSV summary to this file")
args = parser.parse_args()
rows = []
for rec in SeqIO.parse(args.fasta, "fasta"):
seq = str(rec.seq)
rows.append({
"id": rec.id,
"length": len(seq),
"gc": round(gc_content(rec.seq), 3),
"has_stop": "*" in rec.seq.translate(to_stop=False)
if set(seq) <= set("ACGTURacgtur") else "",
})
if not rows:
print("no sequences found", file=sys.stderr)
return 1
header = ["id", "length", "gc", "has_stop"]
lines = ["\t".join(header)]
for r in rows:
lines.append("\t".join(str(r[h]) for h in header))
text = "\n".join(lines)
if args.output:
with open(args.output, "w") as f:
f.write(text + "\n")
print(f"wrote {len(rows)} rows to {args.output}")
else:
print(text)
return 0
if __name__ == "__main__":
raise SystemExit(main())
Running It
python seqstats.py genes.fasta
python seqstats.py genes.fasta -o summary.tsv
head summary.tsv
Why This Structure
- argparse for a documented CLI (--help works out of the box).
- Pure helper functions (gc_content) that are trivially unit-testable.
- Streaming parse (SeqIO.parse) so memory stays flat on big files.
- Exit codes and stderr messages so the script composes in pipelines.
Where to Extend It
- Add a --min-length filter and a --report-only-below-gc threshold.
- Translate protein/CDS candidates and report ORF length.
- BLAST the top candidates (Bio.Blast) and add taxonomic hits to the table.
- Pack as a console entry point (pyproject.toml scripts) so it installs as seqstats.
Summary
A simple Biopython application is an argparse CLI that streams a FASTA with SeqIO.parse, computes per-sequence statistics in pure functions, and writes TSV or prints a table. The pattern - parse, transform, emit - plus exit codes and testable helpers scales from a one-off script to an installed command-line tool.