Skip to main content

Unit 7 · Borrowing Code · Lesson 55 of 57

Packages and pip

Packages and pip

math, random and secrets come with Python. But there are hundreds of thousands more modules out there, written by people all over the world, and they're free to use.

They live on a website called PyPI (the Python Package Index, at pypi.org). A module (or a bundle of them) that you can download from there is called a package.

To download them, you use a tool called pip. It's a command you run in the terminal, not in Python:

pip install requests

That downloads requests, a really popular package for talking to websites. Then, in your Python code, you can just import requests like it came with Python.

Wait, is that safe?

Great question, my fellow CyberAcadian. Not always.

Anyone can upload a package to PyPI. Attackers know that, so they upload packages with names that are almost the same as popular ones, like reqeusts or request, and hide malware inside. Make one typo in pip install, and you just ran someone else's code on your computer.

This is called typosquatting, and it's a type of supply chain attack: instead of attacking you directly, the attacker poisons something you trust and waits for you to grab it.

So before you pip install something:

  • Double check the spelling. Seriously.
  • Look it up on pypi.org first. Is it popular? Does it have a real website and real documentation?
  • Only install what you actually need.

Your turn

The terminal on this page is a real Linux machine (remember Intro to Linux?), and it already has pip on it. Try these two commands:

pip --version
pip list

The first tells you which version of pip you have. The second lists every package that's already installed.

If you try pip install here, Linux will stop you and start talking about a "virtual environment." That's a safety feature to keep your system's Python from getting messed up, and it's a topic for another day!

Live Linux terminal

This lesson comes with a real Ubuntu machine that runs in your browser, so you type every command yourself. Create a free account to do this part.

Tasks to do

Do each one in the terminal or on your practice VM, and it checks itself off. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.