Skip to Content
Course content

103: Standard Input and Command-Line Arguments

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing code for a junior developer who had written a great script to analyze server logs. The logic was flawless, but there was one problem: every time he wanted to analyze a different log file, he opened the .py file, manually changed a hardcoded string like filename = "server_log_monday.txt" to "server_log_tuesday.txt", and saved it. When I asked him why he didn't just pass the filename as an argument, he looked at me like I was speaking a foreign language. He had spent hours over a month just editing a single line of text. It was a classic case of writing a program that works, but isn't actually a tool.

Conversing with the User via input()

Sometimes, you want your program to pause and wait for the user to tell it something while it's already running. That's where input() comes in. It's a straightforward function that prints a prompt to the screen and halts execution until the user hits Enter. I often use this for simple configuration prompts or confirmation checks (like "Are you sure you want to delete this file? y/n").

# A quick example of a dynamic greeting and age check
name = input("Who am I speaking with? ")
age_str = input("And how old are you? ")

# Remember: input() always returns a string. 
# If you need a number, you have to cast it.
age = int(age_str)

if age < 18:
    print(f"Sorry, {name}, you're too young for this script!")
else:
    print(f"Welcome aboard, {name}.")

One thing that trips people up is forgetting that input() is strictly for strings. If you try to perform math on the result without wrapping it in int() or float(), Python will throw a TypeError. It's a small detail, but it's one of those things you'll likely forget at least once in your first week.

Powering Up with sys.argv

While input() is great for interactive scripts, it's a nightmare for automation. If you're scheduling a script to run via a cron job or a CI/CD pipeline, there's no human there to type into a prompt. This is where command-line arguments come in. You provide the data at the moment you launch the script.

To do this, we use the sys module. Specifically, sys.argv, which is essentially a list of all the strings passed to the script from the terminal. The first element, sys.argv[0], is always the name of the script itself. The actual data you care about starts at index 1.

import sys

# Let's say we run this as: python analyzer.py data.csv 100
if len(sys.argv) < 3:
    print("Usage: python analyzer.py [filename] [threshold]")
    sys.exit(1) # Exit with an error code

filename = sys.argv[1]
threshold = int(sys.argv[2])

print(f"Processing {filename} with a threshold of {threshold}...")
# Logic to open the file and filter data would go here

I prefer sys.argv for simple tools, but be warned: as your tools grow, managing a list of indices becomes confusing. If you find yourself checking sys.argv[7], it's time to look into the argparse library. For now, though, mastering sys.argv is the fastest way to turn your scripts into actual command-line utilities.




📋 Practical Task

Build a Command-Line Word Counter

Your task is to create a script called word_count.py that allows a user to specify a text file and a "target word" via command-line arguments. The script should then count how many times that specific word appears in the file.

Requirements:

  • The script must take two arguments: the path to a .txt file and the word to search for.
  • If the user fails to provide both arguments, the script should print a usage message (e.g., Usage: python word_count.py <file> <word>) and exit.
  • The script should read the file, count the occurrences of the word (case-insensitive), and print the final count.
  • Handle the case where the file might not exist by using a try-except block to catch FileNotFoundError.

Testing your tool:
Create a file named sample.txt with some text in it, then run your script from the terminal:
python word_count.py sample.txt python

Rating
0 0

There are no comments for now.

to be the first to leave a comment.