mozprofile — Create and modify Mozilla application profiles

Mozprofile is a python tool for creating and managing profiles for Mozilla’s applications (Firefox, Thunderbird, etc.). In addition to creating profiles, mozprofile can install addons and set preferences Mozprofile can be utilized from the command line or as an API.

The preferred way of setting up profile data (addons, permissions, preferences etc) is by passing them to the profile constructor.

Addons

exception mozprofile.addons.AddonFormatError

Exception for not well-formed add-on manifest files

class mozprofile.addons.AddonManager(profile, restore=True)

Handles all operations regarding addons in a profile including: installing and cleaning addons

classmethod addon_details(addon_path)

Returns a dictionary of details about the addon.

Parameters

addon_path – path to the add-on directory or XPI

Returns:

{'id':      u'rainbow@colors.org', # id of the addon
 'version': u'1.4',                # version of the addon
 'name':    u'Rainbow',            # name of the addon
 'unpack':  False }                # whether to unpack the addon
clean()

Clean up addons in the profile.

get_addon_path(addon_id)

Returns the path to the installed add-on

Parameters

addon_id – id of the add-on to retrieve the path from

install(addons, **kwargs)

Installs addons from a filepath or directory of addons in the profile.

Parameters
  • addons – paths to .xpi or addon directories

  • unpack – whether to unpack unless specified otherwise in the install.rdf

classmethod is_addon(addon_path)

Checks if the given path is a valid addon

Parameters

addon_path – path to the add-on directory or XPI

remove_addon(addon_id)

Remove the add-on as specified by the id

Parameters

addon_id – id of the add-on to be removed

Addons may be installed individually or from a manifest.

Example:

from mozprofile import FirefoxProfile

# create new profile to pass to mozmill/mozrunner
profile = FirefoxProfile(addons=["adblock.xpi"])

Command Line Interface

Creates and/or modifies a Firefox profile. The profile can be modified by passing in addons to install or preferences to set. If no profile is specified, a new profile is created and the path of the resulting profile is printed.

exception mozprofile.cli.KeyValueParseError(msg, errors=())

Error when parsing strings of serialized key-values.

class mozprofile.cli.MozProfileCLI(args=['doc'], add_options=None)

The Command Line Interface for mozprofile.

preferences()

profile preferences

profile(restore=False)

create the profile

profile_args()

arguments to instantiate the profile class

profile_class

alias of mozprofile.profile.Profile

mozprofile.cli.cli(args=['doc'])

Handles the command line arguments for mozprofile via sys.argv

mozprofile.cli.parse_key_value(strings, separator='=', context='key, value')

Parse string-serialized key-value pairs in the form of key = value.

Parameters
  • strings (list) – List of strings to parse.

  • separator (str) – Identifier used to split the strings.

Returns

A list of (<key>, <value>) tuples. Whitespace is not stripped.

Return type

list

Raises

KeyValueParseError

mozprofile.cli.parse_preferences(prefs, context='--setpref=')

Parse preferences specified on the command line.

Parameters

prefs (list) – A list of strings, usually of the form “<pref>=<value>”.

Returns

A dictionary of the form {<pref>: <value>} where values have been

cast.

Return type

dict

The profile to be operated on may be specified with the --profile switch. If a profile is not specified, one will be created in a temporary directory which will be echoed to the terminal:

(mozmill)> mozprofile
/tmp/tmp4q1iEU.mozrunner
(mozmill)> ls /tmp/tmp4q1iEU.mozrunner
user.js

To run mozprofile from the command line enter: mozprofile --help for a list of options.

Permissions

add permissions to the profile

exception mozprofile.permissions.BadPortLocationError(given_port)

Location has invalid port value.

exception mozprofile.permissions.DuplicateLocationError(url)

Same location defined twice.

class mozprofile.permissions.Location(scheme, host, port, options)

Represents a location line in server-locations.txt.

isEqual(location)

compare scheme://host:port, but ignore options

exception mozprofile.permissions.LocationsSyntaxError(lineno, err=None)

Signifies a syntax error on a particular line in server-locations.txt.

exception mozprofile.permissions.MissingPrimaryLocationError

No primary location defined in locations file.

exception mozprofile.permissions.MultiplePrimaryLocationsError

More than one primary location defined.

class mozprofile.permissions.Permissions(profileDir, locations=None)

Allows handling of permissions for mozprofile

clean_db()

Removed permissions added by mozprofile.

network_prefs(proxy=None)

take known locations and generate preferences to handle permissions and proxy returns a tuple of prefs, user_prefs

pac_prefs(user_proxy=None)

return preferences for Proxy Auto Config.

write_db(locations)

write permissions to the sqlite database

class mozprofile.permissions.ServerLocations(filename=None, add_callback=None)

Iterable collection of locations. Use provided functions to add new locations, rather that manipulating _locations directly, in order to check for errors and to ensure the callback is called, if given.

read(filename, check_for_primary=True)

Reads the file and adds all valid locations to the self._locations array.

Parameters
  • filename – in the format of server-locations.txt

  • check_for_primary – if True, a MissingPrimaryLocationError exception is raised if no primary is found

The only exception is that the port, if not defined, defaults to 80 or 443.

FIXME: Shouldn’t this default to the protocol-appropriate port? Is there any reason to have defaults at all?

You can set permissions by creating a ServerLocations object that you pass to the Profile constructor. Hosts can be added to it with add_host(host, port). port can be 0.

Preferences

user preferences

class mozprofile.prefs.Preferences(prefs=None)

assembly of preferences from various sources

add(prefs, cast=False)
Parameters
  • prefs

  • cast – whether to cast strings to value, e.g. ‘1’ -> 1

add_file(path)

a preferences from a file

Parameters

path

classmethod cast(value)

interpolate a preference from a string from the command line or from e.g. an .ini file, there is no good way to denote what type the preference value is, as natively it is a string

  • integers will get cast to integers

  • true/false will get cast to True/False

  • anything enclosed in single quotes will be treated as a string with the ‘’s removed from both sides

classmethod read(path)

read preferences from a file

classmethod read_ini(path, section=None)

read preferences from an .ini file

classmethod read_json(path)

read preferences from a JSON blob

classmethod read_prefs(path, pref_setter='user_pref', interpolation=None)

Read preferences from (e.g.) prefs.js

Parameters
  • path – The path to the preference file to read.

  • pref_setter – The name of the function used to set preferences in the preference file.

  • interpolation – If provided, a dict that will be passed to str.format to interpolate preference values.

classmethod write(_file, prefs, pref_string='user_pref(%s, %s);')

write preferences to a file

exception mozprofile.prefs.PreferencesReadError

read error for prefrences files

Preferences can be set in several ways:

  • using the API: You can make a dictionary with the preferences and pass it to the Profile constructor. You can also add more preferences with the Profile.set_preferences method.

  • using a JSON blob file: mozprofile --preferences myprefs.json

  • using a .ini file: mozprofile --preferences myprefs.ini

  • via the command line: mozprofile --pref key:value --pref key:value [...]

When setting preferences from an .ini file or the --pref switch, the value will be interpolated as an integer or a boolean (true/false) if possible.

Profile

class mozprofile.profile.FirefoxProfile(profile=None, addons=None, preferences=None, locations=None, proxy=None, restore=True, whitelistpaths=None, **kwargs)

Specialized Profile subclass for Firefox

class mozprofile.profile.Profile(profile=None, addons=None, preferences=None, locations=None, proxy=None, restore=True, whitelistpaths=None, **kwargs)

Handles all operations regarding profile.

Creating new profiles, installing add-ons, setting preferences and handling cleanup.

The files associated with the profile will be removed automatically after the object is garbage collected:

profile = Profile()
print profile.profile  # this is the path to the created profile
del profile
# the profile path has been removed from disk

cleanup() is called under the hood to remove the profile files. You can ensure this method is called (even in the case of exception) by using the profile as a context manager:

with Profile() as profile:
    # do things with the profile
    pass
# profile.cleanup() has been called here
clean_preferences()

Removed preferences added by mozrunner.

cleanup()

Cleanup operations for the profile.

pop_preferences(filename)

pop the last set of preferences added returns True if popped

set_persistent_preferences(preferences)

Adds preferences dict to profile preferences and save them during a profile reset

set_preferences(preferences, filename='user.js')

Adds preferences dict to profile preferences

summary(return_parts=False)

returns string summarizing profile information. if return_parts is true, return the (Part_name, value) list of tuples instead of the assembled string

class mozprofile.profile.ThunderbirdProfile(profile=None, addons=None, preferences=None, locations=None, proxy=None, restore=True, whitelistpaths=None, **kwargs)

Specialized Profile subclass for Thunderbird

mozprofile.profile.create_profile(app, **kwargs)

Create a profile given an application name.

Parameters
  • app – String name of the application to create a profile for, e.g ‘firefox’.

  • kwargs – Same as the arguments for the Profile class (optional).

Returns

An application specific Profile instance

Raises

NotImplementedError

Resources

Other Mozilla programs offer additional and overlapping functionality for profiles. There is also substantive documentation on profiles and their management.