🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

[For Beginners] Let's Handle Command-Line Arguments with Python's sys Module!

To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you haven’t installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.

"That black screen (the terminal) looks kind of scary..." "I get that it's a programmer thing, but is it relevant to me?"

Hello! Just a few months ago, I was a complete beginner with zero programming knowledge, thinking the exact same thing as you. With the help of AI, I managed to single-handedly launch two websites (buyonjapan.com, copicode.com).

On this site, I share the points where I actually got stuck and the "aha!" moments of how I solved them, all from a fellow beginner's perspective.

This time, we're covering how to process command-line arguments using Python's `sys.argv`. Once you can use this, you'll be able to change your program's behavior with a single command, just like a magician. It might sound difficult, but don't worry! Just by copying and pasting the code in this article, you'll get to experience that "It works!" feeling. Let's dive in!


First Off, What Are "Command-Line Arguments"? 🤔

Before we get to the main topic, let's take a short detour. Many of you might not be familiar with the term "command-line arguments."

Normally, we operate computers by clicking icons or pressing buttons with a mouse. This is the GUI (Graphical User Interface).

On the other hand, typing commands into a black screen to give instructions is the CUI (Character User Interface), also known as the "command line."

And command-line arguments are extra pieces of information you pass to a program when you run it from the CUI, basically saying, "Hey program, please use these settings for this run!" Think of them as a "set of instructions" or "options" for your program.

Using them is incredibly convenient because you can change a program's behavior for each execution without having to rewrite the code every time!


The First Step to Receiving Arguments in Python: `sys.argv`

The most basic way to receive command-line arguments in Python is by using `argv`, which is part of the `sys` module.

The `sys` module comes standard with Python (see the official documentation), so you don't need to install anything extra. You can use it right away!

First, let's see what form command-line arguments take when they're passed to the program. Save the following code as `show_args.py`.

<!-- show_args.py -->
import sys

print("--- Arguments passed to the program ---")
print(sys.argv)
print(f"The data type is {type(sys.argv)}.")

Once saved, open your terminal (or Command Prompt/PowerShell on Windows), navigate to the directory where you saved the file, and run it like this:

# Command to run in the terminal
python show_args.py first-arg second 333

You should see output like this:

--- Arguments passed to the program ---
['show_args.py', 'first-arg', 'second', '333']
The data type is <class 'list'>.

Looking at the result, you can see what `sys.argv` really is. That's right, it's a list!

Since it's a list, you can access individual arguments using their index numbers, like `sys.argv[1]`, `sys.argv[2]`, and so on.


Common Stumbling Blocks and How to Fix Them 🚨

While `sys.argv` is simple and useful, there are two common pitfalls for beginners. I fell right into them myself! But don't worry, they're not scary once you know how to handle them.

Point 1: Missing Arguments Cause an Error (`IndexError`)

For example, let's say you write a program that takes one argument—a name—and prints a greeting.

<!-- greet.py -->
import sys

# Get the first argument as a name
name = sys.argv[1]

print(f"Hello, {name}!")

If you run this program correctly by passing a name...

# Correct execution example
python greet.py Smith
# Output
# Hello, Smith!

It works perfectly! But what happens if you accidentally forget to pass an argument?

# Example of forgetting an argument
python greet.py
# Output
# Traceback (most recent call last):
#   File "greet.py", line 4, in <module>
#     name = sys.argv[1]
# IndexError: list index out of range

You get an `IndexError: list index out of range`. This error means "You tried to access an index that's outside the list's range!" Since you didn't pass any arguments, `sys.argv` only contains `['greet.py']`. That means index `1` doesn't exist, so the program complains when you try to access `sys.argv[1]`.

【Solution】At the beginning of your program, check if you have the expected number of arguments. You can get the number of elements in a list with `len()`.

<!-- greet_safe.py (Safe version) -->
import sys

# The number of elements in sys.argv is "script name + number of arguments"
# We want 1 argument, so len(sys.argv) should be 2
if len(sys.argv) != 2:
    print("Error: Please provide exactly one name.")
    print("Usage: python greet_safe.py [Your Name]")
    sys.exit() # Exit the program here

# If we reach this line, the argument was passed correctly
name = sys.argv[1]

print(f"Hello, {name}!")

Point 2: All Arguments Are Treated as Strings

Another crucial point is that all arguments in `sys.argv`, even if they look like numbers, are treated as strings.

For instance, let's consider a program that takes two numbers as arguments and adds them together.

<!-- add_wrong.py (Incorrect example) -->
import sys

num1 = sys.argv[1] # The string '100'
num2 = sys.argv[2] # The string '50'

result = num1 + num2 # This will concatenate the strings

print(f"{num1} + {num2} = {result}")

Running this will give you an unexpected result.

# Execution example
python add_wrong.py 100 50

# Output
# 100 + 50 = 10050

Instead of `150`, you get `10050`. This is because the strings `'100'` and `'50'` were simply joined together.

【Solution】If you want to treat arguments as numbers for calculations, you need to convert their type from string to a number (integer or float) using `int()` or `float()`. It's also good practice to use a `try-except` block to handle cases where non-numeric characters are entered.

<!-- add_correct.py (Correct example) -->
import sys

# Check the number of arguments
if len(sys.argv) != 3:
    print("Error: Please provide exactly two numbers.")
    print("Usage: python add_correct.py [number1] [number2]")
    sys.exit()

try:
    # Convert strings to integers using int()
    num1 = int(sys.argv[1])
    num2 = int(sys.argv[2])
    
    result = num1 + num2
    print(f"{num1} + {num2} = {result}")

except ValueError:
    # A ValueError occurs if int() fails to convert
    print("Error: Arguments must be integers.")

[Advanced] Copy, Paste, and Go! Auto-Generate HTML Files with Arguments ✨

Alright, it's time for the main event! Let's use what we've learned to create a practical program that's perfect for you, a web creator.

This is a program that "takes a 'name' and 'favorite color' as command-line arguments and automatically generates an HTML file with a special greeting message just for that person."

Save the following code as `create_html.py`. You can just copy and paste the entire block!

<!-- create_html.py -->
import sys
import os

# --- 1. Check arguments ---
# We need 2 arguments: "name" and "favorite color"
if len(sys.argv) != 3:
    print("[Error] Incorrect number of arguments.")
    print("[Usage] python create_html.py [Name] [color_code_or_name]")
    print("[Example] python create_html.py Smith hotpink")
    sys.exit()

# --- 2. Put arguments into descriptive variables ---
user_name = sys.argv[1]
fav_color = sys.argv[2]

# --- 3. Generate the content to write to the HTML file ---
# f-strings are handy for embedding variables in a string!
# A complete HTML/CSS/JS code
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>A Special Message for {user_name}</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #121212;
            color: #ffffff;
        }}
        .card {{
            padding: 40px 60px;
            border-radius: 15px;
            text-align: center;
            border: 2px solid {fav_color};
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
            background-color: #1e1e1e;
        }}
        h1 {{
            margin: 0;
            font-size: 2.5em;
            /* Color applied via JavaScript */
        }}
        p {{
            margin-top: 10px;
            font-size: 1.2em;
            color: #cccccc;
        }}
    </style>
</head>
<body>
    <div class="card">
        <h1 id="greeting">Hello, {user_name}!</h1>
        <p>Your favorite color is <strong style="color: {fav_color};">{fav_color}</strong>, right!</p>
    </div>

    <script>
        // Adding a little flair by making the text color a gradient
        const greeting = document.getElementById('greeting');
        greeting.style.background = `linear-gradient(45deg, {fav_color}, #ffffff)`;
        greeting.style.webkitBackgroundClip = 'text';
        greeting.style.color = 'transparent';
    </script>
</body>
</html>
"""

# --- 4. Write the file ---
# The filename will be something like "greet_Name.html"
file_name = f"greet_{user_name}.html"

try:
    with open(file_name, "w", encoding="utf-8") as f:
        f.write(html_content)
    
    # Display a success message
    # os.path.abspath() gets the full path of the file
    full_path = os.path.abspath(file_name)
    print("🎉 HTML file generated successfully!")
    print(f"Filename: {file_name}")
    print(f"Saved to: {full_path}")
    print("Open it in your browser to check it out!")

except IOError as e:
    print(f"[Error] Failed to write file: {e}")
    sys.exit()

Ready? In your terminal, run the script with your name and favorite color (any CSS color name or code will work) as arguments!

# Example (try it with your own name!)
python create_html.py Tanaka "rgb(102, 157, 246)"

After running it, a success message will appear in the terminal.

🎉 HTML file generated successfully!
Filename: greet_Tanaka.html
Saved to: /Users/yourname/path/to/greet_Tanaka.html
Open it in your browser to check it out!

And now, a new file like `greet_Tanaka.html` should have been created in the same folder. Double-click this HTML file to open it in your browser!

Example of the generated HTML file displayed in a browser. There is a card in the center with a gradient heading that reads, "Hello, Tanaka!" and text about the specified color.

How about that? With a single command, a webpage just for you was created! This is the power of command-line arguments. If you have a file template, you can instantly mass-produce similar files by changing the name, color, message, and more. Isn't that amazing?


Summary: The Black Screen Can Be Your Ally

In this article, we covered how to handle command-line arguments using Python's `sys.argv`, complete with some of my own stumbling stories.

The command line might seem intimidating at first, but once you get to know it, it will become your best friend, dramatically improving your workflow. I hope this article serves as a stepping stone for you to take your first leap into the world of the black screen.

On to the Next Step

If you're interested in automating programs, try controlling the timing of processes next. With Python's `time` module, you can make a program wait for a certain period (sleep) or accurately measure how long a process takes.

➡️ How to Delay and Measure Time with the time Module