Scripts

Definition: A script is a collection of instructions written in a given interpreted programming language such as Bash, Python, or R) and gathered in a text file. If given a script, the corresponding interpreter (such as the Bash interpreter, the Python interpreter, or the R interpreter) will execute all the instructions contained in the script in order from the first line to the last line. In other words, a script is a program that is written in an interpreted programming language (as opposed to compiled programming language such as C, C++, and Java).

Usually, one choose a text editor (such as vi, emacs, gedit, notepad, etc. ) to write a script. Then one invoke the interpreter on the script by typing the interpreter name on the command line, followed by the path indicating where the script file is located. For instance:

bash MyScript.sh
python MyScript.py
Rscript MyScript.R

In this notebook, we will also learn how to use the ipython notebook as an editor to write your script from it, and how to run them from within the notebook.

Remark: The file extension .sh, .py, .R etc. in the script file names above are just conventions; it is not needed by the interpreter in order to execute the script. It's just nice, since you know the programming language just by looking at the file name.

The notebook as an editor

The notebook editor

The notebook editor is called by using the magic command

%%file filename

at the beginning of a code cell.


In [ ]:
%%file MyScript.py

print 'Hellow world'

Running the script from the notebook

Two solutions:

Solution 1 involve using a bash cell:


In [ ]:
%%bash

python MyScript.py

Solution 2: Use the magic command

%run

In [ ]:
%run MyScript.py

Script input and output

A script can be seen as one of the programming embodiments of the mathematical idea of a mathematical function; that is, a recipe $f$, denoted in math using the expressive arrow symbologism $f:A\rightarrow B$, that knows how to transform any element $a\in A$ from an input set $A$ into an output element $f(b)\in B$ belonging to an output set $B$. (Later on, we will see that there is a also a notion of function in Python, which can be used withing scripts, and which can be regarded as mini-scripts withing scripts).

The main difference between mathematical functions and their programmatic embodiements is that in programming the input set can be split into different "physical" components. For instance, a script can take its arguements from a default place called the standard input, as well as from files stored on the file system (or the internet) and command parameters. Here is a drawing summarizing the various input and output source for a script:

Input from command parameters


In [ ]:

Input and output from files


In [ ]:


In [ ]:


In [ ]:

Standard input, output, and error streams


In [ ]:


In [ ]:


In [ ]: