Back to Python
2026-02-156 min read

Examples Running in the Command Line Interface

Learn Examples Running in the Command Line Interface step by step with clear examples and exercises.

Why This Matters

Understanding how to run examples in the Command Line Interface (CLI) is crucial for any programmer, as it allows you to quickly test and debug your code without relying on an Integrated Development Environment (IDE). This skill is particularly important when working with complex scripts or automation tasks, where a CLI can provide more flexibility and control over the execution of your programs.

Prerequisites

Before diving into examples running in the command line interface, you should have a basic understanding of:

  1. Basic Python Syntax: Familiarity with variables, data types, operators, functions, loops, and conditional statements is necessary to write and run your own Python scripts.
  2. Installing Python: You need to install Python on your system before you can start writing and running scripts from the command line. For most operating systems, this can be easily achieved using package managers like apt for Ubuntu or Homebrew for macOS.
  3. Navigating File System: Knowing how to navigate your file system using commands like cd, ls, and pwd is crucial when working with scripts in the command line interface.
  4. Running Python Scripts: Understanding how to run Python scripts from the command line, including specifying the correct interpreter and passing arguments if necessary.

Core Concept

To run a Python script from the command line, you first need to navigate to the directory containing your script using the cd command. Once you're in the correct directory, you can use the following syntax to execute your script:

python filename.py

Replace filename.py with the name of your Python file (including the .py extension). This command tells the system to run the specified Python script using the default Python interpreter installed on your machine.

Example: Running a Simple Script

Let's create a simple Python script called hello_world.py with the following content:

print("Hello, World!")

To run this script from the command line, navigate to the directory containing hello_world.py using the cd command and execute it with the following command:

python hello_world.py

Upon execution, you should see the output:

Hello, World!

Example: Passing Arguments to a Script

You can also pass arguments to your Python scripts from the command line. To do this, modify your script to accept and process arguments using the sys module's argv list. Here's an example of a simple script that accepts one argument:

import sys

if len(sys.argv) > 1:
print("Hello, " + sys.argv[1] + "!")
else:
print("Please provide a name.")

Save this code as greet.py. To run the script and pass an argument, use the following command:

python greet.py John

The output should be:

Hello, John!

Example: Handling Multiple Arguments

To handle multiple arguments in your script, modify the greet.py example to accept any number of arguments and greet each one:

import sys

for arg in sys.argv[1:]:
print("Hello, " + arg + "!")

Save this code as greet_multiple.py. To run the script with multiple arguments, use the following command:

python greet_multiple.py John Alice Bob

The output should be:

Hello, John!
Hello, Alice!
Hello, Bob!

Worked Example

Let's create a Python script that calculates the factorial of a number provided as an argument. Save the following code as factorial.py:

import sys

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

if len(sys.argv) > 1:
try:
number = int(sys.argv[1])
result = factorial(number)
print("The factorial of", number, "is:", result)
except ValueError:
print("Please provide a valid integer.")
else:
print("Please provide a number to calculate its factorial.")

To run this script and calculate the factorial of 5, use the following command:

python factorial.py 5

The output should be:

The factorial of 5 is: 120

Common Mistakes

  1. Not specifying the Python interpreter: Make sure you're using the correct Python interpreter when running your scripts by either specifying the full path to the interpreter or ensuring that it's included in your system's PATH.
  2. Incorrect script name: Ensure that you provide the correct file name (including the .py extension) when running your scripts from the command line.
  3. Not handling exceptions: When working with user input, always make sure to handle potential exceptions such as ValueError or TypeError to ensure your script can gracefully handle invalid inputs.
  4. Forgetting to import necessary modules: Always double-check that you've imported any required modules in your scripts before attempting to use them.
  5. Not understanding the difference between interactive mode and script execution: The Python interpreter behaves differently when run interactively versus running a script. Be aware of this difference, as it can lead to unexpected results if not accounted for.
  6. Ignoring environment variables: When working with scripts that require specific environment variables, make sure to set them correctly before running the script or include logic in your script to handle missing environment variables.
  7. Not checking for required arguments: If your script requires certain arguments to be provided, make sure to check for their presence and provide appropriate error messages if they're missing.

Practice Questions

  1. Write a Python script that takes two command-line arguments representing the base and exponent, calculates the result using the formula base^exponent, and prints the output.
  2. Modify the greet.py script to accept multiple names as arguments and print a greeting for each one.
  3. Write a Python script that accepts a command-line argument representing a file name, reads the contents of the file, and prints its length (number of characters).
  4. Create a Python script that calculates the sum of all numbers provided as command-line arguments. The script should handle cases where no arguments are provided or when an invalid input is encountered.
  5. Write a Python script that accepts a command-line argument representing a directory path, lists all files within that directory (including subdirectories), and prints their names.
  6. Modify the factorial.py script to handle negative numbers by returning an error message or calculating the factorial of the absolute value and multiplying it by (-1) as appropriate.

FAQ

  1. Why can't I run my Python script from anywhere on my system?

To run your scripts from any directory, you need to add the directory containing the Python interpreter to your system's PATH environment variable.

  1. How do I handle negative numbers when calculating factorials?

You can modify the factorial() function to check for negative numbers and return an error message or handle them appropriately based on your requirements.

  1. Why does my script only work in interactive mode but not when run from the command line?

Make sure that you're using the correct Python interpreter, importing necessary modules, and handling exceptions as needed. Additionally, ensure that any global or module-level variables are properly defined before attempting to use them.

  1. How can I pass a list of numbers as command-line arguments to my script?

You can split the command-line arguments into a list using the sys.argv list and then convert each element to an integer if necessary. For example:

import sys
numbers = [int(arg) for arg in sys.argv[1:]]

Now numbers is a list of integers representing command-line arguments.

5. **How can I pass environment variables to my Python script from the command line?**
You can pass environment variables as command-line arguments prefixed with `--`. For example, to pass an environment variable named `MY_VAR` with value `my_value`, use the following command:

python script.py --MY_VAR=my_value


In your script, you can access this environment variable using the `os` module's `environ` dictionary:

import os

my_var = os.environ["MY_VAR"]

Examples Running in the Command Line Interface | Python | XQA Learn