A Bit About Python Module Imports

The first lines of practically every python script ever begin with the word import. Per the python docs at https://docs.python.org/2/tutorial/modules.html a module is “a file containing Python definitions and statements.” To open a python environment, simply open Terminal and type Python

python

To import a module just type import followed by the name of the module. A common one is os, so let’s import that:

import os

Now let’s use str to see where it is:

str(os)

You’ll then see what the script was that is actually the os module and where it can be found/edited/viewed. Now let’s do a couple of basic tasks with os. First, let’s grab the user who’s running the script’s id (still from a standard python interpreter):

os.getuid()

Here, we’re using a function that’s built into that os script, and the () is the parameters we’re passing to the function. When run in that interactive mode, you can use os.environ to see what environment variables your python script has access to (e.g. if you’re shelling out a command).

os.environ

Now let’s use that os to actually shell out a bash command. Here, we’ll set a variable in the python interpreter:

bashCommand="cat /test.log"

Basically, we just set a variable called bashCommand to contain a simple cat of a log file (quoting it since it has special characters and all that). Next, we’ll use os.system with the variable of the command as the parameter we’re sending into the command:

os.system(bashCommand)

Now I can clear the contents of that bashCommand variable using the del command, still from within that python console:

del bashCommand

When a module is imported, the interpreter first searches for a built-in module with the name you supply. If the interpreter can’t find a module, it will then search through the current working directory, then the PYTHONPATH wet in sys.path and . If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. Now, let’s import urllib and check out what functions it has:

import urllib dir(urllib)

Then let’s ask for help for one of them:

help(urllib.basejoin)

The response will look something like this (ymmv):

urljoin(base, url, allow_fragments=True)

    Join a base URL and a possibly relative URL to form an absolute

    interpretation of the latter.

Now you know what goes in the parenthesis when you actually call the function from within your scripts.