response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
get args | def get_args():
"""get args"""
parser = argparse.ArgumentParser(
description='Two positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('color',
metavar='color',
type=str,
help='The color of the garment')
parser.add_argument('size',
metavar='size',
type=int,
help='The size of the garment')
return parser.parse_args() |
main | def main():
"""main"""
args = get_args()
print('color =', args.color)
print('size =', args.size) |
Get arguments | def get_args() -> Args:
"""Get arguments"""
parser = argparse.ArgumentParser(
description='Create Python argparse program',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
defaults = get_defaults()
username = os.getenv('USER') or 'Anonymous'
hostname = os.getenv('HOSTNAME') or 'localhost'
parser.add_argument('program', help='Program name', type=str)
parser.add_argument('-n',
'--name',
type=str,
default=defaults.get('name', username),
help='Name for docstring')
parser.add_argument('-e',
'--email',
type=str,
default=defaults.get('email', f'{username}@{hostname}'),
help='Email for docstring')
parser.add_argument('-p',
'--purpose',
type=str,
default=defaults.get('purpose', 'Rock the Casbah'),
help='Purpose for docstring')
parser.add_argument('-f',
'--force',
help='Overwrite existing',
action='store_true')
args = parser.parse_args()
args.program = args.program.strip().replace('-', '_')
if not args.program:
parser.error(f'Not a usable filename "{args.program}"')
return Args(args.program, args.name, args.email, args.purpose, args.force) |
Make a jazz noise here | def main() -> None:
"""Make a jazz noise here"""
args = get_args()
program = args.program
if os.path.isfile(program) and not args.overwrite:
answer = input(f'"{program}" exists. Overwrite? [yN] ')
if not answer.lower().startswith('y'):
sys.exit('Will not overwrite. Bye!')
print(body(args), file=open(program, 'wt'), end='')
if platform.system() != 'Windows':
subprocess.run(['chmod', '+x', program], check=True)
print(f'Done, see new script "{program}."') |
The program template | def body(args: Args) -> str:
""" The program template """
today = str(date.today())
return f"""#!/usr/bin/env python3
\"\"\"
Author : {args.name}{' <' + args.email + '>' if args.email else ''}
Date : {today}
Purpose: {args.purpose}
\"\"\"
import argparse
# --------------------------------------------------
def get_args():
\"\"\"Get command-line arguments\"\"\"
parser = argparse.ArgumentParser(
description='{args.purpose}',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('positional',
metavar='str',
help='A positional argument')
parser.add_argument('-a',
'--arg',
help='A named string argument',
metavar='str',
type=str,
default='')
parser.add_argument('-i',
'--int',
help='A named integer argument',
metavar='int',
type=int,
default=0)
parser.add_argument('-f',
'--file',
help='A readable file',
metavar='FILE',
type=argparse.FileType('rt'),
default=None)
parser.add_argument('-o',
'--on',
help='A boolean flag',
action='store_true')
return parser.parse_args()
# --------------------------------------------------
def main():
\"\"\"Make a jazz noise here\"\"\"
args = get_args()
str_arg = args.arg
int_arg = args.int
file_arg = args.file
flag_arg = args.on
pos_arg = args.positional
print(f'str_arg = "{{str_arg}}"')
print(f'int_arg = "{{int_arg}}"')
print('file_arg = "{{}}"'.format(file_arg.name if file_arg else ''))
print(f'flag_arg = "{{flag_arg}}"')
print(f'positional = "{{pos_arg}}"')
# --------------------------------------------------
if __name__ == '__main__':
main()
""" |
Get defaults from ~/.new.py | def get_defaults():
"""Get defaults from ~/.new.py"""
rc = os.path.join(str(Path.home()), '.new.py')
defaults = {}
if os.path.isfile(rc):
for line in open(rc):
match = re.match('([^=]+)=([^=]+)', line)
if match:
key, val = map(str.strip, match.groups())
if key and val:
defaults[key] = val
return defaults |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_no_arg_and_usage():
"""usage"""
for flag in ['', '-h', '--help']:
out = getoutput(f'{prg} {flag}')
assert out.lower().startswith('usage') |
Run a single base test | def run_single(base):
"""Run a single base test"""
num = random.randint(1, 10)
given = base * num
rv, out = getstatusoutput(f'{prg} {given}')
assert rv == 0
cmp = base.upper()
expected = f'{num} 0 0 0' if cmp == 'A' else \
f'0 {num} 0 0' if cmp == 'C' else \
f'0 0 {num} 0' if cmp == 'G' else \
f'0 0 0 {num}'
assert out == expected |
A | def test_a_upper():
"""A"""
run_single('A') |
a | def test_a_lower():
"""a"""
run_single('a') |
C | def test_c_upper():
"""C"""
run_single('C') |
c | def test_c_lower():
"""c"""
run_single('c') |
G | def test_g_upper():
"""G"""
run_single('G') |
g | def test_g_lower():
"""g"""
run_single('g') |
T | def test_t_upper():
"""T"""
run_single('T') |
t | def test_t_lower():
"""t"""
run_single('t') |
From http://rosalind.info/problems/dna/ | def test_rosalind_example():
"""From http://rosalind.info/problems/dna/"""
dna = ('AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATT'
'AAAAAAAGAGTGTCTGATAGCAGC')
rv, out = getstatusoutput(f'{prg} {dna}')
assert rv == 0
assert out == '20 12 17 21' |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert out.lower().startswith('usage') |
masculine_lower | def test_masculine_lower():
"""masculine_lower"""
word = random.choice('chico teatro cartero'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'Me gusto el {word}.' |
masculine_upper | def test_masculine_upper():
"""masculine_upper"""
word = random.choice('CHICO TEATRO CARTERO'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'Me gusto el {word}.' |
feminine_lower | def test_feminine_lower():
"""feminine_lower"""
word = random.choice('chica gata abuela'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'Me gusto la {word}.' |
feminine_upper | def test_feminine_upper():
"""feminine_upper"""
word = random.choice('CHICA GATA ABUELA'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'Me gusto la {word}.' |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert out.lower().startswith('usage') |
upper | def test_upper():
"""upper"""
word = random.choice('APPLE BANANA CHERRY'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'{word} is uppercase.' |
lower | def test_lower():
"""lower"""
word = random.choice('apple banana cherry'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'{word} is lowercase.' |
title | def test_title():
"""title"""
word = random.choice('Apple Banana Cherry'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'{word} is title case.' |
digit | def test_digit():
"""digit"""
word = random.choice('1 2 3'.split())
rv, out = getstatusoutput(f'{prg} {word}')
assert rv == 0
assert out == f'{word} is a digit.' |
space | def test_space():
"""space"""
word = random.choice([' ', '\t'])
rv, out = getstatusoutput(f'{prg} "{word}"')
assert rv == 0
assert out == f'input is space.' |
unclassified | def test_unclassified():
"""unclassified"""
word = random.choice('1.2 3.04 40.5'.split())
rv, out = getstatusoutput(f'{prg} "{word}"')
assert rv == 0
assert out == f'{word} is unclassified.' |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert out.lower().startswith('usage') |
nothing | def test_nothing():
"""nothing"""
rv, out = getstatusoutput(f'{prg}')
assert rv == 0
assert out.rstrip() == 'You have failed me for the last time, Commander.' |
one element | def test_one_element():
"""one element"""
rv, out = getstatusoutput(f'{prg} foo')
assert rv == 0
assert out.rstrip() == ' 1: foo' |
two elements | def test_two_elements():
"""two elements"""
rv, out = getstatusoutput(f'{prg} foo bar')
assert rv == 0
assert out.rstrip() == ' 1: bar\n 2: foo' |
two elements reversed | def test_two_elements_reversed():
"""two elements reversed"""
rev = '-r' if random.choice([0, 1]) else '--reverse'
rv, out = getstatusoutput(f'{prg} foo bar {rev}')
assert rv == 0
assert out.rstrip() == ' 1: foo\n 2: bar' |
MOAR | def test_more():
"""MOAR"""
items = 'one two three four five six seven eight nine ten zero'
rv, out = getstatusoutput(f'{prg} {items}')
assert rv == 0
expected = '\n'.join([
' 1: eight', ' 2: five', ' 3: four', ' 4: nine', ' 5: one',
' 6: seven', ' 7: six', ' 8: ten', ' 9: three', ' 10: two',
' 11: zero'
])
assert out.rstrip() == expected |
MOAR | def test_more_reverse():
"""MOAR"""
items = 'one two three four five six seven eight nine ten zero'
rev = '-r' if random.choice([0, 1]) else '--reverse'
rv, out = getstatusoutput(f'{prg} {items} {rev}')
assert rv == 0
expected = '\n'.join([
' 1: zero', ' 2: two', ' 3: three', ' 4: ten', ' 5: six',
' 6: seven', ' 7: one', ' 8: nine', ' 9: four', ' 10: five',
' 11: eight'
])
assert out.rstrip() == expected |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert out.lower().startswith('usage') |
Run a day | def run_day(day, expected):
"""Run a day"""
rv, out = getstatusoutput(f'{prg} {day}')
assert rv == 0
assert out == expected |
Monday | def test_monday():
"""Monday"""
run_day('Monday', 'On Mondays I never go to work') |
Tuesday | def test_tuesday():
"""Tuesday"""
run_day('Tuesday', 'On Tuesdays I stay at home') |
Wednesday | def test_wednesday():
"""Wednesday"""
run_day('Wednesday', 'On Wednesdays I never feel inclined') |
Thursday | def test_thursday():
"""Thursday"""
run_day('Thursday', "On Thursdays, it's a holiday") |
Friday | def test_friday():
"""Friday"""
run_day('Friday', 'And Fridays I detest') |
Saturday | def test_saturday():
"""Saturday"""
run_day('Saturday', "Oh, it's much too late on a Saturday") |
Sunday | def test_sunday():
"""Sunday"""
run_day('Sunday', 'And Sunday is the day of rest') |
monday | def test_lower():
"""monday"""
for day in [
'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday',
'sunday'
]:
rv, out = getstatusoutput(f'{prg} {day}')
assert rv == 0
assert out == f'Can\'t find "{day}"' |
Monday Tuesday | def test_monday_tuesday():
"""Monday Tuesday"""
run_day(
'Monday Tuesday', '\n'.join(
['On Mondays I never go to work', 'On Tuesdays I stay at home'])) |
Mix good and bad | def test_mix():
"""Mix good and bad"""
run_day(
'Sunday Odinsday Thorsday Friday', '\n'.join([
'And Sunday is the day of rest', "Can't find \"Odinsday\"",
"Can't find \"Thorsday\"", 'And Fridays I detest'
])) |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert out.lower().startswith('usage') |
Bad file | def test_bad_file():
"""Bad file"""
bad = random_string()
rv, out = getstatusoutput(f'{prg} {bad}')
assert rv != 0
assert re.search(f"No such file or directory: '{bad}'", out) |
Bad num | def test_bad_num():
"""Bad num"""
for bad in random.sample(range(-10, 1), 3):
rv, out = getstatusoutput(f'{prg} -n {bad} {sonnet}')
assert rv != 0
assert re.search(f'--num "{bad}" must be greater than 0', out) |
Default --num | def test_default():
"""Default --num"""
rv, out = getstatusoutput(f'{prg} {sonnet}')
assert rv == 0
assert len(out.splitlines()) == 10
expected = """
Sonnet 29
William Shakespeare
When, in disgrace with fortune and men’s eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate,
Wishing me like to one more rich in hope,
Featured like him, like him with friends possessed,
Desiring this man’s art and that man’s scope,
""".strip()
assert out.strip() == expected |
--num 1 | def test_num_1():
"""--num 1"""
rv, out = getstatusoutput(f'{prg} --num 1 {gettysburg}')
assert rv == 0
assert len(out.splitlines()) == 1
assert out.strip(
) == 'Four score and seven years ago our fathers brought forth on this' |
-n 2 | def test_n_2():
"""-n 2"""
rv, out = getstatusoutput(f'{prg} -n 2 {sonnet}')
assert rv == 0
assert len(out.splitlines()) == 2
expected = 'Sonnet 29\nWilliam Shakespeare'
assert out.strip() == expected |
--num 2 | def test_num_3():
"""--num 2"""
rv, out = getstatusoutput(f'{prg} --num 3 {bustle}')
assert rv == 0
assert len(out.splitlines()) == 3
expected = '\n'.join([
'The bustle in a house', 'The morning after death',
'Is solemnest of industries'
])
assert out.strip() == expected |
generate a random string | def random_string():
"""generate a random string"""
k = random.randint(5, 10)
return ''.join(random.choices(string.ascii_letters + string.digits, k=k)) |
generate a random filename | def random_filename():
"""generate a random filename"""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) |
usage | def test_exists():
"""usage"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput('{} {}'.format(prg, flag))
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
die on no args | def test_no_args():
"""die on no args"""
rv, out = getstatusoutput(prg)
assert rv != 0
assert re.match("usage", out, re.IGNORECASE) |
die on missing input | def test_missing_input():
"""die on missing input"""
rv, out = getstatusoutput('{} -c codons.rna'.format(prg))
assert rv != 0
assert re.match("usage", out, re.IGNORECASE) |
die on missing codons | def test_missing_codons():
"""die on missing codons"""
rv, out = getstatusoutput('{} {}'.format(prg, dna))
assert rv > 0
assert re.match("usage", out, re.IGNORECASE) |
die on bad codon_file | def test_bad_codon_file():
"""die on bad codon_file"""
bad = random_filename()
rv, out = getstatusoutput('{} --codons {} {}'.format(prg, bad, dna))
assert rv > 0
assert re.search(f"No such file or directory: '{bad}'", out) |
runs on good input | def test_good_input1():
"""runs on good input"""
run(rna, 'codons.rna', 'WPWRPELRSIVPVLTGE') |
runs on good input | def test_good_input2():
"""runs on good input"""
run(dna, 'codons.dna', 'ELHRSPG') |
runs on good input | def test_good_input3():
"""runs on good input"""
run(rna, 'codons.dna', '-P-RPE-R---P--T-E') |
runs on good input | def test_good_input4():
"""runs on good input"""
run(dna, 'codons.rna', 'E-H----') |
runs ok | def run(input_seq, codons, expected):
"""runs ok"""
random_file = random_filename()
try:
flip = random.randint(0, 1)
out_file, out_arg = (random_file,
'-o ' + random_file) if flip == 1 else ('out.txt',
'')
print(f'{prg} -c {codons} {out_arg} {input_seq}')
rv, output = getstatusoutput(f'{prg} -c {codons} {out_arg} {input_seq}')
assert rv == 0
assert output.rstrip() == f'Output written to "{out_file}".'
assert os.path.isfile(out_file)
assert open(out_file).read().strip() == expected
finally:
if os.path.isfile(out_file):
os.remove(out_file) |
generate a random filename | def random_filename():
"""generate a random filename"""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) |
usage | def test_exists():
"""usage"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput('{} {}'.format(prg, flag))
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
die on no args | def test_no_args():
"""die on no args"""
rv, out = getstatusoutput(prg)
assert rv != 0
assert re.match("usage", out, re.IGNORECASE) |
die on missing input | def test_bad_file():
"""die on missing input"""
bad = random_filename()
rv, out = getstatusoutput(f'{prg} {bad}')
assert rv != 0
assert re.match('usage:', out, re.I)
assert re.search(f"No such file or directory: '{bad}'", out) |
runs on good input | def test_good_input1():
"""runs on good input"""
out_dir = 'out'
try:
if os.path.isdir(out_dir):
rmtree(out_dir)
rv, out = getstatusoutput(f'{prg} {input1}')
assert rv == 0
assert out == 'Done, wrote 1 sequence in 1 file to directory "out".'
assert os.path.isdir(out_dir)
out_file = os.path.join(out_dir, 'input1.txt')
assert os.path.isfile(out_file)
assert open(out_file).read().rstrip() == 'GAUGGAACUUGACUACGUAAAUU'
finally:
if os.path.isdir(out_dir):
rmtree(out_dir) |
runs on good input | def test_good_input2():
"""runs on good input"""
out_dir = random_filename()
try:
if os.path.isdir(out_dir):
rmtree(out_dir)
rv, out = getstatusoutput(f'{prg} -o {out_dir} {input2}')
assert rv == 0
assert out == f'Done, wrote 2 sequences in 1 file to directory "{out_dir}".'
assert os.path.isdir(out_dir)
out_file = os.path.join(out_dir, 'input2.txt')
assert os.path.isfile(out_file)
assert open(out_file).read().rstrip() == output2().rstrip()
finally:
if os.path.isdir(out_dir):
rmtree(out_dir) |
runs on good input | def test_good_multiple_inputs():
"""runs on good input"""
out_dir = random_filename()
try:
if os.path.isdir(out_dir):
rmtree(out_dir)
rv, out = getstatusoutput(f'{prg} --outdir {out_dir} {input1} {input2}')
assert rv == 0
assert out == f'Done, wrote 3 sequences in 2 files to directory "{out_dir}".'
assert os.path.isdir(out_dir)
out_file1 = os.path.join(out_dir, 'input1.txt')
out_file2 = os.path.join(out_dir, 'input2.txt')
assert os.path.isfile(out_file1)
assert os.path.isfile(out_file2)
assert open(out_file1).read().rstrip() == 'GAUGGAACUUGACUACGUAAAUU'
assert open(out_file2).read().rstrip() == output2().rstrip()
finally:
if os.path.isdir(out_dir):
rmtree(out_dir) |
generate a random string | def random_string():
"""generate a random string"""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) |
usage | def test_exists():
"""usage"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput('{} {}'.format(prg, flag))
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
die on bad seqtype | def test_bad_seqtype():
"""die on bad seqtype"""
bad = random_string()
rv, out = getstatusoutput(f'{prg} -t {bad}')
assert rv != 0
assert re.match('usage:', out, re.I)
assert re.search(
f"-t/--seqtype: invalid choice: '{bad}' \(choose from 'dna', 'rna'\)",
out) |
die on bad pctgc | def test_bad_pctgc():
"""die on bad pctgc"""
bad = random.randint(1, 10)
rv, out = getstatusoutput(f'{prg} -p {bad}')
assert rv != 0
assert re.match('usage:', out, re.I)
assert re.search(f'--pctgc "{float(bad)}" must be between 0 and 1', out) |
runs on good input | def test_defaults():
"""runs on good input"""
out_file = 'out.fa'
try:
if os.path.isfile(out_file):
os.remove(out_file)
rv, out = getstatusoutput(prg)
assert rv == 0
assert out == f'Done, wrote 10 DNA sequences to "{out_file}".'
assert os.path.isfile(out_file)
# correct number of seqs
seqs = list(SeqIO.parse(out_file, 'fasta'))
assert len(seqs) == 10
# the lengths are in the correct range
seq_lens = list(map(lambda seq: len(seq.seq), seqs))
assert max(seq_lens) <= 75
assert min(seq_lens) >= 50
# bases are correct
bases = ''.join(
sorted(
set(chain(map(lambda seq: ''.join(sorted(set(seq.seq))),
seqs)))))
assert bases == 'ACGT'
# the pct GC is about right
gc = list(map(lambda seq: GC(seq.seq) / 100, seqs))
assert .47 <= mean(gc) <= .53
finally:
if os.path.isfile(out_file):
os.remove(out_file) |
runs on good input | def test_options():
"""runs on good input"""
out_file = random_string() + '.fasta'
try:
if os.path.isfile(out_file):
os.remove(out_file)
min_len = random.randint(50, 99)
max_len = random.randint(100, 150)
num_seqs = random.randint(100, 150)
pct_gc = random.random()
cmd = (f'{prg} -m {min_len} -x {max_len} -o {out_file} '
f'-n {num_seqs} -t rna -p {pct_gc:.02f} -s 1')
rv, out = getstatusoutput(cmd)
assert rv == 0
assert out == f'Done, wrote {num_seqs} RNA sequences to "{out_file}".'
assert os.path.isfile(out_file)
# correct number of seqs
seqs = list(SeqIO.parse(out_file, 'fasta'))
assert len(seqs) == num_seqs
# the lengths are in the correct range
seq_lens = list(map(lambda seq: len(seq.seq), seqs))
assert max(seq_lens) <= max_len
assert min(seq_lens) >= min_len
# bases are correct
bases = ''.join(
sorted(
set(chain(map(lambda seq: ''.join(sorted(set(seq.seq))),
seqs)))))
assert bases == 'ACGU'
# the pct GC is about right
gc = list(map(lambda seq: GC(seq.seq) / 100, seqs))
assert pct_gc - .3 <= mean(gc) <= pct_gc + .3
finally:
if os.path.isfile(out_file):
os.remove(out_file) |
get args | def get_args():
"""get args"""
parser = argparse.ArgumentParser(
description='Probabalistically subset FASTA files',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
metavar='FILE',
type=argparse.FileType('r'),
nargs='+',
help='Input FASTA file(s)')
parser.add_argument('-p',
'--pct',
help='Percent of reads',
metavar='reads',
type=float,
default=.1)
parser.add_argument('-s',
'--seed',
help='Random seed value',
metavar='seed',
type=int,
default=None)
parser.add_argument('-o',
'--outdir',
help='Output directory',
metavar='DIR',
type=str,
default='out')
args = parser.parse_args()
if not 0 < args.pct < 1:
parser.error(f'--pct "{args.pct}" must be between 0 and 1')
if not os.path.isdir(args.outdir):
os.makedirs(args.outdir)
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
random.seed(args.seed)
total_num = 0
for i, fh in enumerate(args.file, start=1):
basename = os.path.basename(fh.name)
out_file = os.path.join(args.outdir, basename)
print(f'{i:3}: {basename}')
out_fh = open(out_file, 'wt')
num_taken = 0
for rec in SeqIO.parse(fh, 'fasta'):
if random.random() <= args.pct:
num_taken += 1
SeqIO.write(rec, out_fh, 'fasta')
out_fh.close()
total_num += num_taken
num_files = len(args.file)
print(f'Wrote {total_num:,} sequence{"" if total_num == 1 else "s"} '
f'from {num_files:,} file{"" if num_files == 1 else "s"} '
f'to directory "{args.outdir}"') |
generate a random string | def random_string():
"""generate a random string"""
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) |
usage | def test_exists():
"""usage"""
for file in [prg, n1k, n10k, n100k, n1m]:
assert os.path.isfile(file) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput('{} {}'.format(prg, flag))
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
die on bad file | def test_bad_file():
"""die on bad file"""
bad = random_string()
rv, out = getstatusoutput(f'{prg} {bad}')
assert rv != 0
assert re.match('usage:', out, re.I)
assert re.search(f"No such file or directory: '{bad}'", out) |
die on bad pct | def test_bad_pct():
"""die on bad pct"""
bad = random.randint(1, 10)
rv, out = getstatusoutput(f'{prg} -p {bad} {n1k}')
assert rv != 0
assert re.match('usage:', out, re.I)
assert re.search(f'--pct "{float(bad)}" must be between 0 and 1', out) |
runs on good input | def test_defaults():
"""runs on good input"""
out_dir = 'out'
try:
if os.path.isdir(out_dir):
rmtree(out_dir)
rv, out = getstatusoutput(f'{prg} -s 10 {n1k}')
assert rv == 0
expected = (' 1: n1k.fa\n'
'Wrote 108 sequences from 1 file to directory "out"')
assert out == expected
assert os.path.isdir(out_dir)
files = os.listdir(out_dir)
assert len(files) == 1
out_file = os.path.join(out_dir, 'n1k.fa')
assert os.path.isfile(out_file)
# correct number of seqs
seqs = list(SeqIO.parse(out_file, 'fasta'))
assert len(seqs) == 108
finally:
if os.path.isdir(out_dir):
rmtree(out_dir) |
runs on good input | def test_options():
"""runs on good input"""
out_dir = random_string()
try:
if os.path.isdir(out_dir):
rmtree(out_dir)
cmd = f'{prg} -s 4 -o {out_dir} -p .25 {n1k} {n10k} {n100k}'
print(cmd)
rv, out = getstatusoutput(cmd)
assert rv == 0
assert re.search('1: n1k.fa', out)
assert re.search('2: n10k.fa', out)
assert re.search('3: n100k.fa', out)
assert re.search(
f'Wrote 27,688 sequences from 3 files to directory "{out_dir}"',
out)
assert os.path.isdir(out_dir)
files = os.listdir(out_dir)
assert len(files) == 3
seqs_written = 0
for file in files:
seqs_written += len(
list(SeqIO.parse(os.path.join(out_dir, file), 'fasta')))
assert seqs_written == 27688
finally:
if os.path.isdir(out_dir):
rmtree(out_dir) |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('positional',
metavar='str',
help='A positional argument')
parser.add_argument('-a',
'--arg',
help='A named string argument',
metavar='str',
type=str,
default='')
parser.add_argument('-i',
'--int',
help='A named integer argument',
metavar='int',
type=int,
default=0)
parser.add_argument('-f',
'--file',
help='A readable file',
metavar='FILE',
type=argparse.FileType('r'),
default=None)
parser.add_argument('-o',
'--on',
help='A boolean flag',
action='store_true')
return parser.parse_args() |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
str_arg = args.arg
int_arg = args.int
file_arg = args.file
flag_arg = args.on
pos_arg = args.positional
print(f'str_arg = "{str_arg}"')
print(f'int_arg = "{int_arg}"')
print('file_arg = "{}"'.format(file_arg.name if file_arg else ''))
print(f'flag_arg = "{flag_arg}"')
print(f'positional = "{pos_arg}"') |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.