Debian Codegraph @

devtools/emulate-tools.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 This script can be symlinked to samtools, bcftools, bgzip, or tabix.
4 When invoked under one of those names, it will emulate that tool's
5 behaviour by using pysam's facilities.
6 """
7
8 import argparse
9 import gzip
10 import os
11 import sys
12 import tempfile
13
14 import pysam
15
16 command = os.path.basename(sys.argv[0])
17
18 if command in ("samtools", "bcftools"):
19 if len(sys.argv) > 1:
20 try:
21 tool = pysam.utils.PysamDispatcher(command, sys.argv[1])
22 tool(*sys.argv[2:], catch_stdout=None)
23 print(tool.stderr, end="", file=sys.stderr)
24 except pysam.utils.SamtoolsError as e:
25 sys.exit(f"emulate-tools.py: {e}")
26
27 else:
28 version = getattr(pysam.version, f"__{command}_version__")
29 print(f"Program: {command}\nVersion: {version}", file=sys.stderr)
30
31 else:
32 parser = argparse.ArgumentParser()
33 parser.add_argument("-c", "--stdout", action="store_true")
34 parser.add_argument("-d", "--decompress", action="store_true")
35 parser.add_argument("-f", "--force", action="store_true")
36 parser.add_argument("-p", "--preset")
37 parser.add_argument("input_file", nargs="?")
38 opt = parser.parse_args()
39
40 if command == "bgzip":
41 if opt.decompress:
42 with gzip.open(sys.stdin.buffer, "rb") as f:
43 sys.stdout.buffer.write(f.read())
44
45 elif opt.input_file and opt.stdout:
46 pysam.tabix_compress(opt.input_file, "-", force=True)
47
48 else:
49 f = tempfile.NamedTemporaryFile(delete=False)
50 f.write(sys.stdin.buffer.read())
51 f.close()
52 pysam.tabix_compress(f.name, "-", force=True)
53 os.remove(f.name)
54
55 elif command == "tabix":
56 pysam.tabix_index(opt.input_file, preset=opt.preset, force=opt.force)
57
58 else:
59 sys.exit(f"emulate-tools.py: unknown command {command!r}")