Python Extras

Most of you know Python, but it's a big language, and I've found that many of you don't know about a few features that are useful to know about, both in CS 304 and in general.

  • installing packages
  • importing packages/modules
  • files as modules
  • files as scripts
  • scripts with command-line arguments
  • files that are both modules and scripts

If you already know about these things; great. You might skim this just to be sure. Or skip down to the summary to see if that is clear.

Installing Packages with Pip

The Python language provides lots of useful stuff, but the Python community has written lots of useful packages. Some of those packages are automatically installed when you install Python. Others can be installed later from various repositories on the web.

For example, if you'd like to write a web scraper, you might want to install BeautifulSoup4. That link goes to PyPi, which hosts thousands of Python packages.

The command to install a package is pip. It's used by the System Administrator to install a package to the system folders, which are shared among all the users. Here's an example of how to install BeautifulSoup4 using pip:

# pip install beautifulsoup4

Notice the prompt is a hash (#) rather than the usual dollar sign ($). That's a standard way of signalling that the command is reserved for administrators, not for ordinary users.

However, you can install your own copy of a Python package in your own directory by using virtual environments, called virtualenv. We'll learn more about that topic separately.

Import

To use one of those wonderful Python packages in our Python program, we have to import it. Let's use the datetime package (which is standard, so no need to install).

Files as Modules

In principle, we could write our Python programs in one file, but as that file gets bigger, it becomes more unwieldy. It's a good idea to break your program up (divide-and-conquer) into modules, where a module is a set of related variables, functions, classes, objects and methods (stuff) that can be imported into other