0.4 Running Python from the command line¶
Suggested time: 1 lesson (with Chapter 0.3) · You need: Chapter 0.3
What you will do¶
Run Python programs from the terminal, stop them, and read their error messages properly. By the end of this chapter you will be able to:
- check which Python the terminal is using;
- run a Python file, and stop it with Ctrl+C;
- explain why the folder you run a program from matters;
- tell the Python prompt
>>>apart from the shell prompt; - read a traceback from the bottom up;
- (A Level) pass arguments to a program with
sys.argv, and return an exit code.
Key vocabulary¶
| Term | Meaning | Example |
|---|---|---|
| Python launcher | On Windows, the py command, which finds and starts the right Python |
py hello.py |
| REPL | Read–Evaluate–Print Loop: Python's interactive prompt, >>> |
typing 2 + 3 at >>> |
| Traceback | The report Python prints when a program crashes, showing where it happened | ZeroDivisionError: division by zero |
| Exception | An error that happens while a program is running | FileNotFoundError |
| Module | A Python file or library that can be imported, or run with -m |
pip, platform |
| Exit code | A number a program hands back to the shell when it finishes; 0 means success |
sys.exit(1) |
Step 1: Which Python is this?¶
The first command shows the version; the second shows where it's installed.
Why py on Windows and python3 on Mac?
On Windows, py is the Python launcher: it finds the Python you installed, even if more than one is present.
On macOS and Linux, python3 is the standard name. (On many Macs, python on its own either doesn't exist
or points to something else.) This book uses py for Windows and python3 for macOS and Linux throughout.
Step 2: Run a Python file¶
The pattern is always the same: cd into the folder that holds the file, then run it.
| While a program is running… | What to do |
|---|---|
| It is stuck, or a game window won't close | Click in the terminal and press Ctrl+C (on a Mac too: Ctrl, not Cmd) |
| You changed the code | Save the file, click back in the terminal, press ↑ then Enter |
| The screen is messy | Type cls (Windows) or clear (Mac/Linux) |
Text games suit the terminal
Programs that use input(), such as the Castle Adventure, work especially well in a terminal.
Step 3: Why the folder you run from matters¶
A program that opens files (a saved game, a level map, a picture) has to find them. If the code uses a
relative path such as "castle.txt", Python looks for it starting from the terminal's current working
directory, not from the folder the .py file is saved in.
Save this program as where_am_i.py (it is also in the OOP Adventure Game folder of the course materials) and run it twice:
"""
where_am_i.py - shows the difference between the folder your
terminal is in and the folder this file is saved in.
"""
import os
# The current working directory: where the terminal is "standing"
print("Terminal is in: ", os.getcwd())
# The folder this .py file is saved in
file_folder = os.path.dirname(os.path.abspath(__file__))
print("This file is in:", file_folder)
if os.getcwd() == file_folder:
print("Same folder - relative paths like 'assets/...' will work.")
else:
print("Different folders - relative paths may NOT work.")
print("Tip: cd into the file's folder before running it.")
First from inside its own folder, then from the folder above:
alex@MacBook-Air Programming % python3 where_am_i.py
Terminal is in: /Users/alex/Documents/Programming
This file is in: /Users/alex/Documents/Programming
Same folder - relative paths like 'assets/...' will work.
alex@MacBook-Air Programming % cd ..
alex@MacBook-Air Documents % python3 Programming/where_am_i.py
Terminal is in: /Users/alex/Documents
This file is in: /Users/alex/Documents/Programming
Different folders - relative paths may NOT work.
Tip: cd into the file's folder before running it.
What's happening in where_am_i.py?
os.getcwd() returns the current working directory, the folder the terminal was in when the program started.
__file__ holds the path of the running .py file; os.path.abspath() makes it a full path and
os.path.dirname() removes the file name, leaving the folder. The game series use this trick so they can always
find their assets folder. Programs you write yourself may not, so make "cd first, then run" a habit.
Step 4: Two different prompts¶
If you type py or python3 on its own, Python starts in interactive mode (the REPL) and the prompt changes to
>>>. That is Python waiting for Python code, not the shell waiting for commands.
>>> 7 * 6
42
>>> python3 hello.py
File "<stdin>", line 1
python3 hello.py
^^^^^
SyntaxError: invalid syntax
>>> exit()
At >>> you type Python (such as 7 * 6). At the shell prompt (>, % or $) you type commands (such as
cd or python3 hello.py). Type exit() to leave >>>. Thonny's Shell pane and IDLE's main window are also >>> prompts.
Two useful switches: -c and -m
-c runs a short piece of code: python3 -c "print(7 * 6)" prints 42.
-m runs a module as a program. You will use it for pip (Chapter 0.6) and venv.
python3 -m pip means "the pip that belongs to this Python".
Step 5: Read a traceback, bottom up¶
When a program crashes, Python prints a traceback. Here is a small program with a hidden problem:
def average(scores):
return sum(scores) / len(scores)
def report(name, scores):
print(name, "averaged", average(scores))
report("Sam", [12, 15, 9])
report("Alex", [])
Sam averaged 12.0
Traceback (most recent call last):
File "scores.py", line 8, in <module>
report("Alex", [])
File "scores.py", line 5, in report
print(name, "averaged", average(scores))
^^^^^^^^^^^^^^^
File "scores.py", line 2, in average
return sum(scores) / len(scores)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
Read it from the bottom up:
- The last line says what went wrong: a
ZeroDivisionError. - The line above says where: line 2, in
average, dividing bylen(scores). - Further up shows how the program got there: line 8 called
report, which calledaverage.
Alex has no scores, so len(scores) is 0. The fix belongs in the program's design: decide what an empty list
should mean, and check for it before dividing.
Your output may look slightly different
Python also prints the full path to the file, and newer versions add the ^^^ and ~~~ markers that point
at the exact part of the line. The wording of some messages changes between versions, but the shape is always the same.
Checkpoint
You can cd to a folder, run a program from the terminal, stop it with Ctrl+C,
and say which line caused a crash by reading the traceback.
Step 6 (A Level): arguments and exit codes¶
Programs run from the command line can be given arguments, and can hand back an exit code when they finish.
import sys
if len(sys.argv) < 2:
print("Usage: python3 greet.py NAME")
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}! You gave me {len(sys.argv) - 1} argument(s).")
print("sys.argv is", sys.argv)
$ python3 greet.py "Sam Jones" 17
Hello, Sam Jones! You gave me 2 argument(s).
sys.argv is ['greet.py', 'Sam Jones', '17']
$ python3 greet.py
Usage: python3 greet.py NAME
What's happening?
sys.argv is a list of strings. Item 0 is the program's own name; the arguments follow. Quotation marks
keep Sam Jones together as one argument, and 17 arrives as the string '17', so you would need int()
to use it as a number. sys.exit(1) stops the program with exit code 1, which by convention means "something went wrong";
finishing normally gives 0. To see the last exit code, type echo %ERRORLEVEL% (Command Prompt) or echo $? (macOS/Linux).
Concept: programs that talk to other programs
How it works: the shell passes arguments into the program, and the program passes an exit code back out.
Why we use it: it lets one program control another, so a test runner can check whether your tests passed
from the exit code alone.
Where else it's used: Git, pip and every automated build rely on exit codes to decide whether to carry on.
Troubleshooting¶
| What you see | What to try |
|---|---|
can't open file … [Errno 2] No such file or directory |
You're in the wrong folder. cd to the folder that contains the file and check with dir *.py or ls *.py. |
FileNotFoundError when opening a data file or picture |
The terminal's folder isn't the program's folder (Step 3). cd there first. |
SyntaxError straight after typing a command |
You're at the >>> prompt. Type exit() first. |
| Nothing happens and there's no new prompt | The program is waiting, perhaps for input(). Type an answer, or press Ctrl+C. |
ModuleNotFoundError: No module named … |
A library isn't installed for this Python. See Chapter 0.6. |
Check your understanding¶
- A student types
python3 hello.pyand sees>>>followed bySyntaxError. What has happened? - A game works when started from its own folder but crashes with
FileNotFoundErrorwhen started from the Desktop. Why? - In a traceback, which line tells you what kind of error happened, and which tells you where?
- (A Level) A program is run with
python3 score.py Alex 42. What issys.argv[2], and what type is it?
Answers
- They are at Python's interactive prompt, so the command was treated as Python code, which isn't valid Python. Type
exit()and run the command at the shell prompt. - The game opens its files with relative paths, which are worked out from the current working directory. From the Desktop, the path points to a file that doesn't exist.
- The last line gives the type of error; the lines just above it give the file and line number where it happened.
'42': a string. Useint(sys.argv[2])to get the number.
Summary¶
- Run a program with
py file.py(Windows) orpython3 file.py(Mac/Linux), aftercd-ing into its folder. - Ctrl+C stops a program; ↑ repeats a command.
>>>is Python's own prompt; typeexit()to leave it.- Read tracebacks from the bottom up: what went wrong, then where, then how the program got there.
- (A Level)
sys.argvholds the arguments as strings;sys.exit(n)returns an exit code, where0means success.