Previous topic

mmf.utils.run

This Page

mmf.utils.script

AttributeError
OptionParser(*argv, **kwargs) Standard optparse.OptionParser class with following extra options:
do(cmds[, mesg, query, options]) Execute a command after first confirming with the user and presenting information (if verbose options are selected).
os_do(action[, options])
yes_no([default]) This function prompts the user for a yes or no answer and will accept a default response.
do_f(fcns[, mesg, query, options]) Execute a function after first confirming with the user and presenting information (if verbose options are selected).
execute(command[, cwd]) This function executes the specified command at the os level.
check_access(path, mode) Check that path has proper access as specified by mode.
backup(file[, options]) Backup a file and return backup name.

Inheritance diagram for mmf.utils.script:

Inheritance diagram of mmf.utils.script

Utilities for writing scripts.

Here is a sample script to get you started:

#!/usr/bin/python # Note that the first line only helps on unix systems. It specified # the interpreter to use to interpret this file. On other systems you # may have to create an alias with the proper python invocation.

import sys,os,re import mmf.utils.script as script

# Parse arguments parser = script.OptionParser() parser.add_option(“–home”,

type=”string”, dest=”home_dir”, default=”~”, help=”use <home> rather than ~ for installation”, metavar=”<home>”)
parser.add_option(“–src”,

type=”string”, dest=”src_dir”, default=”work/unix/configurations/linux”, help=”use config files in <src> rather than ” +

“<home>/work/unix/configurations/linux”,

metavar=”<src>”)

(options, args) = parser.parse_args()

############# Script Body def main():

# Setup directories home_dir = os.path.expanduser(options.home_dir) check_access(home_dir,os.F_OK | os.R_OK | os.W_OK | os.X_OK) if options.verbose: print “Using <home> = ” + home_dir

src_dir = os.path.expanduser(options.src_dir) if ‘.’ == src_dir or ‘..’ == src_dir:

src_dir = os.path.abspath(src_dir)
if not os.path.isabs(src_dir):
src_dir = os.path.normpath(os.path.join(home_dir,src_dir))

check_access(src_dir,os.F_OK | os.R_OK) if options.verbose: print “Using <src> = ” + src_dir

# Get all files in src_dir directory for (root, dirs, files) in os.walk(src_dir):

if ‘CVS’ in dirs:
dirs.remove(‘CVS’) # don’t visit CVS directories
def is_not_temp(f):
return (“#” not in f) and (“~” not in f)

files = filter(is_not_temp,files) for f in files:

src = os.path.join(root,f) fd = open(src,’r’)

# Files are linked when the second line of the file # looks like “# dest=~/.xsession” with optional whitespace line1 = fd.readline() line2 = fd.readline() fd.close()

dest = re.match(r”As*[#;]+s*dests*=s*(S*)”,line2) if dest is not None:

dest = os.path.expanduser(dest.group(1))
if dest is not None:
if os.path.islink(dest):

mesg = “Symlink “+dest+” exists.” query = “Remove and replace with link to “+src+”?” cmds = [“os.remove(“+`dest`+”)”,

“os.symlink(“+`src`+ ”,” +`dest`+”)”]

do(cmds,mesg,query)

elif os.path.isfile(dest):

mesg = “File “+dest+” exists.” query = “Backup and symlink “+src+” to “+dest+”?” cmds=[“backup(“+`dest`+”)”,

“os.symlink(“+`src`+”,”+`dest`+”)”]

do(cmds,mesg,query)

else:
query = “Link “+src+” to “+dest+”?” cmds = [“os.symlink(“+`src`+”,”+`dest`+”)”] do(cmds,query=query)
if __name__==”__main__”:
main()
class mmf.utils.script.AttributeError[source]

Bases: exceptions.Exception

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

class mmf.utils.script.OptionParser(*argv, **kwargs)[source]

Bases: optparse.OptionParser

Standard optparse.OptionParser class with following extra options: -v, –verbose -n, –no-action -i, –interactive

The parse_args() method is also overloaded to maintain a local copy of the options for use as a default argument.

Methods

add_option(Option) add_option(opt_str, ...)
add_option_group(*args, **kwargs)
add_options(option_list)
check_values(values : Values, ...) -> (values : Values, args : [string])
destroy() Declare that you are done with this OptionParser. This cleans up
disable_interspersed_args() Set parsing to stop on the first non-option.
enable_interspersed_args() Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments.
error(msg : string) Print a usage message incorporating ‘msg’ to stderr and exit.
exit([status, msg])
expand_prog_name(s)
format_description(formatter)
format_epilog(formatter)
format_help([formatter])
format_option_help([formatter])
get_default_values()
get_description()
get_option(opt_str)
get_option_group(opt_str)
get_prog_name()
get_usage()
get_version()
has_option(opt_str)
parse_args(*argv, **kwargs) Sets module variable options to the latest parsing of arguments.
print_help(file : file = stdout) Print an extended help message, listing all options and any
print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to ‘file’ (default stdout).
print_version(file : file = stdout) Print the version message for this program (self.version) to ‘file’ (default stdout).
remove_option(opt_str)
set_conflict_handler(handler)
set_default(dest, value)
set_defaults(**kwargs)
set_description(description)
set_process_default_values(process)
set_usage(usage)
parse_args(*argv, **kwargs)[source]

Sets module variable options to the latest parsing of arguments. This is used as a defualt argument in other methods of this module.

mmf.utils.script.do(cmds, mesg=None, query=None, options=None)[source]

Execute a command after first confirming with the user and presenting information (if verbose options are selected).

Return False if there was an error.

mmf.utils.script.os_do(action, options=None)[source]
mmf.utils.script.yes_no(default='')[source]

This function prompts the user for a yes or no answer and will accept a default response. Exceptions (such as EOF) are not caught. The result is True for ‘yes’ and False for ‘no’.

mmf.utils.script.do_f(fcns, mesg=None, query=None, options=None)[source]

Execute a function after first confirming with the user and presenting information (if verbose options are selected).

Return False if there was an error.

mmf.utils.script.execute(command, cwd=None)[source]

This function executes the specified command at the os level.

mmf.utils.script.check_access(path, mode)[source]

Check that path has proper access as specified by mode.

Throws an AttributeError on failure

mmf.utils.script.backup(file, options=None)[source]

Backup a file and return backup name.