How to run a Python program from the command line

PythonBeginner
Practice Now

Introduction

In this lab, you will learn the fundamental skill of running Python programs from the command line. This method is essential for automation, scripting, and deploying applications. We will guide you through creating a Python script, executing it, and passing arguments to it, all within the command-line interface.

Create and Run a Simple Python Script

The most common way to run a Python program is by writing your code in a file with a .py extension and then executing that file using the Python interpreter from your terminal. Let's start by creating a classic "Hello, World!" program.

First, you need to create a new file. In the WebIDE's file explorer on the left, right-click on the empty space in the project directory and select "New File". Name the file hello.py.

Next, open the hello.py file and add the following Python code. This code uses the built-in print() function to display a message to the console.

print("Hello, LabEx!")

Now that you have created the script, you can run it. Open the integrated terminal in your WebIDE (if it's not already open, you can use the menu Terminal > New Terminal). The terminal should open in the /home/labex/project directory, where you saved your file.

To execute the script, type the python command followed by the name of your file:

python hello.py

After pressing Enter, you will see the output of your script printed directly in the terminal.

Hello, LabEx!

You have successfully created and executed your first Python script from the command line.

Using Command-Line Arguments

Running scripts from the command line becomes even more powerful when you can pass information to them at runtime. These pieces of information are called command-line arguments. Python's sys module provides a simple way to access them.

Let's create a new script that greets a user by name, with the name provided as a command-line argument.

Create a new file named greet.py in the /home/labex/project directory.

Add the following code to greet.py. This script imports the sys module. The command-line arguments are stored in the sys.argv list. sys.argv[0] is always the name of the script itself, and the subsequent arguments start from sys.argv[1].

import sys

## Get the name from the first command-line argument
name = sys.argv[1]

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

Now, run this script from the terminal, but this time, add a name after the script's filename. For example, let's use "World".

python greet.py World

The script will take "World" as an argument and use it in the output.

Hello, World!

You can try running it with your own name to see how the output changes.

python greet.py LabEx
Hello, LabEx!

This technique makes your scripts flexible and reusable for different inputs.

Making Scripts More Robust

What happens if you run the greet.py script from the previous step without providing a name? Let's try it.

python greet.py

You will encounter an error.

Traceback (most recent call last):
  File "/home/labex/project/greet.py", line 4, in <module>
    name = sys.argv[1]
IndexError: list index out of range

This IndexError occurs because the script tries to access sys.argv[1], but since no argument was provided, this index does not exist. A robust script should handle such cases gracefully.

Let's modify greet.py to check if an argument was provided. If not, it will use a default name. We can check the number of items in the sys.argv list using the len() function. If len(sys.argv) is greater than 1, it means at least one argument was provided.

Update your greet.py file with the following code:

import sys

if len(sys.argv) > 1:
    ## Use the provided argument if it exists
    name = sys.argv[1]
else:
    ## Use a default name if no argument is provided
    name = "World"

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

Now, your script is more robust. Run it again without an argument:

python greet.py

This time, it runs without error and uses the default name.

Hello, World!

And it still works correctly when you provide an argument:

python greet.py LabEx
Hello, LabEx!

Handling potential errors and providing default behaviors are key practices for writing reliable command-line applications.

Summary

In this lab, you have learned the essential skills for running Python programs from the command line. You started by creating and executing a simple script. Then, you progressed to making your scripts more dynamic and interactive by using command-line arguments via the sys module. Finally, you learned how to make your scripts more robust by handling cases where arguments might be missing. These are foundational skills for any Python developer who wants to build command-line tools or automate tasks.