Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 01 · 30 minutes

Run a Python script and know which Python runs it

After this lesson you can
  • Check the Python version and use the interactive prompt
  • Write a script, pass it words from the command line and read its errors
  • Prove which Python and which virtual environment run your code
Lab files of this lesson (3)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Your team lead sends you a ten-line script with the note "works on my machine". On yours it crashes, and you do not know which Python you ran, or whether the packages you installed last week are even in reach. You first learn how a script starts and where its Python comes from. Then you write a small helper that prints a banner for the host named on the command line, and you read what Python says when the name is missing.

The idea

Python is a programming language. The program python3 (the interpreter) reads your text file (a script), turns it into instructions and runs them, one statement at a time. You do not compile anything first.

How a script runs
YouShellpython3python3 hello.pystart it with the file nameread the file, run each lineoutput and an exit codeoutput on screen, code in $?YouShellpython312345
  1. You → Shell: python3 hello.py
  2. Shell → python3: start it with the file name
  3. python3: read the file, run each line
  4. python3 → Shell: output and an exit code
  5. Shell → You: output on screen, code in $?

You can use Python in two ways:

WayCommandUse it for
The REPL (read, evaluate, print, loop)python3Try one idea and see the result at once.
A scriptpython3 file.pyAnything that you will run again.

The virtual environment (venv) from lesson 0 is a private folder that links to one interpreter and holds its own installed packages. Each project gets its own. A package that you install in one venv does not change another project and does not change the system.

Worked example

Work in ~/krlab/python with the venv from lesson 0.

1. Check the version and try the prompt

python3 --version prints the version. The lessons need 3.12 or later. Activate the venv of lesson 0 first, as lesson 0 showed. Skip that line if your prompt already shows (.venv): you activate again in every new terminal.

cd ~/krlab/python
source .venv/bin/activate
python3 --version
Python 3.14.4

Start the REPL by typing python3 alone. The prompt >>> waits for one statement, and the REPL prints the value of each expression.

>>> 2 + 3
5
>>> name = "root"
>>> name.upper()
'ROOT'
>>> len(name)
4
>>> exit()

name = "root" stores a value under a name (a variable). "root" is text, called a string (str). name.upper() calls a method: a function that belongs to a value, here the text. len(name) is a built-in function that counts the characters. exit() leaves the REPL; Ctrl+D does the same.

2. Write your first script

A file is better than the prompt when you want to repeat the work. Create hello.py with your editor and put this in it.

import sys loads a module, a file of ready code from the standard library. sys holds facts about the running Python. print(...) shows values on the screen. An f-string is text that starts with f. It puts the value of a name that you write in braces into the text. sys.version_info is the version of the running Python. .major and .minor are parts of that value: the dot picks one part. sys.argv is the list of words on the command line.

hello.py

import sys

name = "analyst"
print(f"Hello, {name}")
print("Python", sys.version_info.major, sys.version_info.minor)
print("Script:", sys.argv[0])
python3 hello.py
Hello, analyst
Python 3 14
Script: hello.py

The two numbers on the second line are your own version.

3. Pass words to a script

Everything that you type after the script name becomes an item of sys.argv. The first item is the script name. A word with spaces needs quotes, or the shell cuts it into two words. In a list, counting starts at zero: sys.argv[1] is the second item. len of a list is the number of items.

Create args.py.

How the shell cuts a command into sys.argv
python3the interpreter: not in argvargs.pysys.argv[0]: the script namescansys.argv[1]: the first word"web 01"sys.argv[2]: quotes join wordspython3the interpreter: not in argvargs.pysys.argv[0]: the script namescansys.argv[1]: the first word"web 01"sys.argv[2]: quotes join words

args.py

import sys

print(sys.argv)
print(len(sys.argv), "words")
print("second word:", sys.argv[1])
python3 args.py scan "web 01"
['args.py', 'scan', 'web 01']
3 words
second word: scan

4. Read an error

Make a script that fails on purpose. echo prints text, and > puts that text into a file. $? is the exit code of the last command: a program that works returns 0, a program that fails returns a different number.

echo 'print(1/0)' > bad.py
python3 bad.py
echo "exit code: $?"
Traceback (most recent call last):
  File "/home/you/krlab/python/bad.py", line 1, in <module>
    print(1/0)
          ~^~
ZeroDivisionError: division by zero
exit code: 1
A traceback, from the bottom up
ZeroDivisionErrorthe error name: read firstdivision by zerothe reasonFile ".../bad.py",the file that failedline 1,the line numberprint(1/0)the code of that lineZeroDivisionErrorthe error name: read firstdivision by zerothe reasonFile ".../bad.py",the file that failedline 1,the line numberprint(1/0)the code of that line

Read a traceback from the bottom. The last line names the error and its reason. The lines above show where it happened. Lesson 5 uses the exit code.

5. Prove which Python runs

deactivate leaves the venv. which prints the full path of the program that a name starts. source .venv/bin/activate enters the venv again and puts .venv/bin first in your PATH.

deactivate
which python3
source .venv/bin/activate
which python
/usr/bin/python3
/home/you/krlab/python/.venv/bin/python

python -c "..." runs the text that follows as a program. sys.prefix is the folder of the Python that runs now, and sys.base_prefix is the system Python that it came from. When the two differ, you are inside a venv.

python -c "import sys; print(sys.prefix); print(sys.base_prefix)"
pip list
/home/you/krlab/python/.venv
/usr
Package Version
------- -------
pip     25.1.1

pip list shows the installed packages. The list is nearly empty: your project starts clean. You do not need to activate: .venv/bin/python hello.py also uses the venv. That form is the safest one in a script or a scheduled job.

Your turn

Do the task of your team lead. There is no code here: use what the worked example showed.

Write banner.py in ~/krlab/python. It takes the name of a host from the command line and prints one line: Scanning, the host name and, in brackets, how many characters the name has. For example, the host x1 gives Scanning x1 (2 characters). Do not add any check for a missing name: you want to read the error that Python gives.

Run it with a name in quotes, then with three separate words, then with no word at all. Then answer from your own terminal.

Check yourself

You run "python3 tool.py" and see "ModuleNotFoundError: No module named 'requests'". You installed it yesterday. What is the likely cause?

You installed it into a different Python: another venv, or the system one. The module exists only where you ran pip install. Activate the right venv, or run that venv's python directly, and check with which python.

Why does the REPL print 5 for "2 + 3" but a script prints nothing for the same line?

The REPL prints the value of every expression because it is made for trial and error. A script runs your statements and shows only what you pass to print().

You read a long traceback. Where do you look first?

At the last line. It holds the error type and the reason. Then read upward to the last line that points into your own file: that is where your code made the call that failed.

Should you commit the .venv folder to Git?

No. It is large, it belongs to one machine, and anybody can rebuild it. Commit the list of requirements instead (lesson 7) and add .venv/ to .gitignore.

Field notes

  • Write python3, not python, outside a venv. On many systems python does not exist, or it still means Python 2 on an old one.
  • Do not run sudo pip install. It changes files that the system's package manager owns, and it can break system tools. Use a venv, or pipx for a command-line tool that you want on your PATH. pip install needs no root: in a container, install as an ordinary user.
  • Add #!/usr/bin/env python3 as the first line and run chmod +x to start a script as ./tool.py. In production, point to the venv interpreter, for example /opt/tool/.venv/bin/python, so the job never depends on a PATH.
  • Python adds the script's folder to the front of its search path. A file named json.py or random.py next to your script hides the standard module of that name. Run python3 -I script.py (isolated mode) when you analyse untrusted files. Never run Python inside a folder that you downloaded.
  • Compare versions on purpose. A tool that runs on 3.14 in your lab can meet an older version on a production server. Write python3 --version in your README and test on the oldest version that you support. Each Python version gets security fixes for about five years, then it ends. Check the end-of-life date of your version and plan the move before it comes.