Special Topic - Command-Line Arguments in Python

Command-Line Arguments in Python

Command-line arguments in Python offer a powerful way to pass information to your scripts at runtime. Whether you're automating tasks or creating dynamic programs, understanding how to leverage these arguments is crucial. Below, we explore 10 examples demonstrating the versatility of command-line arguments, covering basic usage, arithmetic operations, file handling, and more.

Example 1: Basic Command-Line Arguments

import sys

def greet():
    if len(sys.argv) != 2:
        print("Usage: script.py ")
    else:
        name = sys.argv[1]
        print(f"Hello, {name}!")

if __name__ == "__main__":
    greet()

Console Output:

C:\>python script.py John
Hello, John!

Description: This script takes a single command-line argument (a name) and prints a greeting. It checks if the correct number of arguments is provided and displays usage instructions if not.

๐Ÿ’ก

Tip: Always validate the number of arguments before proceeding with your logic to prevent unexpected errors or behaviors.

Example 2: Sum of Two Numbers

import sys

def sum_numbers():
    if len(sys.argv) != 3:
        print("Usage: script.py  ")
    else:
        num1 = int(sys.argv[1])
        num2 = int(sys.argv[2])
        print(f"Sum: {num1 + num2}")

if __name__ == "__main__":
    sum_numbers()

Console Output:

C:\>python script.py 10 20
Sum: 30

Description: This script takes two numbers as command-line arguments, converts them to integers, and prints their sum.

โž•

Trivia: Command-line arguments are always passed as strings. Remember to convert them to the appropriate type before performing arithmetic operations.

Example 3: Calculate the Area of a Rectangle

import sys

def calculate_area():
    if len(sys.argv) != 3:
        print("Usage: script.py  ")
    else:
        length = float(sys.argv[1])
        width = float(sys.argv[2])
        print(f"Area of the rectangle: {length * width}")

if __name__ == "__main__":
    calculate_area()

Console Output:

C:\>python script.py 5 3
Area of the rectangle: 15.0

Description: This script calculates the area of a rectangle given its length and width as command-line arguments.

๐Ÿ“

Tip: When working with measurements or dimensions, using floating-point numbers ensures that the calculation is precise, especially when dealing with non-integer values.

Example 4: Check for Prime Number

import sys

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

def main():
    if len(sys.argv) != 2:
        print("Usage: script.py ")
    else:
        number = int(sys.argv[1])
        print(f"{number} is {'a prime number' if is_prime(number) else 'not a prime number'}")

if __name__ == "__main__":
    main()

Console Output:

C:\>python script.py 29
29 is a prime number

Description: This script checks if a number provided as a command-line argument is prime.

๐Ÿ”

Trivia: Checking if a number is prime by iterating only up to the square root of the number is a common optimization technique in algorithms.

Example 5: File Copy Utility

import sys
import shutil

def copy_file():
    if len(sys.argv) != 3:
        print("Usage: script.py <source> <destination>")
    else:
        source = sys.argv[1]
        destination = sys.argv[2]
        shutil.copy(source, destination)
        print(f"Copied {source} to {destination}")

if __name__ == "__main__":
    copy_file()

Console Output:

C:\>python script.py file.txt copy.txt
Copied file.txt to copy.txt

Description: This script copies a file from a source path to a destination path using command-line arguments. It uses the shutil module for file operations, which simplifies tasks like copying files.

โš ๏ธ

Warning: Be cautious when running scripts with elevated privileges (e.g., as an administrator) because they can modify system files or directories. Elevated privileged scripts have more access to the system, which can be risky if the script contains errors or malicious code.

๐Ÿ—‚๏ธ

Tip: The shutil module is a powerful tool for file operations, including copying, moving, and deleting files. It simplifies tasks that would otherwise require multiple lines of code.

Example 6: Multiplication Table

import sys

def multiplication_table():
    if len(sys.argv) != 2:
        print("Usage: script.py ")
    else:
        number = int(sys.argv[1])
        for i in range(1, 11):
            print(f"{number} x {i} = {number * i}")

if __name__ == "__main__":
    multiplication_table()

Console Output:

C:\>python script.py 5
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50

Description: This script prints the multiplication table for a number provided as a command-line argument.

โœ–๏ธ

Tip: Python’s f-string formatting makes it easy to create dynamic strings. This feature is particularly useful when generating tables or formatted outputs.

Example 7: Simple Calculator

import sys

def calculator():
    if len(sys.argv) != 4:
        print("Usage: script.py   ")
    else:
        num1 = float(sys.argv[1])
        operator = sys.argv[2]
        num2 = float(sys.argv[3])

        if operator == '+':
            print(f"{num1} + {num2} = {num1 + num2}")
        elif operator == '-':
            print(f"{num1} - {num2} = {num1 - num2}")
        elif operator == '*':
            print(f"{num1} * {num2} = {num1 * num2}")
        elif operator == '/':
            print(f"{num1} / {num2} = {num1 / num2}")
        else:
            print("Invalid operator")

if __name__ == "__main__":
    calculator()

Console Output:

C:\>python script.py 10 * 5
10.0 * 5.0 = 50.0

Description: This script performs a basic arithmetic operation (addition, subtraction, multiplication, or division) based on command-line arguments.

๐Ÿงฎ

Tip: Ensure that users pass the correct operator by validating the input. It’s also good practice to handle division by zero errors in the calculator.

Example 8: Count Words in a File

import sys

def count_words():
    if len(sys.argv) != 2:
        print("Usage: script.py ")
    else:
        filename = sys.argv[1]
        with open(filename, 'r') as file:
            content = file.read()
            words = content.split()
            print(f"Word count: {len(words)}")

if __name__ == "__main__":
    count_words()

Console Output:

C:\>python script.py text.txt
Word count: 42

Description: This script counts the number of words in a file specified by a command-line argument.

๐Ÿ“„

Tip: Always ensure the file exists before attempting to open it. You can enhance the script by adding error handling for missing or inaccessible files.

Example 9: Greet Multiple People

import sys

def greet_people():
    if len(sys.argv) < 2:
        print("Usage: script.py   ... ")
    else:
        for name in sys.argv[1:]:
            print(f"Hello, {name}!")

if __name__ == "__main__":
    greet_people()

Console Output:

C:\>python script.py John Jane Doe
Hello, John!
Hello, Jane!
Hello, Doe!

Description: This script greets multiple people whose names are provided as command-line arguments.

๐Ÿ™‹‍โ™‚๏ธ

Tip: Use slicing with sys.argv[1:] to handle an arbitrary number of command-line arguments. This technique is especially useful for programs that accept a variable-length list of inputs.

Example 10: Calculate Factorial from Command-Line Argument

import sys

def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def main():
    if len(sys.argv) != 2:
        print("Usage: script.py ")
    else:
        number = int(sys.argv[1])
        print(f"Factorial of {number} is {factorial(number)}")

if __name__ == "__main__":
    main()

Console Output:

C:\>python script.py 5
Factorial of 5 is 120

Description: This script calculates the factorial of a number provided as a command-line argument.

๐ŸŽฒ

Trivia: The factorial function is widely used in probability and combinatorics. For example, the number of ways to arrange n distinct objects is given by n! (n factorial).

Key Takeaways

Command-line arguments allow you to interact with Python scripts in a flexible and dynamic way. They enable you to pass input directly to your script without requiring user prompts during execution, making your scripts more versatile and automatable.

๐Ÿ”ง

Tip: Combine command-line arguments with Python's built-in modules to create powerful tools. For instance, you can enhance scripts by adding options for different modes of operation or logging outputs to a file.