Python Basics12/13
Starting sandbox…
Beginner·3 graded tests

Command-Line Arguments

Command-line programs receive their settings as arguments. The argparse module in the standard library reads those arguments, converts them to the types the program expects, and reports an error when they are missing or malformed. It is imported the same way as any other standard library module.

[1]python
out1ms
filter_variants

ArgumentParser holds the definition of the interface. Each call to add_argument declares one option: its name, the type its value is converted to, and the value used when the option is absent.

Reading the arguments

parse_args returns an object whose attributes hold the parsed values. A leading -- is stripped and internal hyphens become underscores, so --min-depth is read back as args.min_depth.

[2]python
out1ms
30 TP53
<class 'int'>

Because type=int was declared, the string "30" arrives as the integer 30. Without it, every value would remain a string.

Omitted options take their declared defaults.

[3]python
out1ms
10 any

Positional arguments and flags

A name declared without a leading -- is positional: it is required, and it is read from its place in the argument list. action="store_true" declares a flag that takes no value and is True only when present.

[4]python
out1ms
Namespace(vcf='variants.vcf', verbose=True)

Where the arguments come from

Called with no argument, parse_args() reads sys.argv[1:], which is what the shell passed to the program. Called with a list, it parses that list instead. Doing the parsing inside a function that accepts the list makes the function testable without running the program from a shell.

[5]python
out1ms
25
10

When an argument is missing or cannot be converted, argparse prints a usage message and exits rather than raising an exception the program could catch. That behaviour is correct for a command-line program, and it is the reason no validation code for these options is written by hand.

Task

Write parse_options(argv). Build an ArgumentParser, declare --min-depth as an integer with default 10 and --gene with default "any", parse the given list, and return "depth=<min-depth> gene=<gene>".

exerciseEvery submission runs independently in a fresh namespace.

Test cases · 3

#viainputexpected stdout
1stdin--min-depth 30 --gene TP53depth=30 gene=TP53
2stdin·depth=10 gene=any
3stdin--gene BRCA1depth=10 gene=BRCA1

Hints · 2

01Hint

A --min-depth option is read back as args.min_depth.

02Hint

type=int converts the value; default supplies it when absent.