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
To import a module just type import followed by the name of the module. A common one is os, so let’s import that:
Now let’s use str to see where it is:
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):
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).
Now let’s use that os to actually shell out a bash command. Here, we’ll set a variable in the python interpreter:
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:
Now I can clear the contents of that bashCommand variable using the del command, still from within that python console:
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:
Then let’s ask for help for one of them:
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.