Alright ! Let’s talk about argument parsing in Python the process of taking those ***** command line arguments that you don’t want to deal with and turning them into something useful for your program. It’s like a magic trick, but without all the smoke and mirrors!
First: why do we need argument parsing? Well, let’s say you have this fancy new Python script called “my_script” that does some amazing thing or another (we won’t get into details here). But what if someone wants to run it with a specific set of options? That’s where argument parsing comes in.
Now, there are plenty of libraries out there for handling arguments argparse is probably the most popular one. But let’s not use that today. Instead, we’re going to write our own custom parser using good old Python itself!
Here’s how it works: you create a function with some fancy syntax and then call it from your main script. The function takes in all of the command line arguments as a list (which is what `sys.argv` gives us), and returns a dictionary containing any options that were specified. Here’s an example:
# This script defines a function that parses command line arguments and returns a dictionary of specified options.
def parse_args(args):
# Define some default values for our options
output = "stdout" # Set default value for output option
verbose = False # Set default value for verbose option
# Loop through the arguments list to find any options we care about
for arg in args[1:]: # Loop through arguments, starting from index 1 (skipping script name)
if arg.startswith("--"): # Check if argument starts with "--"
option, value = arg[2:].split("=") # Split argument at "=" to get option and value
# Set our default values based on the specified options
if option == "output": # Check if option is "output"
output = value # Set output value to specified value
elif option == "verbose": # Check if option is "verbose"
verbose = True # Set verbose value to True
return {"output": output, "verbose": verbose} # Return dictionary with specified options and values
So what’s going on here? We start by defining some default values for our options (in this case, we only have two: `output` and `verbose`). Then we loop through the arguments list starting from index 1 (since we don’t care about the script name), looking for any options that start with “–“. If we find one, we split it into an option and a value using “=” as our delimiter. Finally, we set our default values based on the specified options.
Now let’s see how to use this function in your main script:
# Import the necessary modules
import sys
from my_script import parse_args
# Define a function to parse the command line arguments
def parse_args(args):
# Create an empty dictionary to store the parsed options
options = {}
# Loop through the command line arguments
for arg in args:
# Check if the argument starts with "--"
if arg.startswith("--"):
# Split the argument into an option and a value using "=" as the delimiter
option, value = arg.split("=")
# Add the option and value to the dictionary
options[option] = value
# Set default values for the options
if "--verbose" not in options:
options["verbose"] = False
if "--debug" not in options:
options["debug"] = False
# Return the parsed options
return options
# Call the parse_args function and pass it the command line arguments
parsed = parse_args(sys.argv)
# Use the parsed options as needed
if parsed["verbose"]:
print("Verbose mode enabled!")
# Do some other stuff with your script here...
And that’s it! You now have a custom argument parser in Python. It may not be as fancy or feature-rich as argparse, but hey at least you can say you wrote it yourself!