Made the local file name safe for windows
[pyTivo.git] / Cheetah / Utils / Misc.py
blobaa5cc6dca0c593be2792f3a32b1c9b00101a08f6
1 #!/usr/bin/env python
2 # $Id: Misc.py,v 1.8 2005/11/02 22:26:08 tavis_rudd Exp $
3 """Miscellaneous functions/objects used by Cheetah but also useful standalone.
5 Meta-Data
6 ================================================================================
7 Author: Mike Orr <iron@mso.oz.net>
8 License: This software is released for unlimited distribution under the
9 terms of the MIT license. See the LICENSE file.
10 Version: $Revision: 1.8 $
11 Start Date: 2001/11/07
12 Last Revision Date: $Date: 2005/11/02 22:26:08 $
13 """
14 __author__ = "Mike Orr <iron@mso.oz.net>"
15 __revision__ = "$Revision: 1.8 $"[11:-2]
17 import os # Used in mkdirsWithPyInitFile.
18 import types # Used in useOrRaise.
19 import sys # Used in die.
21 ##################################################
22 ## MISCELLANEOUS FUNCTIONS
24 def die(reason):
25 sys.stderr.write(reason + '\n')
26 sys.exit(1)
28 def useOrRaise(thing, errmsg=''):
29 """Raise 'thing' if it's a subclass of Exception. Otherwise return it.
31 Called by: Cheetah.Servlet.cgiImport()
32 """
33 if type(thing) == types.ClassType and issubclass(thing, Exception):
34 raise thing(errmsg)
35 return thing
38 def checkKeywords(dic, legalKeywords, what='argument'):
39 """Verify no illegal keyword arguments were passed to a function.
41 in : dic, dictionary (**kw in the calling routine).
42 legalKeywords, list of strings, the keywords that are allowed.
43 what, string, suffix for error message (see function source).
44 out: None.
45 exc: TypeError if 'dic' contains a key not in 'legalKeywords'.
46 called by: Cheetah.Template.__init__()
47 """
48 # XXX legalKeywords could be a set when sets get added to Python.
49 for k in dic.keys(): # Can be dic.iterkeys() if Python >= 2.2.
50 if k not in legalKeywords:
51 raise TypeError("'%s' is not a valid %s" % (k, what))
54 def removeFromList(list_, *elements):
55 """Save as list_.remove(each element) but don't raise an error if
56 element is missing. Modifies 'list_' in place! Returns None.
57 """
58 for elm in elements:
59 try:
60 list_.remove(elm)
61 except ValueError:
62 pass
65 def mkdirsWithPyInitFiles(path):
66 """Same as os.makedirs (mkdir 'path' and all missing parent directories)
67 but also puts a Python '__init__.py' file in every directory it
68 creates. Does nothing (without creating an '__init__.py' file) if the
69 directory already exists.
70 """
71 dir, fil = os.path.split(path)
72 if dir and not os.path.exists(dir):
73 mkdirsWithPyInitFiles(dir)
74 if not os.path.exists(path):
75 os.mkdir(path)
76 init = os.path.join(path, "__init__.py")
77 f = open(init, 'w') # Open and close to produce empty file.
78 f.close()
82 # vim: shiftwidth=4 tabstop=4 expandtab