Running Python Scripts
To run Python scripts, you must interact with the Python interpreter through your system's command-line interface (Terminal on macOS/Linux or Command Prompt/PowerShell on Windows).
1. Executing via the Command Line (The Standard Way)
The most common way to run a script is by passing the path of your script file directly to the Python interpreter.
Open your terminal or command prompt.
Use the
cdcommand to navigate to the directory where your script is saved.Invoke the interpreter followed by the filename.
Bash
# Navigate to the folder containing your script
cd /path/to/your/project
# Run the script using the Python 3 interpreter
python3 main.py
# Note: On Windows configurations, the command is typically just 'python'
python main.py2. Using Interactive Mode (REPL)
If you want to test individual lines of code or run quick experiments without saving a script file, you can use Python’s built-in REPL (Read-Eval-Print Loop) interactive shell.
Type
python3(orpythonon Windows) directly into your terminal with no trailing filenames and press Enter.The terminal will display the Python version followed by a triple-greater-than prompt (
>>>), indicating it is ready for commands.To exit the interactive shell, type
exit()or pressCtrl + D(Ctrl + ZthenEnteron Windows).
Python
>>> message = "System Online"
>>> print(message)
System Online
>>> exit()3. Making Scripts Executable (Linux & macOS)
On Unix-based platforms like Linux and macOS, you can transform a plain text script into a self-executing utility binary that runs without explicitly typing the python3 prefix.
Step A: Add a Shebang Line
Open your .py file and add a shebang as the absolute first line of code. This tells the operating system's shell which interpreter to use to parse the file.
Python
#!/usr/bin/env python3
print("This script executes natively!")
Step B: Modify File Permissions
By default, newly created files do not have execution permissions. You must grant them using the chmod utility in your terminal:
Bash
# Grant execution rights to the file
chmod +x script.py
# Run the script directly using its relative path
./script.py4. Passing Runtime Arguments
You can pass external configuration data into your script when you launch it from the command line. Python captures these trailing values and stores them in a list called sys.argv inside the built-in sys module.
Python
# ─── operational_script.py ───
import sys
# sys.argv[0] is always the name of the script file itself
script_name = sys.argv[0]
# sys.argv[1] captures the first true argument passed
target_environment = sys.argv[1]
print(f"Executing {script_name} targeting the {target_environment} server block.")
To run this script with its parameters, append the argument strings to your execution command:
Bash
python3 operational_script.py production
# Outputs: Executing operational_script.py targeting the production server block.