Python pip in Depth
pip is a tool that installs Python packages into an environment.
Install a package (shell)
This is a shell transcript. pip downloads the package into the active environment.
$ pip install requestsList what you have (shell)
pip list shows every package in this environment, with its version.
$ pip listInspect one package (shell)
pip show prints one package's version and where it lives.
$ pip show requestsSave your exact versions (shell)
pip freeze prints pins, one per line. The > sign saves them into a file.
$ pip freeze > requirements.txtA requirements file (config)
This config file lists one package per line. Each line is a name plus a specifier.
requests==2.32.3
flask>=3.0
click~=8.1Install from the file (shell)
Another machine can rebuild the same setup from the file.
$ pip install -r requirements.txtExample
text = """requests==2.32.3
flask>=3.0
click~=8.1"""
def split_line(line):
for i, ch in enumerate(line):
if ch in "=<>~":
return line[:i], line[i:]
return line, "(any version)"
rows = []
for line in text.splitlines():
name, spec = split_line(line)
rows.append((name, spec))
for name, spec in sorted(rows):
print(name, "->", spec)Key points
- Pin: writing one exact version for a package, so every install gets the same one
- Specifier: the short rule after a package name that says which versions are allowed
- == means exactly this version: requests==2.32.3 is a pin
- >= means this version or any newer one
- ~= means compatible updates only: ~=8.1 allows 8.2 but not 9.0
- Use pip freeze to print your exact versions in requirements.txt style
- Use python3 -m pip to run the pip that belongs to one named Python
- Use pip to install Python packages into an environment.
In this example, text holds the same three lines a requirements.txt file would hold. split_line walks one line character by character. It stops at the first specifier character, one of = < > or ~. Everything before it is the name. Everything from it onward is the specifier. The loop builds one pair per line. sorted(rows) orders the pairs by name. The last loop prints each name with its specifier.
Note
pip installs into the environment it belongs to.
If a package installs fine but will not import, the install and the run used two different environments.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
pip install worked, but your program fails with ModuleNotFoundError for the same package. What is the classic cause?