Table of contents

  1. Python | How to Parse Command-Line Options
  2. Command-line options to IPython *scripts*?
  3. How to determine if Python script was run via command line?

Python | How to Parse Command-Line Options

Parsing command-line options in Python is typically done using the built-in argparse module. It provides a lot of flexibility in defining and reading command-line arguments. Here's a step-by-step guide on how to parse command-line options using argparse.

1. Basic Parsing:

import argparse

# Initialize the parser
parser = argparse.ArgumentParser(description="A simple argument parser")

# Add arguments
parser.add_argument("name", help="Your name")

# Parse arguments
args = parser.parse_args()

# Use arguments
print(f"Hello, {args.name}!")

Run the script:

$ python script.py Alice
Hello, Alice!

2. Different Types of Arguments:

  • Positional arguments: As shown above, "name" is a positional argument. It is required to be passed.

  • Optional arguments: These are often used for switches or to specify additional configurations.

parser.add_argument("-v", "--verbose", help="Increase output verbosity", action="store_true")
  • Default values and data types: You can set default values and specify the type of the argument.
parser.add_argument("-n", "--number", help="An integer number", type=int, default=0)

3. A More Comprehensive Example:

import argparse

parser = argparse.ArgumentParser(description="A program that accepts command line options")

parser.add_argument("username", help="Username for the application")

parser.add_argument("-v", "--verbose", help="Increase output verbosity", action="store_true")

parser.add_argument("-a", "--age", help="Your age", type=int)

parser.add_argument("-e", "--email", help="Your email address", default="[email protected]")

args = parser.parse_args()

print(f"Username: {args.username}")
if args.verbose:
    print("Verbose mode is ON!")
if args.age:
    print(f"Age: {args.age}")
print(f"Email: {args.email}")

Run the script:

$ python script.py Alice -v -a 30
Username: Alice
Verbose mode is ON!
Age: 30
Email: [email protected]

4. Other useful features:

  • Choices: Restrict the value of the argument to a set of specific values.
parser.add_argument("--color", choices=["red", "green", "blue"])
  • add_mutually_exclusive_group(): Ensure that only one of the arguments in the group is provided.
group = parser.add_mutually_exclusive_group()
group.add_argument("--admin", action="store_true")
group.add_argument("--user", action="store_true")

The argparse module provides even more capabilities, like customizing help messages, handling sub-commands, and so on. Always refer to the official Python documentation for a comprehensive overview of its features.


Command-line options to IPython *scripts*?

IPython provides a way to pass command-line options to Python scripts using the sys.argv list. Here's how you can do it:

  1. Import the sys module to access the sys.argv list, which contains the command-line arguments passed to the script.

  2. Parse the command-line arguments and perform the desired actions based on those arguments.

Here's a simple example:

import sys

def main():
    if len(sys.argv) != 2:
        print("Usage: python myscript.py <arg>")
        sys.exit(1)

    arg = sys.argv[1]
    print(f"Argument passed: {arg}")

if __name__ == "__main__":
    main()

In this example:

  • We import the sys module to access sys.argv.

  • In the main() function, we check the length of sys.argv to ensure that exactly one argument is passed (the script name itself counts as one argument).

  • If the correct number of arguments is not provided, we print a usage message and exit the script with a non-zero status code.

  • If the correct number of arguments is provided, we retrieve the argument value from sys.argv[1] and perform the desired actions.

You can run this script from the command line as follows:

python myscript.py myargument

Replace myscript.py with the name of your script and myargument with the value you want to pass as a command-line argument.

You can extend this example to handle more complex command-line options and arguments using libraries like argparse for more sophisticated argument parsing and validation.


How to determine if Python script was run via command line?

To determine if a Python script was run via the command line, you can check the value of the built-in variable __name__. When a Python script is run, __name__ is set to "__main__" if the script is the main program being executed. If the script is imported as a module into another script, __name__ will be set to the module's name.

Here's an example:

if __name__ == "__main__":
    print("This script was run via the command line.")
else:
    print("This script was imported as a module.")

When you run this script from the command line, it will print "This script was run via the command line." If you import this script as a module into another script, it will print "This script was imported as a module."

This technique is commonly used to create Python scripts that can be both run as standalone programs and imported as modules into other scripts without executing the code inside the if __name__ == "__main__": block when imported.


More Python Questions

More C# Questions