Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesFor most Python scripts, parse command-line arguments with the standard-library argparse module. Define positional inputs and options with add_argument(), call parse_args(), then use the resulting Namespace attributes. Python generates help text and reports common input errors for you.
How do I parse command-line arguments in Python?
Start with an ArgumentParser, describe each input, and parse the arguments. This small script accepts two required integers and an optional flag:
import argparse
parser = argparse.ArgumentParser(description="Add two integers.")
parser.add_argument("left", type=int, help="first integer")
parser.add_argument("right", type=int, help="second integer")
parser.add_argument("--verbose", action="store_true", help="show a labeled result")
args = parser.parse_args()
result = args.left + args.right
print(f"{args.left} + {args.right} = {result}" if args.verbose else result)
Save it as add.py and run it from a terminal:
python add.py 3 8
python add.py 3 8 --verbose
python add.py --help
The first command prints 11; the second prints 3 + 8 = 11. The help option displays usage generated from the parser definition. The official Python Argparse Tutorial calls argparse the recommended command-line parsing module in the standard library.
What happens when you call parse_args()?
add_argument() describes how command-line tokens should be interpreted; parse_args() reads and validates those tokens. With no argument passed to the method, it reads the command-line arguments from sys.argv. The parsed values are returned as attributes on a Namespace, such as args.left and args.verbose. See the argparse API reference.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
You can instead supply a list of strings. This is useful for testing parsing behavior without launching the script as a separate process:
args = parser.parse_args(["3", "8", "--verbose"])
print(args.left, args.right, args.verbose)
Because left and right were declared with type=int, the two values in the namespace are integers, not strings. The API reference and the Python command-line documentation explain the relationship between the interpreter’s command line and the arguments available to a program.
How do I add positional arguments and options?
A positional argument is identified by its place in the command, while an option is introduced by a flag such as --output. Choose names and help text that make the command understandable to someone who has not read the source.
Required positional values
A bare name creates a required positional argument. For example, parser.add_argument("filename") makes the script expect a filename after the script name. Positional values are appropriate when the command has a natural order and the values are essential to its main task.
Named options and defaults
Use one or more option strings to create a flag or a value-taking option. A short and long spelling can refer to the same value:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
parser.add_argument("-o", "--output", default="result.txt",
help="path for the output file")
If the user omits this option, the value is result.txt. The default is also available as an attribute on the parsed namespace. Use required=True when an option-style value must be supplied, though a required positional is often clearer for a core input.
Convert and constrain values
Set type to convert a supplied value, such as type=int. Use choices to limit accepted values to a known set:
parser.add_argument("--format", choices=["json", "csv"], default="json")
If a user supplies an invalid integer or a value outside the declared choices, the parser reports an error rather than leaving your program to handle an unchecked string. For more complex validation or conversion, define the behavior deliberately rather than silently accepting a value your program cannot use.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →How do I add flags, repeatable options, and mutually exclusive choices?
Boolean on/off flags
For a flag that is false when omitted and true when present, use action="store_true". In the opening example, --verbose works this way. This is clearer than asking a user to type a value such as --verbose true.
Count repeated flags
Use action="count" when each repetition should increase a counter, for example to support -v and -vv:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
parser.add_argument("-v", "--verbose", action="count", default=0,
help="increase verbosity; repeat for more detail")
Then branch on args.verbose to choose the amount of diagnostic output. Set a default explicitly when your code expects a numeric count even if the option is absent.
Arguments that consume multiple values
Use nargs to specify how many values an argument consumes or to express a variable number of values. For example, nargs=2 accepts exactly two values, while nargs="+" accepts one or more. Select a form that makes the command’s expected input unambiguous; the returned value for a multi-value argument is a sequence rather than a single scalar.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Options that cannot be combined
When two choices are incompatible, define a mutually exclusive group so the parser can reject a command that supplies both:
group = parser.add_mutually_exclusive_group()
group.add_argument("--quiet", action="store_true")
group.add_argument("--verbose", action="store_true")
Add required=True to the group only if the user must choose one of its options. The official Argparse Tutorial covers actions, nargs, and mutually exclusive groups.
How do I display help and handle invalid input?
Give the parser a description and each argument a help string. Running the program with --help (or -h) displays generated usage and option descriptions. You usually do not need to implement a separate help screen for a straightforward command-line tool.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
If the user omits a required positional argument, supplies a value that cannot be converted by type, or uses an unrecognized argument, argparse prints usage and an error message. This behavior helps users correct invocation mistakes. Keep help text concrete: explain what a value controls, its expected format, and any meaningful default.
What if a positional value starts with a hyphen?
A value such as -f may look like an option. Put -- before it to indicate that subsequent tokens should be treated as positional input:
python my_script.py -- -f
The tutorial demonstrates the same delimiter with parse_args(["--", "-f"]). This is particularly useful when a filename or other positional value begins with a hyphen and could otherwise be interpreted as an option.
How do I choose between argparse, optparse, and getopt?
| Need | Suitable choice | Guidance |
|---|---|---|
| A typical new script or command-line tool | argparse |
The standard-library recommendation for general use, with positional and optional arguments, conversion, validation, help, and subcommands. Python Argparse Tutorial |
| An established program already built around older option parsing | optparse or a planned migration |
Check compatibility and behavior before changing an existing command interface. Python command-line libraries |
| C-style option processing or a deliberately low-level interface | getopt |
Python documents it as a C-style parser and provides an argparse equivalent. Python getopt documentation |
For new general-purpose interfaces, begin with argparse. Do not change an established tool solely for stylistic reasons: compare interface compatibility and the behavior your users and scripts depend on. The argparse API reference describes differences from optparse, including positional arguments and subcommands.
How can I test argument parsing?
Separate parsing from the rest of the program when the parser needs to be exercised by tests or called by other Python code. One simple pattern is to define a function that accepts an explicit argument list:
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
import argparse
def parse_arguments(argv=None):
parser = argparse.ArgumentParser(description="Add two integers.")
parser.add_argument("left", type=int)
parser.add_argument("right", type=int)
parser.add_argument("--verbose", action="store_true")
return parser.parse_args(argv)
if __name__ == "__main__":
args = parse_arguments()
total = args.left + args.right
print(f"{args.left} + {args.right} = {total}" if args.verbose else total)
When called without a list, parse_arguments() retains the usual behavior of parsing the process command line. A test can pass a fixed list such as ["3", "8", "--verbose"], inspect the returned attributes, and verify the conversion and flag behavior without depending on a user’s terminal invocation.
Troubleshooting common argparse problems
- “The following arguments are required”: Supply the missing positional input, or revise the declaration if it was meant to be optional. A bare positional name is required by default.
- “Invalid int value” or a similar conversion error: Check that the token matches the declared
type. If the input is not meant to be an integer, remove or change that conversion deliberately. - “Unrecognized arguments”: Check spelling and whether a value-taking option has its value. If a token is intended as a hyphen-leading positional value, place
--before it. - An option is unexpectedly false or missing: Confirm the invocation includes the flag and that the code reads the correct namespace attribute. With
store_true, omission means false. - Two options conflict: If they are mutually exclusive, provide only one. If they should be compatible, do not put them in the same mutually exclusive group.
- Tests read the real process arguments: Pass a list to
parse_args()or to a wrapper function acceptingargv; no-argument parsing readssys.argv.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server, so it is not an argument-parsing library or a substitute for argparse. If your command-line task is to capture a web page instead, one GET request can return an image or PDF. See the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo removes known cookie-consent banners, newsletter popups, and chat widgets before capture; those cleanup steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with response headers indicating the page verdict and billing status. Its MCP server provides screenshot and PDF tools for AI agents. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000. Learn more at ScreenshotNeo, or sign up free for 1,000 screenshots a month, with no card.
Frequently Asked Questions
Does argparse come with Python?
Yes. It is part of Python’s standard library, so a typical installation does not require a separate package install.
What does parse_args() return?
It returns an argparse Namespace whose attributes correspond to the arguments declared on the parser.
Can I use argparse inside a notebook or another Python function?
Yes. Pass a list of strings to parse_args() when you want to parse a controlled set of arguments rather than the current process command line.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

