Explain Codes LogoExplain Codes Logo

How do I access command line arguments?

python
command-line-arguments
argparse
python-scripts
Nikita BarsukovbyNikita Barsukov·Jan 23, 2025
TLDR

Directly access command line arguments in Python with sys.argv—a list where the index sys.argv[0] is the script name, and further elements correspond to arguments. The argparse library offers a more advanced approach, offering features like assigning default values or defining specific data types.

Snippet for sys.argv usage:

import sys print(f"Arguments: {sys.argv[1:]}") # printing all command line arguments excluding script name

Snippet for argparse usage:

import argparse parser = argparse.ArgumentParser(description='Example.') # creating an ArgumentParser object parser.add_argument('arg', help='A single argument.') # adding an argument args = parser.parse_args() # parsing the arguments print(f"Received: {args.arg}") # accessing the parsed argument

Avoiding argument access pitfalls

In Python scripts, there are potential pitfalls when parsing command line arguments. Here are some proactive measures one can take:

  1. Confirm argument count before access: By checking the argument count, you can prevent the possibility of an IndexError:
import sys if len(sys.argv) > 1: # checking if any arguments have been passed print(f"Arguments: {sys.argv[1:]}") else: print("No arguments provided, just like my family at the last Python convention...") # Nerdy joke here :)
  1. Graciously handle invalid types and values: With argparse, you can manage erroneous inputs using tailored validation logic or type conversion:
import argparse def is_positive(n): value = int(n) if value <= 0: raise argparse.ArgumentTypeError("Value must be positive, like my outlook after a successful script run!") # light-hearted comment return value parser = argparse.ArgumentParser(description='Check for positive integer example.') # creating the ArgumentParser parser.add_argument('num', type=is_positive, help='A positive integer argument.') # adding an argument with custom validation args = parser.parse_args() # parsing the arguments print(f"Positive integer received: {args.num}")
  1. Use try-except blocks for safe argument parsing: Some arguments like file paths or numerical inputs may be prone to errors. To guard your script against such errors, use try-except blocks:
import sys try: filename = sys.argv[1] # trying to access the file name with open(filename, 'r') as file: # trying to open the file data = file.read() except IndexError: print("Please provide a file name. It's like going to the library and not knowing what book to read.") # friendly reminder except FileNotFoundError: print("File not found. It's like getting lost in the Matrix!") # playful comment

Advanced parsing with argparse

For a more sophisticated argument parsing, the argparse library provides several powerful features:

  1. Help generation: By providing descriptions and help messages to your parser, argparse will auto-generate a helpful output for the -h or --help flags:
import argparse parser = argparse.ArgumentParser(description='Helpful example.') # specifying a script description parser.add_argument('--option', help='Here to help!') # adding an argument with a help description args = parser.parse_args() # continue your script...
  1. Subcommands: These are a way to create additional actions within your script. This feature can be especially handy for larger scripts:
import argparse parser = argparse.ArgumentParser(description='Example with subcommands.') # creating the ArgumentParser subparsers = parser.add_subparsers(dest='subcommand', help='Available subcommands') # adding sub-parsers to handle multiple actions # defining a subcommand sub = subparsers.add_parser('start', help='Starts the process.') # add a new subcommand 'start' sub.add_argument('id', help='Process ID to start.') # adding an argument to the 'start' subcommand args = parser.parse_args() # parsing the arguments if args.subcommand == 'start': # checking if the 'start' subcommand has been used start_process(args.id) # continue...
  1. Custom argument actions: Through this feature, you can design the parser to perform custom tasks upon parsing arguments:
import argparse parser = argparse.ArgumentParser(description='Example with customized actions.') # creating the ArgumentParser # defining an action that stores multiple arguments parser.add_argument('--accumulate', nargs='+', help='Collect multiple arguments.') # defining an action that counts occurrences parser.add_argument('--repeat', action='count', default=0, help='Count the occurrences.') args = parser.parse_args() # parsing the arguments # now you can use the collected and/or counted arguments...

Alternative libraries for command line argument parsing

While sys.argv and argparse cover a wide range of use-cases, there are alternative libraries available:

  1. click: Provides a decorator-based API for creating intuitive command-line interfaces.
  2. docopt: Allows definition of command-line interfaces by parsing usage instructions.
  3. fire: Automatically turns any Python component (functions, classes, modules, etc.) into a command-line interface.

These alternatives might be worth considering for more complex scenarios, offering additional features and a different approach to command-line parsing.