11. utils — A collection of miscellaneous utility functions. — pyFormex v0.8.6 documentation

### Navigation

- index
- modules |
- next |
- previous |
- pyFormex v0.8.6 documentation >
- pyFormex reference manual >

# 11. `utils` — A collection of miscellaneous utility functions.

`Classes defined in module utils`

class `utils.` `NameSequence`(name, ext='')

  A class for autogenerating sequences of names.

  The name is a string including a numeric part, which is incremented at each call of the ‘next()’ method.

  The constructor takes name template and a possible extension as arguments. If the name starts with a non-numeric part, it is taken as a constant part. If the name ends with a numeric part, the next generated names will be obtained by incrementing this part. If not, a string ‘-000’ will be appended and names will be generated by incrementing this part.

  If an extension is given, it will be appended as is to the names. This makes it possible to put the numeric part anywhere inside the names.

  Example:

      >>> N = NameSequence('hallo.98')
      >>> [ N.next() for i in range(3) ]
      ['hallo.98', 'hallo.99', 'hallo.100']
      >>> NameSequence('hallo','.png').next()
      'hallo-000.png'
      >>> N = NameSequence('/home/user/hallo23','5.png')
      >>> [ N.next() for i in range(2) ]
      ['/home/user/hallo235.png', '/home/user/hallo245.png']

  `next`()

    Return the next name in the sequence

  `peek`()

    Return the next name in the sequence without incrementing.

  `glob`()

    Return a UNIX glob pattern for the generated names.

    A NameSequence is often used as a generator for file names. The glob() method returns a pattern that can be used in a UNIX-like shell command to select all the generated file names.

`Functions defined in module utils`

`utils.` `checkVersion`(name, version, external=False)

  Checks a version of a program/module.

  name is either a module or an external program whose availability has been registered. Default is to treat name as a module. Add external=True for a program.

  Return value is -1, 0 or 1, depending on a version found that is <, == or > than the requested values. This should normally understand version numbers in the format 2.10.1 Returns -2 if no version found.

`utils.` `hasModule`(name, check=False)

  Test if we have the named module available.

  Returns a nonzero (version) string if the module is available, or an empty string if it is not.

  By default, the module is only checked on the first call. The result is remembered in the the_version dict. The optional argument check==True forces a new detection.

`utils.` `hasExternal`(name, force=False)

  Test if we have the external command ‘name’ available.

  Returns a nonzero string if the command is available, or an empty string if it is not.

  The external command is only checked on the first call. The result is remembered in the the_external dict.

`utils.` `checkModule`(name=None)

  Check if the named Python module is available, and record its version.

  The version string is returned, empty if the module could not be loaded. The (name,version) pair is also inserted into the the_version dict.

`utils.` `checkExternal`(name=None, command=None, answer=None)

  Check if the named external command is available on the system.

  name is the generic command name, command is the command as it will be executed to check its operation, answer is a regular expression to match positive answers from the command. answer should contain at least one group. In case of a match, the contents of the match will be stored in the the_external dict with name as the key. If the result does not match the specified answer, an empty value is inserted.

  Usually, command will contain an option to display the version, and the answer re contains a group to select the version string from the result.

  As a convenience, we provide a list of predeclared external commands, that can be checked by their name alone. If no name is given, all commands in that list are checked, and no value is returned.

`utils.` `strNorm`(s)

  Normalize a string.

  Text normalization removes all ‘&’ characters and converts it to lower case.

`utils.` `prefixFiles`(prefix, files)

  Prepend a prefix to a list of filenames.

`utils.` `matchMany`(regexps, target)

  Return multiple regular expression matches of the same target string.

`utils.` `matchCount`(regexps, target)

  Return the number of matches of target to regexps.

`utils.` `matchAny`(regexps, target)

  Check whether target matches any of the regular expressions.

`utils.` `matchNone`(regexps, target)

  Check whether targes matches none of the regular expressions.

`utils.` `matchAll`(regexps, target)

  Check whether targets matches all of the regular expressions.

`utils.` `listTree`(path, listdirs=True, topdown=True, sorted=False, excludedirs=[], excludefiles=[], includedirs=[], includefiles=[])

  List all files in path.

  If `dirs==False`, directories are not listed. By default the tree is listed top down and entries in the same directory are unsorted.

  exludedirs and excludefiles are lists of regular expressions with dirnames, resp. filenames to exclude from the result.

  includedirs and includefiles can be given to include only the directories, resp. files matching any of those patterns.

  Note that ‘excludedirs’ and ‘includedirs’ force top down handling.

`utils.` `removeTree`(path, top=True)

  Remove all files below path. If top==True, also path is removed.

`utils.` `pyformexFiles`(relative=False)

  Return a list of the pyformex source .py files.

`utils.` `setSaneLocale`(localestring='')

  Set a sane local configuration for LC_NUMERIC.

  localestring is the locale string to be set, e.g. ‘en_US.UTF-8’

  This will change the `LC_ALL` setting to the specified string, and set the `LC_NUMBERIC` to ‘C’.

  Changing the LC_NUMERIC setting is a very bad idea! It makes floating point values to be read or written with a comma instead of a the decimal point. Of course this makes input and output files completely incompatible. You will often not be able to process these files any further and create a lot of troubles for yourself and other people if you use an LC_NUMERIC setting different from the standard.

  Because we do not want to help you shoot yourself in the foot, this function always sets `LC_NUMERIC` back to a sane value and we call this function when pyFormex is starting up.

`utils.` `all_image_extensions`()

  Return a list with all known image extensions.

`utils.` `fileDescription`(ftype)

  Return a description of the specified file type.

  The description of known types are listed in a dict file_description. If the type is unknown, the returned string has the form `TYPE files (*.type)`

`utils.` `fileType`(ftype)

  Normalize a filetype string.

  The string is converted to lower case and a leading dot is removed. This makes it fit for use with a filename extension.

  Example:

      >>> fileType('pdf')
      'pdf'
      >>> fileType('.pdf')
      'pdf'
      >>> fileType('PDF')
      'pdf'
      >>> fileType('.PDF')
      'pdf'

`utils.` `fileTypeFromExt`(fname)

  Derive the file type from the file name.

  The derived file type is the file extension part in lower case and without the leading dot.

  Example:

      >>> fileTypeFromExt('pyformex.pdf')
      'pdf'
      >>> fileTypeFromExt('.pyformexrc')
      ''
      >>> fileTypeFromExt('pyformex')
      ''

`utils.` `findIcon`(name)

  Return the file name for an icon with given name.

  If no icon file is found, returns the question mark icon.

`utils.` `projectName`(fn)

  Derive a project name from a file name.

  The project name is the basename f the file without the extension.

`utils.` `mtime`(fn)

  Return the (UNIX) time of last change of file fn.

`utils.` `timeEval`(s, glob=None)

  Return the time needed for evaluating a string.

  s is a string with a valid Python instructions. The string is evaluated using Python’s eval() and the difference in seconds between the current time before and after the evaluation is printed. The result of the evaluation is returned.

  This is a simple method to measure the time spent in some operation. It should not be used for microlevel instructions though, because the overhead of the time calls. Use Python’s timeit module to measure microlevel execution time.

`utils.` `countLines`(fn)

  Return the number of lines in a text file.

`utils.` `runCommand`(cmd, RaiseError=True, quiet=False)

  Run a command and raise error if exited with error.

  cmd is a string with the command to be run. The command is run in the background, waiting for the result. If no error occurs, the exit status and stdout are returned. Else an error is raised by default.

`utils.` `spawn`(cmd)

  Spawn a child process.

`utils.` `killProcesses`(pids, signal)

  Send the specified signal to the processes in list

`utils.` `changeExt`(fn, ext)

  Change the extension of a file name.

  The extension is the minimal trailing part of the filename starting with a ‘.’. If the filename has no ‘.’, the extension will be appended. If the given extension does not start with a dot, one is prepended.

`utils.` `tildeExpand`(fn)

  Perform tilde expansion on a filename.

  Bash, the most used command shell in Linux, expands a ‘~’ in arguments to the users home direction. This function can be used to do the same for strings that did not receive the bash tilde expansion, such as strings in the configuration file.

`utils.` `userName`()

  Find the name of the user.

`utils.` `is_pyFormex`(filename)

  Checks whether a file is a pyFormex script.

  A script is considered to be a pyFormex script if its first line starts with ‘#!’ and contains the substring ‘pyformex’ A file is considered to be a pyFormex script if its name ends in ‘.py’ and the first line of the file contains the substring ‘pyformex’. Typically, a pyFormex script starts with a line:

      #!/usr/bin/pyformex

`utils.` `splitEndDigits`(s)

  Split a string in any prefix and a numerical end sequence.

  A string like ‘abc-0123’ will be split in ‘abc-‘ and ‘0123’. Any of both can be empty.

`utils.` `splitStartDigits`(s)

  Split a string in a numerical sequence and any suffix.

  A string like ‘0123-abc’ will be split in ‘0123’ and ‘-abc’. Any of both can be empty.

`utils.` `prefixDict`(d, prefix='')

  Prefix all the keys of a dict with the given prefix.

  - d: a dict where all the keys are strings.
  - prefix: a string

  The return value is a dict with all the items of d, but where the keys have been prefixed with the given string.

`utils.` `subDict`(d, prefix='', strip=True)

  Return a dict with the items whose key starts with prefix.

  - d: a dict where all the keys are strings.
  - prefix: a string
  - strip: if True (default), the prefix is stripped from the keys.

  The return value is a dict with all the items from d whose key starts with prefix. The keys in the returned dict will have the prefix stripped off, unless strip=False is specified.

`utils.` `selectDict`(d, keys)

  Return a dict with the items whose key is in keys.

  - d: a dict where all the keys are strings.
  - keys: a set of key values, can be a list or another dict.

  The return value is a dict with all the items from d whose key is in keys. See `removeDict()` for the complementary operation.

  Example:

      >>> d = dict([(c,c*c) for c in range(6)])
      >>> selectDict(d,[4,0,1])
      {0: 0, 1: 1, 4: 16}

`utils.` `removeDict`(d, keys)

  Remove a set of keys from a dict.

  - d: a dict
  - keys: a set of key values

  The return value is a dict with all the items from d whose key is not in keys. This is the complementary operation of selectDict.

  Example:

      >>> d = dict([(c,c*c) for c in range(6)])
      >>> removeDict(d,[4,0])
      {1: 1, 2: 4, 3: 9, 5: 25}

`utils.` `refreshDict`(d, src)

  Refresh a dict with values from another dict.

  The values in the dict d are update with those in src. Unlike the dict.update method, this will only update existing keys but not add new keys.

`utils.` `stuur`(x, xval, yval, exp=2.5)

  Returns a (non)linear response on the input x.

  xval and yval should be lists of 3 values: `[xmin,x0,xmax], [ymin,y0,ymax]`. Together with the exponent exp, they define the response curve as function of x. With an exponent > 0, the variation will be slow in the neighbourhood of (x0,y0). For values x < xmin or x > xmax, the limit value ymin or ymax is returned.

`utils.` `interrogate`(item)

  Print useful information about item.

### Navigation

- index
- modules |
- next |
- previous |
- pyFormex v0.8.6 documentation >
- pyFormex reference manual >