Issue
I want to programmatically install and import packages based on a list of package names. For most packages, this is no problem since the package and module names are the same.
However, the PyYAML package is one exception since its module is called simply yaml and there are probably more exceptions.
Here is the python function I use to install and import the packages/modules:
def install_and_import(package):
import importlib
try:
importlib.import_module(package) #needs module name!
except ImportError:
import pip
pip.main(['install', package]) #needs package name
finally:
globals()[package] = importlib.import_module(package)
Calling the function for each package in this list, ['backoff', 'pyyaml'] (parsed from requirements.txt), I get:
Collecting backoff
Installing collected packages: backoff
Successfully installed backoff-1.4.3
Collecting pyyaml
Installing collected packages: pyyaml
Successfully installed pyyaml-3.12
[...Trackback...]
ModuleNotFoundError: No module named 'pyyaml'
Is there a way, given just the package name (e.g., pyyaml), to find out the name of the module I actually need to import (e.g., yaml)?
Solution
Using distlib (pip install distlib) and a hacky "guess" at module names (this can be improved, but wanted to give you what I came up with before I have to get back to other things!)
import os.path
import sys
import distlib.database
def to_module(s):
parts = os.path.splitext(s)[0].split(os.sep)
if s.endswith('.py'):
if parts[-1] == '__init__':
parts.pop()
elif s.endswith('.so'):
parts[-1], _, _ = parts[-1].partition('.')
return '.'.join(parts)
def main():
dp = distlib.database.DistributionPath()
dist = dp.get_distribution(sys.argv[1])
for f, _, _ in dist.list_installed_files():
if f.endswith(('.py', '.so')):
print(to_module(f))
if __name__ == '__main__':
exit(main())
to_module is pretty self explanatory, I use the DistributionPath() (a representation of "installed" modules) to query for a specific package that's installed. From that I list the files and if they look like modules converts them into modules. Note that this won't catch things like six (which add a six.moves module dynamically), but it's a pretty good first-order approximation.
I'm also making assumptions about posix here, for other platforms you'll want to adjust (such as windows which'll use .pyd I believe).
Sample output:
$ python test.py pyyaml
_yaml
yaml
yaml.composer
yaml.constructor
yaml.cyaml
yaml.dumper
yaml.emitter
yaml.error
yaml.events
yaml.loader
yaml.nodes
yaml.parser
yaml.reader
yaml.representer
yaml.resolver
yaml.scanner
yaml.serializer
yaml.tokens
$ python test.py coverage
coverage.pickle2json
coverage.execfile
coverage.python
coverage.summary
coverage.html
coverage.plugin
coverage.pytracer
coverage.config
coverage.__main__
coverage.data
coverage.debug
coverage.annotate
coverage.backward
coverage.parser
coverage.misc
coverage.files
coverage.multiproc
coverage.backunittest
coverage.env
coverage
coverage.control
coverage.cmdline
coverage.results
coverage.version
coverage.plugin_support
coverage.templite
coverage.collector
coverage.xmlreport
coverage.report
coverage.phystokens
coverage.bytecode
coverage.tracer
coverage.fullcoverage.encodings
Answered By - Anthony Sottile Answer Checked By - Terry (Python.Easybugfix Volunteer)
Post a Comment
Post a Comment