5. script — Basic pyFormex script functions

The script module provides the basic functions available in all pyFormex scripts. These functions are available in GUI and NONGUI applications, without the need to explicitely importing the script module.

5.1. Functions defined in module script

script.Globals()[source]

Return the globals that are passed to the scripts on execution.

When running pyformex with the –nogui option, this contains all the globals defined in the module formex (which include those from coords, arraytools and numpy.

When running with the GUI, this also includes the globals from gui.draw (including those from gui.color).

Furthermore, the global variable __name__ will be set to either ‘draw’ or ‘script’ depending on whether the script was executed with the GUI or not.

script.export(dic)[source]

Export the variables in the given dictionary.

script.export2(names, values)[source]

Export a list of names and values.

script.forget(names)[source]

Remove the global variables specified in list.

script.forgetAll()[source]

Delete all the global variables.

script.rename(oldnames, newnames)[source]

Rename the global variables in oldnames to newnames.

script.listAll(clas=None, like=None, filtr=None, dic=None, sort=False)[source]

Return a name list of objects that match the given criteria.

Parameters:
  • clas (class | list of classes) – If provided, only instances of these class(es) will be returned.

  • like (str) – If provided, only object names starting with this string will be returned.

  • filtr (func) – A function taking an object name as parameter and returning True or False. If specified, only object names returning True will be returned.

  • dic (mapping) – A dictionary with strings as keys. Objects from this dict will be returned. The default is the pyFormex global dict: pf.PF.

  • sort (bool) – If True, the returned list will be sorted.

Returns:

list – A list of keys from dic matching the criteria.

Examples

>>> from pyformex.core import Mesh, TriSurface
>>> pf.PF.clear()
>>> M = Mesh()
>>> M1 = Mesh(eltype='tri3')
>>> S = M1.toSurface()
>>> F = S.toFormex()
>>> export({'Mint':2, 'M':M, 'S':S, 'F':F, 'M1':M1})
>>> listAll()
['Mint', 'M', 'S', 'F', 'M1']
>>> listAll(clas=Mesh)
['M', 'S', 'M1']
>>> listAll(clas=Mesh, filtr=lambda o: isinstance(pf.PF[o], TriSurface))
['S']
>>> listAll(like='M')
['Mint', 'M', 'M1']
script.named(name)[source]

Returns the global object named name.

script.getcfg(name, default=None)[source]

Return a value from the configuration or None if nonexistent.

script.ask(question, choices=None, default='')[source]

Ask a question and present possible answers.

If no choices are presented, anything will be accepted. Else, the question is repeated until one of the choices is selected. If a default is given and the value entered is empty, the default is substituted. Case is not significant, but choices are presented unchanged. If no choices are presented, the string typed by the user is returned. Else the return value is the lowest matching index of the users answer in the choices list. Thus, ask(‘Do you agree’,[‘Y’,’n’]) will return 0 on either ‘y’ or ‘Y’ and 1 on either ‘n’ or ‘N’.

script.ack(question)[source]

Show a Yes/No question and return True/False depending on answer.

script.error(message)[source]

Show an error message and wait for user acknowlegement.

script.playScript(scr, name=None, filename=None, argv=[], encoding=None)[source]

Run a pyFormex script specified as text.

Parameters:
  • scr (str) – A multiline string holding a valid Python program, ususally a pyFormex script. The program will be executed in an internal interpreter, with the Globals() as local definitions. There is a lock to prevent multiple scripts from being executed at the same time. This implies that pyFormex scripts can not start another script.

  • name (str, optional) – If specified, this name is set in the global variable pf.scriptName to identify the currently running script.

  • filename (path_like, optional) – If specified, this filename is set into the global variable __file__ in the script executing environment.

  • argv (list, optional) – This value is set in the global variable _argv_. It is mostly used to pass an argument list to the script in –nogui mode.

  • encoding (str, optional) – If specified, this is an encoding scheme for the script text provided in scr. The text will be decoded by the specified scheme prior to execution. This is mostly intended to obfuscate the code for occasional viewer.

script.runScript(fn, argv=[])[source]

Run a pyFormex script stored on a file.

Parameters:
  • fn (path_like) – The name of a file holding a pyFormex script.

  • argv (list, optional) – A list of arguments to be passed to the script. This argument list becomes available in the script as the global variable _argv_.

Notes

This calls playScript() to execute the code read from the script file.

See also

runApp

run a pyFormex application

runAny

run a pyFormex script or app

script.runApp(appname, argv=[], refresh=False, lock=True, check=True, wait=False)[source]

Run a pyFormex application.

A pyFormex application is a Python module that can be loaded in pyFormex and at least contains a function ‘run()’. Running the application means execute this function.

Parameters:
  • appname (str) – The name of the module in Python dot notation. The module should live in a path included in the ‘appsdirs’ configuration variable.

  • argv (list, optional) – A list of arguments to be passed to the app. This argument list becomes available in the app as the global variable _argv_.

  • refresh (bool) – If True, the app module will be reloaded before running it.

  • lock (bool) – If True (default), the running of the app will be recorded so that other apps can be locked out while this one has not finished.

  • check (bool) – If True (default), check that no other app is running at this time. If another app is running, either wait or return without executing.

  • wait (bool) – If True, and check is True and another app is busy, wait until that one has finished and then start execution.

Returns:

int – The return value of the run function. A zero value is supposed to mean a normal exit.

See also

runScript

run a pyFormex script

runAny

run a pyFormex script or app

script.runAny(appname=None, argv=[], remember=True, refresh=False, wait=False)[source]

Run a pyFormex application or script file.

Parameters:
  • appname (str) – Either the name of a pyFormex application (app) or the name of a file containing a pyFormex script. An app name is specified in Python fotted module format (pkg.module) and the path to the package should be in the configuration variable ‘appsdirs’. If no appname is provided, the current app/script set in the GUI will be run, if it is set.

  • argv (list, optional) – A list of arguments to be passed to the app. This argument list becomes available in the script or app as the global variable _argv_.

  • remember (bool) – If True (default), the app is set as the current app in the GUI, so that the play button can be used to run it again.

  • refresh (bool) – Parameters passed to runApp().

  • wait (bool) – Parameters passed to runApp().

See also

runScript

run a pyFormex script

runApp

run a pyFormex application

script.autoExport(g)[source]

Autoexport globals from script/app globals.

Parameters:

g (dict) – A dictionary holding definitions topossibly autoexport. Normally this is the globals dict from a script/app run enviroment.

Notes

This exports some objects from the script/app runtime globals to the pf.PF session globals directory. The default is to export all instances of Geometry.

This can be customized in the script/app by setting the global variables autoglobals and autoclasses. If autoglobals evaluates to False, no autoexport will be done. If set to True, the default autoexport will be done: all instances of Geometry. If set to a list of names, only the specified names will be exported. The global variable autoclasses may be set to a list of class names and all global instances of the specified classes will be exported.

Remember that the variables need to be globals in your script/app in order to be autoexported, and that the autoglobals feature should not be disabled in your configuration (it is enabled by default).

script.breakpt(msg=None)[source]

Set a breakpoint where the script can be halted on a signal.

If an argument is specified, it will be written to the message board.

The exitrequested signal is usually emitted by pressing a button in the GUI.

script.stopatbreakpt()[source]

Set the exitrequested flag.

script.exit(all=False)[source]

Exit from the current script or from pyformex if no script running.

script.quit()[source]

Quit the pyFormex program

This is a hard exit from pyFormex. It is normally not called directly, but results from an exit(True) call.

script.processArgs(args)[source]

Run pyFormex scripts/apps in batch mode.

Arguments are interpreted as names of script files, possibly interspersed with arguments for the scripts. Each running script should pop the required arguments from the list.

script.setPrefs(res, save=False)[source]

Update the current settings (store) with the values in res.

res is a dictionary with configuration values. The current settings will be update with the values in res.

If save is True, the changes will be stored to the user’s configuration file.

script.chdir(path, create=False)[source]

Change the current working directory.

If path exists and it is a directory name, make it the current directory. If path exists and it is a file name, make the containing directory the current directory. If path does not exist and create is True, create the path and make it the current directory. If create is False, raise an Error.

Parameters:
  • path (path_like) – The name of a directory or file. If it is a file, the name of the directory containing the file is used. If the path exists, it is made the current directory. The path can be an absolute or a relative pathname. A ‘~’ character at the start of the pathname will be expanded to the user’s home directory.

  • create (bool.) – If True and the specified path does not exist, it will be created and made the current directory. The default (False) will do nothing if the specified path does not exist.

Notes

The new current directory is stored in the user’s preferences file for persistence between pyFormex invocations.

script.pwdir()[source]

Print the current working directory.

script.mkdir(path, clear=False, new=False)[source]

Create a directory.

Create a directory, including any needed parent directories. Any part of the path may already exist.

Parameters:
  • path (path_like) – The pathname of the directory to create, either an absolute or relative path. A ‘~’ character at the start of the pathname will be expanded to the user’s home directory.

  • clear (bool.) – If True, and the directory already exists, its contents will be deleted.

  • new (bool.) – If True, requires the directory to be a new one. An error will be raised if the path already exists.

  • different (The following table gives an overview of the actions for) –

  • parameters (combinations of the) –

  • ============= (====== ==== ===================) –

  • exists (clear new path does not exist path) –

  • =============

  • is (F F newly created kept as) –

  • emptied (T F newly created) –

  • OSError (T/F T newly created raise) –

  • =============

Returns:

Path – The tilde-expanded path of the directory, if the operation was successful.

Raises:

OSError: – in the following cases: - the directory could not be created, - clear=True, and the existing directory could not be cleared, - new=False, clear=False, and the existing path is not a directory, - new=True, and the path exists.

script.runtime()[source]

Return the time elapsed since start of execution of the script.

script.startGui()[source]

Start the gui

This can be used to start the gui when pyFormex was loaded from a Python shell.