Arguments with argparse

Mediumsys Module Programs · 19 of 20

Write a Python program that parses named options with argparse.

Advertisement
Output
smoke firefox 2

Approach

  1. Pass a list to parse_args to test without a terminal.

Solution

Python
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.

More sys module programs

← All 20 sys Module Programs

Leave a Comment