Running Python Scripts from the Command Line

🏷️ Setting Up Your Python Environment / Understanding the Python Interpreter

🧭 Context Introduction

Once you have Python installed and your interpreter ready, the next essential skill is knowing how to run your Python scripts. As an engineer, you will frequently execute scripts from the command lineβ€”whether you are automating tasks, processing data, or testing a new tool. This guide walks you through the different ways to run Python scripts directly from your terminal, making your workflow faster and more efficient.


βš™οΈ The Basic Command Structure

Running a Python script from the command line is straightforward. The general pattern is:

  • python followed by the name of your script file (e.g., script.py)

For example, if you have a file named hello_world.py, you would type:

  • python hello_world.py

This tells the Python interpreter to read and execute the code inside that file. Make sure you are in the same directory as your script, or provide the full path to the file.


πŸ› οΈ Different Ways to Run Scripts

There are several common approaches depending on your operating system and how you installed Python:

Method Command Example When to Use
Using python python my_script.py Standard on most systems
Using python3 python3 my_script.py When both Python 2 and 3 are installed
Using py (Windows) py my_script.py Windows systems with the Python Launcher
Full path to interpreter /usr/bin/python3 my_script.py When you need a specific Python version

πŸ•΅οΈ Passing Arguments to Your Script

Many scripts accept input values called arguments. You pass them right after the script name:

  • python my_script.py arg1 arg2 arg3

Inside your script, these arguments are accessible and can be used to change behavior without modifying the code. This is especially useful for automation and batch processing.


πŸ“‚ Running Scripts from Any Directory

You are not limited to running scripts only from the folder where they live. You can:

  • Provide a relative path: python scripts/my_script.py
  • Provide an absolute path: python /home/user/projects/my_script.py

This flexibility allows you to keep your scripts organized in folders while executing them from wherever you are working.


πŸ”„ Making Scripts Executable (Linux/macOS)

On Unix-like systems, you can make a script run like any other command. This involves two steps:

  1. Add a shebang line at the very top of your script: #!/usr/bin/env python3
  2. Make the file executable using: chmod +x my_script.py

After this, you can run the script simply by typing:

  • ./my_script.py

No need to type python before it. This is a common pattern for command-line tools and automation scripts.


🐚 Running Scripts in the Background

When you run a script normally, it takes over your terminal until it finishes. To run a script and continue using your terminal, you can:

  • Append an ampersand (&) at the end: python my_script.py &
  • Use nohup to keep it running even after you close the terminal: nohup python my_script.py &

This is useful for long-running tasks like data processing or server scripts.


❗ Common Pitfalls to Avoid

  • File not found error: Double-check that you are in the correct directory or using the right path.
  • Module not found error: Your script may depend on external libraries. Install them first using pip install.
  • Permission denied: On Linux/macOS, ensure the script file has read permissions.
  • Wrong Python version: If your script uses Python 3 syntax, running it with python (which might point to Python 2) will cause errors. Use python3 explicitly.

βœ… Quick Recap

  • The basic command is python script_name.py
  • You can pass arguments after the script name
  • Use full or relative paths to run scripts from anywhere
  • On Linux/macOS, make scripts executable with a shebang line
  • Run scripts in the background with & or nohup

Mastering these command-line techniques will make you more productive and give you greater control over your Python workflows. Practice by creating a simple script and running it using each method described above.


Running Python scripts from the command line lets you execute your code directly from the terminal or command prompt instead of using an interactive shell.

πŸš€ Example 1: Running a simple "Hello, World" script

This example shows the most basic way to run a Python file from the command line.

# hello.py
print("Hello, World!")

πŸ“€ Output: Hello, World!


πŸš€ Example 2: Passing a command-line argument to a script

This example demonstrates how to pass a name as an argument when running the script.

# greet.py
import sys

name = sys.argv[1]
print(f"Hello, {name}!")

πŸ“€ Output: Hello, Alice! (when run as python greet.py Alice)


πŸš€ Example 3: Running a script that reads a file from the command line

This example shows how to pass a filename as an argument and read its contents.

# read_file.py
import sys

filename = sys.argv[1]
with open(filename, "r") as file:
    content = file.read()
print(content)

πŸ“€ Output: Contents of the file (when run as python read_file.py data.txt)


πŸš€ Example 4: Running a script with multiple command-line arguments

This example shows how to accept and use multiple arguments passed from the command line.

# calculator.py
import sys

num1 = float(sys.argv[1])
operator = sys.argv[2]
num2 = float(sys.argv[3])

if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    result = num1 / num2
else:
    result = "Invalid operator"

print(f"Result: {result}")

πŸ“€ Output: Result: 8.0 (when run as python calculator.py 5 + 3)


πŸš€ Example 5: Running a script that handles missing arguments gracefully

This example shows how to provide a helpful message when the user forgets to pass arguments.

# backup.py
import sys

if len(sys.argv) < 2:
    print("Usage: python backup.py <source_folder>")
    print("Example: python backup.py /home/user/documents")
    sys.exit(1)

source = sys.argv[1]
print(f"Backing up files from: {source}")
print("Backup complete.")

πŸ“€ Output: Usage: python backup.py (when run without arguments)


πŸ“Š Comparison Table: Running Python Scripts

Method Command Example When to Use
Basic script python script.py Running any Python file
With one argument python script.py arg1 Passing a single input
With multiple arguments python script.py arg1 arg2 arg3 Passing multiple inputs
With file input python script.py data.txt Processing external files
With error handling python script.py (no args) Preventing crashes from missing inputs

🧭 Context Introduction

Once you have Python installed and your interpreter ready, the next essential skill is knowing how to run your Python scripts. As an engineer, you will frequently execute scripts from the command lineβ€”whether you are automating tasks, processing data, or testing a new tool. This guide walks you through the different ways to run Python scripts directly from your terminal, making your workflow faster and more efficient.


βš™οΈ The Basic Command Structure

Running a Python script from the command line is straightforward. The general pattern is:

  • python followed by the name of your script file (e.g., script.py)

For example, if you have a file named hello_world.py, you would type:

  • python hello_world.py

This tells the Python interpreter to read and execute the code inside that file. Make sure you are in the same directory as your script, or provide the full path to the file.


πŸ› οΈ Different Ways to Run Scripts

There are several common approaches depending on your operating system and how you installed Python:

Method Command Example When to Use
Using python python my_script.py Standard on most systems
Using python3 python3 my_script.py When both Python 2 and 3 are installed
Using py (Windows) py my_script.py Windows systems with the Python Launcher
Full path to interpreter /usr/bin/python3 my_script.py When you need a specific Python version

πŸ•΅οΈ Passing Arguments to Your Script

Many scripts accept input values called arguments. You pass them right after the script name:

  • python my_script.py arg1 arg2 arg3

Inside your script, these arguments are accessible and can be used to change behavior without modifying the code. This is especially useful for automation and batch processing.


πŸ“‚ Running Scripts from Any Directory

You are not limited to running scripts only from the folder where they live. You can:

  • Provide a relative path: python scripts/my_script.py
  • Provide an absolute path: python /home/user/projects/my_script.py

This flexibility allows you to keep your scripts organized in folders while executing them from wherever you are working.


πŸ”„ Making Scripts Executable (Linux/macOS)

On Unix-like systems, you can make a script run like any other command. This involves two steps:

  1. Add a shebang line at the very top of your script: #!/usr/bin/env python3
  2. Make the file executable using: chmod +x my_script.py

After this, you can run the script simply by typing:

  • ./my_script.py

No need to type python before it. This is a common pattern for command-line tools and automation scripts.


🐚 Running Scripts in the Background

When you run a script normally, it takes over your terminal until it finishes. To run a script and continue using your terminal, you can:

  • Append an ampersand (&) at the end: python my_script.py &
  • Use nohup to keep it running even after you close the terminal: nohup python my_script.py &

This is useful for long-running tasks like data processing or server scripts.


❗ Common Pitfalls to Avoid

  • File not found error: Double-check that you are in the correct directory or using the right path.
  • Module not found error: Your script may depend on external libraries. Install them first using pip install.
  • Permission denied: On Linux/macOS, ensure the script file has read permissions.
  • Wrong Python version: If your script uses Python 3 syntax, running it with python (which might point to Python 2) will cause errors. Use python3 explicitly.

βœ… Quick Recap

  • The basic command is python script_name.py
  • You can pass arguments after the script name
  • Use full or relative paths to run scripts from anywhere
  • On Linux/macOS, make scripts executable with a shebang line
  • Run scripts in the background with & or nohup

Mastering these command-line techniques will make you more productive and give you greater control over your Python workflows. Practice by creating a simple script and running it using each method described above.

Interactive Views

You are currently in πŸ“š All-in-One mode. Use the tabs at the top to switch to πŸ“– Theory Only or πŸ’» Code Only views.

Running Python scripts from the command line lets you execute your code directly from the terminal or command prompt instead of using an interactive shell.

πŸš€ Example 1: Running a simple "Hello, World" script

This example shows the most basic way to run a Python file from the command line.

# hello.py
print("Hello, World!")

πŸ“€ Output: Hello, World!


πŸš€ Example 2: Passing a command-line argument to a script

This example demonstrates how to pass a name as an argument when running the script.

# greet.py
import sys

name = sys.argv[1]
print(f"Hello, {name}!")

πŸ“€ Output: Hello, Alice! (when run as python greet.py Alice)


πŸš€ Example 3: Running a script that reads a file from the command line

This example shows how to pass a filename as an argument and read its contents.

# read_file.py
import sys

filename = sys.argv[1]
with open(filename, "r") as file:
    content = file.read()
print(content)

πŸ“€ Output: Contents of the file (when run as python read_file.py data.txt)


πŸš€ Example 4: Running a script with multiple command-line arguments

This example shows how to accept and use multiple arguments passed from the command line.

# calculator.py
import sys

num1 = float(sys.argv[1])
operator = sys.argv[2]
num2 = float(sys.argv[3])

if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    result = num1 / num2
else:
    result = "Invalid operator"

print(f"Result: {result}")

πŸ“€ Output: Result: 8.0 (when run as python calculator.py 5 + 3)


πŸš€ Example 5: Running a script that handles missing arguments gracefully

This example shows how to provide a helpful message when the user forgets to pass arguments.

# backup.py
import sys

if len(sys.argv) < 2:
    print("Usage: python backup.py <source_folder>")
    print("Example: python backup.py /home/user/documents")
    sys.exit(1)

source = sys.argv[1]
print(f"Backing up files from: {source}")
print("Backup complete.")

πŸ“€ Output: Usage: python backup.py (when run without arguments)


πŸ“Š Comparison Table: Running Python Scripts

Method Command Example When to Use
Basic script python script.py Running any Python file
With one argument python script.py arg1 Passing a single input
With multiple arguments python script.py arg1 arg2 arg3 Passing multiple inputs
With file input python script.py data.txt Processing external files
With error handling python script.py (no args) Preventing crashes from missing inputs