Scripts

You can write scripts in Python to be run by the Python interpreter rather than in a Jupyter notebook.

These scripts run in a console window by default, but can also create graphical interfaces. Another alternative is to have a web server run a script that generates HTML when a browser accesses a web site (this is actually how Jupyter notebook works).

These scripts are text files whose names have a .py file type extension.

To debug these scripts we can also use the Python interpreter in interactive mode (so-called REPL mode: Read Evaluate Print Loop).

Here's a script to write 100 numbers to standard output, one per line. Instead of specifying a file name, you can use the file descriptors (0 for stdin, 1 for stdout, 2 for stderr).

In [2]:
fout=open(1,'w')
for i in range(100):
    fout.write("{}\n".format(i))
fout.close()

Here's an example of a script that reads from the standard input and writes every 10th line to the standard output. These "filters" can be used to build "pipelines" to process text.

The first, "shebang", line is used to specify that if this script is executed the python command should be used to interpret it. This does not work on Windows (you must run the python interpreter with a .bat file or associate the extension with the python interpreter).

In [3]:
#!/usr/bin/env python
#
# copy every 10'th line from stdin to stdout
# 
fin=open(0)
fout=open(1,'w')
try:
    for s in fin:
        fout.write(s)
        for s in range(9):
            next(fin)
except:
    fin.close()
    fout.close()