This recipe creates a class to allow access to variables stored in pkg-config files ( or '.pc' files ). This is usefull in conjunction with distutils to get correct information for compiling external C/C++ modules. Variable substitution is performed with string.Template.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42  | import os
from string import Template
class pkgconfig(dict):
  _paths = ['/usr/lib/pkgconfig', '/usr/local/lib/pkgconfig']
  def __init__(self, package):
    self._load(package)
  def _load(self, package):
    for path in self._paths:
      fn = os.path.join(path, '%s.pc' % package)
      if os.path.exists(fn):
        self._parse(fn)
  def _parse(self, filename):
    lines = open(filename).readlines()
    lokals = {}
    for line in lines:
      line = line.strip()
      if not line:
        continue
      elif ':' in line: # exported variable
        name, val = line.split(':')
        val = val.strip()
        if '$' in val:
          try:
            val = Template(val).substitute(lokals)
          except ValueError:
            raise ValueError("Error in variable substitution!")
        self[name] = val
      elif '=' in line: # local variable
        name, val = line.split('=')
        if '$' in val:
          try:
            val = Template(val).substitute(lokals)
          except ValueError:
            raise ValueError("Error in variable substitution!")
        lokals[name] = val
 | 
The pkg-config command can provide both compiler and linker arguments given the name of a library. This class reads pkg-config files exposing the information to Python. It is usefull in conjunction with distutils when building external C/C++ libraries.
I have subclassed a dict as the information held is simple key/val strings. Variables in pkg-config are stored like '${myvar}' which just so happens to be what string.Template uses :)
I do not know about pkg-config paths on Win32 systems but it should be simple enough to add any extra required paths.
Download
Copy to clipboard