COMP1730COMP6730 Programming for Scientists
Modules and programs
Lecture outline
python modulesimport
Commandline interface and scripting
Modules
Modules
Every python file is a module.
A module is a sequence of statements.Every module has a name.
When the python shell runs in script mode, the file its executing becomes the main module.
Its name becomesmain .
Its namespace is the global namespace.
The first time a module is imported, that module
is loaded executed; it may later be reloaded.
Every loaded module creates a separate permanent namespace.
When executing import modname, the python interpreter:
checks if modname is already loaded;if not or if reloading, it:
finds the module file normally modname.pyexecutes the file in a new namespace;
and stores the module object roughly,
namespace in the system dictionary of
loaded modules;
and then associates modname with the
module object in the current namespace.
Note: the Spyder IDE reloads all userdefined
modules on first import when running a file.
The global variable name in every module namespace stores the module name.
sys.modules is a dictionary of all loaded modules.
dirmodule returns a list of names defined in modules namespace
dir lists the current global namespace.
name
main
import sys
lensys.modules
sys.modulesmath. name math
dir
, sys
import math
dir
, sys, math
def some useful functionx:
if name main :
this part will not execute whenthe module is imported printsome useful function0
Code within the if statement will execute when the module is run, but not when its imported guarded main.
For example, test cases.
The commandline
A commandline terminal or shell is a text IO interface to the computers operating system OS.
The shell is an interpreter for a command programming language.
Image from wikipedia
The languages of shells are more or less different, but some aspects are fairly common.
Some concepts from the commandline interface explain how programs interact with the OS.
Typically, there is a current working directory.
To run a executable program, type its name.Where the OS searches for programs is
usually configurable.
Alternatively, enter the full path.
To run a python program file:python3 my prog.py
Runs the python shell in script mode.
Can pass arguments strings to the program:python3 my prog.py arg1 arg two
Inputs that the OS provides to the program:
A list of commandline arguments strings.
A set of environment variables keyvalue
pairs, both byte strings.
Open files or filelike objects for standard
input and standard output.
You can access these within python:
sys.argv
os.environ and os.getenvvarsys.stdin and sys.stdout
By default, input.. reads sys.stdin and print writes to sys.stdout.
Reviews
There are no reviews yet.