Modules

In [ ]:
# Compatibility with Python 3
from __future__ import print_function  # print('me') instead of print 'me'
from __future__ import division  # 1/2 == 0.5, not 0
In [ ]:
# Show figures inside the notebook
%matplotlib inline
In [ ]:
import numpy as np  # the Python array package
import matplotlib.pyplot as plt  # the Python plotting package
In [ ]:
import nibabel as nib

Let's say I have a function that loads a 4D image, and writes a text file containing the mean values for each volume:

In [ ]:
def vol_means(image_fname):
    img = nib.load(fname)
    data = img.get_data()
    means = []
    for i in range(data.shape[-1]):
        vol = data[..., i]
        means.append(np.mean(vol))
    return means

Let's check that works:

In [ ]:
my_means = vol_means('ds107_sub012_t1r2.nii')
plt.plot(my_means)

This seems like a useful function to me. I want to make a module called mymodule so I can do this:

import mymodule
means = mymodule.vol_means('ds107_sub012_t1r2.nii')

In fact, what I would really like to do, is to be able to have a script called my_script.py that prints the scan means out to the terminal window like this:

import mymodule
means = mymodule.vol_means('ds107_sub012_t1r2.nii')
print(means)

And I want to be able to run it like this from the command line:

python my_script.py

A Python module is a Python file with functions (and other things) that other modules and scripts may use. These other modules and scripts will import the module.

A script is a file that you can run with python my_script.py that will do some processing, and usually print something to the screen, put up a plot or save some data to the filesystem.

You store modules in files ending in .py. For example, the module mymodule would be in a file called mymodule.py.

A module needs to 'import' everything it uses.

You can store scripts with any extension, but it is common to use .py extensions for Python scripts as well.