specifying a list as a command line argument in python

Learn specifying a list as a command line argument in python with practical examples, diagrams, and best practices. Covers python development techniques with visual explanations.

Passing Lists as Command-Line Arguments in Python

Hero image for specifying a list as a command line argument in python

Learn how to effectively pass lists of values to your Python scripts via command-line arguments using argparse and other methods.

When developing Python scripts, it's common to need to pass various types of data as command-line arguments. While simple strings and numbers are straightforward, passing a list of values requires a bit more consideration. This article will guide you through different approaches to handle lists as command-line arguments in Python, focusing on the robust argparse module.

Understanding the Challenge

The command line typically treats all arguments as strings. When you want to pass multiple distinct values that logically form a list, you need a way to parse that single string argument into a Python list. For example, if you want to pass a list of file paths or a series of numbers, you can't just type python script.py --files file1.txt file2.txt. This would typically be interpreted as --files taking file1.txt as its value, and file2.txt as a separate, unassociated argument.

flowchart TD
    A[User executes script] --> B{Command-line arguments provided}
    B --> C{Arguments are strings}
    C --> D{How to represent a list?}
    D --> E["Option 1: Space-separated values"]
    D --> F["Option 2: Comma-separated string"]
    D --> G["Option 3: Multiple occurrences of same argument"]
    E --> H["Requires `nargs='*'` or `nargs='+'`"]
    F --> I["Requires string splitting"]
    G --> J["Requires `action='append'`"]
    H --> K[Python List]
    I --> K
    J --> K

Flowchart of parsing list arguments from the command line

Using argparse for Space-Separated Lists

The argparse module is the recommended way to handle command-line arguments in Python. For lists where items are separated by spaces, argparse offers the nargs argument. Setting nargs='*' allows zero or more arguments, while nargs='+' requires at least one argument. These arguments will be collected into a list.

import argparse

parser = argparse.ArgumentParser(description='Process a list of items.')
parser.add_argument('--items', nargs='+', help='A list of items (space-separated)')

args = parser.parse_args()

if args.items:
    print(f"Received items: {args.items}")
    print(f"Type of items: {type(args.items)}")
else:
    print("No items provided.")

Example using nargs='+' to parse space-separated list items.

To run this script, you would execute it like this: python your_script.py --items apple banana cherry

This would output: Received items: ['apple', 'banana', 'cherry'] Type of items: <class 'list'>

Handling Comma-Separated Strings as Lists

Sometimes, it's more convenient for users to provide a single string with comma-separated values, especially if individual items might contain spaces. In this scenario, you'll receive a single string argument, which you then need to split into a list within your script.

import argparse

parser = argparse.ArgumentParser(description='Process a comma-separated list.')
parser.add_argument('--names', type=str, help='A comma-separated list of names')

args = parser.parse_args()

if args.names:
    name_list = [name.strip() for name in args.names.split(',') if name.strip()]
    print(f"Received names: {name_list}")
    print(f"Type of names: {type(name_list)}")
else:
    print("No names provided.")

Example parsing a comma-separated string into a list.

To run this script: python your_script.py --names "Alice, Bob, Charlie"

This would output: Received names: ['Alice', 'Bob', 'Charlie'] Type of names: <class 'list'>

Notice the use of quotes around the argument to ensure the shell passes the entire string "Alice, Bob, Charlie" as a single argument.

Using action='append' for Repeated Arguments

Another powerful feature of argparse is the action='append' option. This allows you to specify the same argument multiple times on the command line, and argparse will collect all values into a list.

import argparse

parser = argparse.ArgumentParser(description='Process multiple occurrences of an argument.')
parser.add_argument('--tag', action='append', help='Add a tag (can be used multiple times)')

args = parser.parse_args()

if args.tag:
    print(f"Received tags: {args.tag}")
    print(f"Type of tags: {type(args.tag)}")
else:
    print("No tags provided.")

Example using action='append' for repeated arguments.

To run this script: python your_script.py --tag python --tag programming --tag cli

This would output: Received tags: ['python', 'programming', 'cli'] Type of tags: <class 'list'>