1 import os
2
3 def basic_preloader(master, package=None, version=None, exact=False,
4 env_var=None):
5 """A basic preloader that adds a custom path to the list of
6 directories that Tcl uses when attempting to resolve packages with
7 the package command.
8
9 The custom path is taken from the environment variable specified in
10 env_var, the other parameters received (package, version and exact)
11 are never used here.
12 """
13 dep_path = os.environ.get(env_var)
14 if dep_path:
15 master.tk.eval(
16 'global auto_path; '
17 'lappend auto_path {%s}' % dep_path)
18
19
20 class DependenceLoader(dict):
21
22 def remove(self, package):
23 """Remove package so it will no longer be loaded when a Tcl
24 interpreter is created."""
25 del self[package]
26
27
28 def add(self, package, preloader=None, version=None, exact=False,
29 **kwargs):
30 """Indicate that package, replac must be loaded after the Tcl interpreter
31 is created. Adding the same package twice replaces the older.
32
33 If preloader is specified it must be callable and should expect
34 to be invoked with a Tkinter.Tk instance, package, version, exact,
35 and any extra kwargs passed.
36
37 If version is specified, and exact is True, then only the specific
38 package version will be accepted. Defining only version allows
39 Tcl to load newer versions of the package as long as the major
40 number is the same. If neither version nor exact are given then
41 any version of the package is acceptable for loading.
42 Remember to use a string when specifying version, like '1.2.3'.
43 """
44 if preloader is not None and not hasattr(preloader, '__call__'):
45 raise TypeError('loader must be callable')
46
47 self[package] = {
48 'preloader': preloader, 'preloader_kw': kwargs,
49 'version': version,
50 'exact': exact}
51
52
53 def load_now(self, master):
54 """Load all the added packages."""
55 for pkg, opts in self.iteritems():
56 version, exact = opts['version'], opts['exact']
57
58 if opts['preloader'] is not None:
59 opts['preloader'](
60 master, pkg, version, exact, **opts['preloader_kw'])
61
62 args = ()
63 if exact:
64 args += ('-exact', )
65 args += (pkg, version)
66
67
68 master.tk.call('package', 'require', *args)
69
70
71 dependences = DependenceLoader()
72