This class manages a list of search paths and helps to find and open application-bound resources (files). :param base: default value for :meth:`add_path` calls. :param opener: callable used to open resources. :param cachemode: controls which lookups are cached. One
| 2642 | |
| 2643 | |
| 2644 | class ResourceManager(object): |
| 2645 | """ This class manages a list of search paths and helps to find and open |
| 2646 | application-bound resources (files). |
| 2647 | |
| 2648 | :param base: default value for :meth:`add_path` calls. |
| 2649 | :param opener: callable used to open resources. |
| 2650 | :param cachemode: controls which lookups are cached. One of 'all', |
| 2651 | 'found' or 'none'. |
| 2652 | """ |
| 2653 | |
| 2654 | def __init__(self, base='./', opener=open, cachemode='all'): |
| 2655 | self.opener = opener |
| 2656 | self.base = base |
| 2657 | self.cachemode = cachemode |
| 2658 | |
| 2659 | #: A list of search paths. See :meth:`add_path` for details. |
| 2660 | self.path = [] |
| 2661 | #: A cache for resolved paths. ``res.cache.clear()`` clears the cache. |
| 2662 | self.cache = {} |
| 2663 | |
| 2664 | def add_path(self, path, base=None, index=None, create=False): |
| 2665 | """ Add a new path to the list of search paths. Return False if the |
| 2666 | path does not exist. |
| 2667 | |
| 2668 | :param path: The new search path. Relative paths are turned into |
| 2669 | an absolute and normalized form. If the path looks like a file |
| 2670 | (not ending in `/`), the filename is stripped off. |
| 2671 | :param base: Path used to absolutize relative search paths. |
| 2672 | Defaults to :attr:`base` which defaults to ``os.getcwd()``. |
| 2673 | :param index: Position within the list of search paths. Defaults |
| 2674 | to last index (appends to the list). |
| 2675 | |
| 2676 | The `base` parameter makes it easy to reference files installed |
| 2677 | along with a python module or package:: |
| 2678 | |
| 2679 | res.add_path('./resources/', __file__) |
| 2680 | """ |
| 2681 | base = os.path.abspath(os.path.dirname(base or self.base)) |
| 2682 | path = os.path.abspath(os.path.join(base, os.path.dirname(path))) |
| 2683 | path += os.sep |
| 2684 | if path in self.path: |
| 2685 | self.path.remove(path) |
| 2686 | if create and not os.path.isdir(path): |
| 2687 | os.makedirs(path) |
| 2688 | if index is None: |
| 2689 | self.path.append(path) |
| 2690 | else: |
| 2691 | self.path.insert(index, path) |
| 2692 | self.cache.clear() |
| 2693 | return os.path.exists(path) |
| 2694 | |
| 2695 | def __iter__(self): |
| 2696 | """ Iterate over all existing files in all registered paths. """ |
| 2697 | search = self.path[:] |
| 2698 | while search: |
| 2699 | path = search.pop() |
| 2700 | if not os.path.isdir(path): continue |
| 2701 | for name in os.listdir(path): |