Python Practice › sys Module Programs › Program 19
Arguments with argparse
Write a Python program that parses named options with argparse.
Output
smoke firefox 2
Approach
- Pass a list to
parse_argsto test without a terminal.
Solution
import argparse parser = argparse.ArgumentParser(description="Run tests")parser.add_argument("suite")parser.add_argument("--browser", default="chromium", choices=["chromium", "firefox", "webkit"])parser.add_argument("--retries", type=int, default=0) args = parser.parse_args(["smoke", "--browser", "firefox", "--retries", "2"])print(args.suite, args.browser, args.retries)Output
smoke firefox 2
Line by line
Line 8
In a real script call parser.parse_args() with no list to read sys.argv.
Learn the concept
New to this topic? Read the lesson, then come back.