-
Notifications
You must be signed in to change notification settings - Fork 141
Using FreeCAD's Persistent Configuration System
Gaël Écorchard edited this page May 2, 2020
·
1 revision
Use this template:
PREF_PATH = 'User parameter:BaseApp/Preferences/Macros/MyMacro'
PREF_BOOL_PARAM = 'BoolParameter'
PREF_FLOAT_PARAM = 'FloatParameter'
PREF_INT_PARAM = 'IntParameter'
PREF_STR_PARAM = 'StringParameter'
DEFAULT_BOOL_PARAM = True
DEFAULT_FLOAT_PARAM = 0.707
DEFAULT_INT_PARAM = 0
DEFAULT_STR_PARAM = 'FreeCAD'
parameter_group = App.ParamGet(PREF_PATH)
# Set parameters.
parameter_group.SetBool(PREF_BOOL_PARAM, True)
parameter_group.SetFloat(PREF_FLOAT_PARAM, 3.1416)
parameter_group.SetInt(PREF_INT_PARAM, 42)
parameter_group.SetString(PREF_STR_PARAM, 'Text content')
# Get parameters.
# Beware, that there is not way as of 2020-05-02 to know if a parameter
# is defined by using only `Get*()` functions. `Get*()` always returns
# a value.
# Use GetContents(), GetBools() and similars, or `get_param()` (cf. below) to
# check whether a parameter exists.
bool_parameter = parameter_group.GetBool(PREF_BOOL_PARAM, DEFAULT_BOOL_PARAM)
float_parameter = parameter_group.GetFLoat(PREF_FLOAT_PARAM, DEFAULT_FLOAT_PARAM)
int_parameter = parameter_group.GetInt(PREF_INT_PARAM, DEFAULT_INT_PARAM)
str_parameter = parameter_group.GetString(PREF_STR_PARAM, DEFAULT_STR_PARAM)
def get_param(group, param, default=None, type_=None):
"""Return a parameter with type checking and default."""
type_map = {
'Integer': int,
'Float': float,
'Boolean': bool,
'Unsigned Long': int,
'String': str,
int: int,
float: float,
bool: bool,
str: str,
}
if (type_ is not None) and (type_ not in type_map):
raise ValueError('Unkown type')
for typ_, name, val in group.GetContents():
if name != param:
continue
if (type_ is not None) and (type_map[type_] is not type_map[typ_]):
raise RuntimeError('Parameter found with wrong type: {}'.format(
typ_))
return val
if default is None:
raise RuntimeError('Parameter {} not found'.format(param))
return default
See TreeToAscii.FCMacro for a practical example.