In this lesson, you will learn how to trigger your Python programs directly from your terminal, allowing you to bypass your IDE and run code in any environment.
The Power of the Terminal
While your IDE is great for writing code, the command line is where you actually deploy or run that code. To execute a script, you use the python (or python3) command followed by the name of your file.
If you have a file named hello.py containing print("Hello, world!"), navigate to that folder in your terminal and type:
python hello.py
The terminal acts as a direct interface to the Python interpreter. When you hit Enter, the interpreter reads your file from top to bottom and executes every line.
Passing Arguments
Sometimes you want your script to behave differently based on input. You can pass "arguments" after the filename, separated by spaces:
python script.py data.txt 100
Inside your Python script, you can access these values using the built-in sys module. Specifically, sys.argv is a list where the first item is the script name, and subsequent items are your arguments:
import sys
# If you ran 'python script.py hello', sys.argv[1] would be 'hello'
print(f"The first argument is: {sys.argv[1]}")
The Interactive Shell
If you just want to test a quick snippet of code without creating a whole file, you can type python (or python3) into your terminal without a filename. This opens the Interactive Shell (or REPL). You will see >>> prompts. Anything you type here—like 2 + 2—is executed immediately. It is a fantastic sandbox for testing ideas before adding them to your project files. Type exit() or press Ctrl+Z (or Ctrl+D) to return to your normal terminal.
Mastering these commands allows you to run automation scripts on servers, process files quickly, and debug your logic without the overhead of a graphical interface.
Key Takeaway: The command line is the primary way to execute your Python files and test logic in real-time, providing a fast, lightweight bridge between your code and the operating system.