You should be used to installing new modules using pip. You have probably used a requirements.txt file to install multiple modules together with the command.
pip install -r requirements.txt
But what about if you need more flexibility. Why would you ever need more flexibility? If you look at my introduction to YAML post, the code supports either the yaml or ruamel.yaml module. There is no way to add conditional logic to a requirements.txt file so a different strategy is needed.
pip is just a module so it can be imported like any other module. This not only gives you access to the main method, which takes an argument list just as if you were calling pip from the command line, but also to its various methods and classes. One of these is the WorkingSet class which creates a collection of the installed modules (or active distributions as the documentation calls them). Using this we can create the conditional logic needed to ensure one of the yaml modules is installed as below.
import pip package_names = [ ws.project_name for ws in pip._vendor.pkg_resources.WorkingSet() ] if ('yaml' not in package_names) and ('ruamel.yaml' not in package_names): pip.main(['install','ruamel.yaml'])
WorkingSet returns a few other useful properties and methods apart from the package_name. The location property returns the path to where the module is installed and the version property naturally returns the version installed. The requires method returns a list of dependencies.
As with most modules, if you’re interested in finding out more dig around in the source code.