Sub topic 10
Running a script from the terminal
This chapter assumes you have a working Python 3 installation that responds to python3 --version (or py --version on Windows). It also assumes you can open a terminal and change directories with cd. You should have a saved file named hello.py that contains print("Hello, world!").
What happens when you run a script
Running a script means asking the Python interpreter to read a text file and execute it from top to bottom. You type a command, your shell finds the interpreter, and the interpreter does the rest.
Three details matter in practice:
- The shell, not Python, resolves the command name. If
python3is not on your PATH, you get "command not found" before Python ever starts. - The interpreter resolves the script path relative to your current working directory, which is the folder your terminal is in at that moment.
- When the script finishes, the process returns an exit code to the shell.
0means success. Any other value means failure.
The basic command
Open a terminal, move to the folder that holds the file, and run it:
cd ~/projects/first-steps
python3 hello.py
# On Windows, use: py hello.pyExpected output:
Hello, world!The argument hello.py is a path. It can be relative to the current directory or absolute. These two commands run the same file:
python3 hello.py
python3 ~/projects/first-steps/hello.pyUse pwd (macOS and Linux) or cd with no arguments (Windows Command Prompt) to print the current directory. Use ls or dir to confirm the file is there.
Paths with spaces
A path that contains spaces must be quoted. Otherwise the shell splits it into several arguments and Python tries to open only the first piece.
python3 "My Projects/hello.py"Standard output, standard error, and redirection
A running program has two output streams. print() writes to standard output (stdout). Tracebacks and warnings go to standard error (stderr). Both appear in your terminal by default, but you can separate them. The following script writes to each stream:
import sys
print("this goes to stdout")
print("this goes to stderr", file=sys.stderr)Save it as streams.py and redirect stdout to a file:
python3 streams.py > out.txtThe terminal still shows the stderr line, and out.txt holds only the stdout line. To send stderr to a file, use 2>:
python3 streams.py 2> errors.txtThis separation is why log files and scripts chained in pipelines stay clean when errors occur.
Exit codes
Every script ends with an exit code. A script that reaches its last line normally returns 0. An uncaught exception makes Python exit with 1. You can choose a code yourself with sys.exit().
import sys
def main():
if len(sys.argv) < 2:
print("usage: exitdemo.py NAME", file=sys.stderr)
return 2
print(f"Hello, {sys.argv[1]}!")
return 0
if __name__ == "__main__":
sys.exit(main())Save this as exitdemo.py. Run it with no argument, then read the code your shell recorded:
python3 exitdemo.py
echo $?The output is:
usage: exitdemo.py NAME
2On Windows Command Prompt, use echo %ERRORLEVEL%. In PowerShell, use $LASTEXITCODE.
Exit codes let other tools react to your script. In a shell, python3 job.py && echo done prints "done" only when the script exits with 0.
Running without a file
Python has several launch modes besides python3 file.py. The first three are useful during setup and debugging.
| Command | What it does |
|---|---|
| `python3 -c "print(2 + 3)"` | Runs the quoted string as a program |
| `python3 -m module` | Finds an importable module and runs it as a script |
| `python3 -i hello.py` | Runs the script, then opens the REPL with its variables still defined |
| `python3 -u hello.py` | Runs with unbuffered output, so text appears immediately |
| `python3 -X utf8 hello.py` | Forces UTF-8 for text I/O, which helps on older Windows setups |
The -m mode deserves attention. Commands such as python3 -m venv .venv and python3 -m pip install requests use it. Running pip as python3 -m pip guarantees that pip belongs to the same interpreter you are calling. A bare pip command might belong to a different installation.
The -i mode is a good way to inspect a script after it runs. If hello.py defines a variable total, you can type total at the prompt that follows.
Making a script directly executable (macOS and Linux)
You can skip typing python3 by adding a shebang line and an executable permission. A shebang is a first line beginning with #! that tells the operating system which program should run the file.
#!/usr/bin/env python3
print("Hello from an executable script")Save it as hello_exec.py, then set the permission and run it:
chmod +x hello_exec.py
./hello_exec.pyThe ./ prefix is required. It tells the shell to run the file in the current directory instead of searching PATH for a command with that name. The shebang uses env so that the first python3 on your PATH is chosen. That choice makes the script follow an active virtual environment.
Windows does not use shebang lines to run files from a terminal. The py launcher does read them to choose a Python version, but the practical command there is still py hello.py.
Which interpreter ran my script?
Most setup problems come from running a different Python than you intended. Add a check at the top of a script, or run it as a one-liner:
import sys
print(sys.executable)
print(sys.version)sys.executable prints the full path of the interpreter in use. If a virtual environment is active, the path points inside the .venv folder. If you expected that and see a system path instead, the environment is not activated in this terminal. Activation applies only to the terminal where you ran the activation command.
Common errors when running a script
| Message | Cause | Fix |
|---|---|---|
| `can't open file '...hello.py': [Errno 2] No such file or directory` | Wrong working directory, wrong file name, or a missing extension | Run `pwd` and `ls`, then `cd` to the right folder or use the full path |
| `python3: command not found` | Python is not on PATH, or your system uses another command name | Try `python` or `py`, and review the PATH chapter |
| `Permission denied` when using `./script.py` | The executable bit is not set | Run `chmod +x script.py` |
| `bad interpreter` or `env: python3\r` | The file has Windows line endings (CRLF) but has a shebang | Save the file with LF line endings in your editor |
| `ModuleNotFoundError` | The package is not installed in the interpreter that ran the script | Check `sys.executable`, then install with that interpreter's `-m pip` |
| `SyntaxError` | The file has invalid Python, often from a pasted prompt such as `>>>` | Remove REPL prompt characters from the file |
The last row is a frequent beginner problem. Text copied from the REPL includes >>> markers. Those belong to the interactive session. A script file contains only the code.
Where the script's folder matters
When you run python3 path/to/script.py, Python puts the script's folder at the front of its import search path. That is why import helper works when helper.py sits next to your script, even if you run the command from elsewhere. File paths you open inside the script, such as open("data.txt"), still resolve against the current working directory, not the script's folder. If a script works from its own folder but fails from another, this difference is the usual cause.
To build a path relative to the script itself, use pathlib:
from pathlib import Path
here = Path(__file__).resolve().parent
print(here / "data.txt")Pycache folders
After you import one of your own modules, Python may create a __pycache__ folder holding compiled bytecode. The script you run directly is not cached this way. These folders are safe to delete and are normally excluded from version control.
Exercise
You run python3 report.py and see [Errno 2] No such file or directory, but you are sure the file exists. Name two commands you would run first, and say what each tells you.
Show answer
Run pwd (or cd on Windows Command Prompt) to see the current working directory, and ls (or dir) to list the files in it. If report.py is not listed, you are in the wrong folder or the file name differs, for example report.py.txt from a hidden extension. Change to the right folder with cd, or pass the full path to the script.
Exercise
A script ends with sys.exit(3). How do you check the code in a macOS or Linux shell, and what does a value other than 0 signal?
Show answer
Run echo $? immediately after the script. A nonzero value signals failure to the shell and to any tool that called the script, so python3 job.py && echo done will not print "done".