| 1 |
|
|---|
| 2 |
|
|---|
| 3 |
"""Miscellaneous functions/objects used by Cheetah but also useful standalone. |
|---|
| 4 |
|
|---|
| 5 |
|
|---|
| 6 |
|
|---|
| 7 |
|
|---|
| 8 |
|
|---|
| 9 |
|
|---|
| 10 |
|
|---|
| 11 |
|
|---|
| 12 |
|
|---|
| 13 |
|
|---|
| 14 |
__author__ = "Mike Orr <iron@mso.oz.net>" |
|---|
| 15 |
__revision__ = "$Revision: 1.8 $"[11:-2] |
|---|
| 16 |
|
|---|
| 17 |
import os |
|---|
| 18 |
import types |
|---|
| 19 |
import sys |
|---|
| 20 |
|
|---|
| 21 |
|
|---|
| 22 |
|
|---|
| 23 |
|
|---|
| 24 |
def die(reason): |
|---|
| 25 |
sys.stderr.write(reason + '\n') |
|---|
| 26 |
sys.exit(1) |
|---|
| 27 |
|
|---|
| 28 |
def useOrRaise(thing, errmsg=''): |
|---|
| 29 |
"""Raise 'thing' if it's a subclass of Exception. Otherwise return it. |
|---|
| 30 |
|
|---|
| 31 |
Called by: Cheetah.Servlet.cgiImport() |
|---|
| 32 |
""" |
|---|
| 33 |
if type(thing) == types.ClassType and issubclass(thing, Exception): |
|---|
| 34 |
raise thing(errmsg) |
|---|
| 35 |
return thing |
|---|
| 36 |
|
|---|
| 37 |
|
|---|
| 38 |
def checkKeywords(dic, legalKeywords, what='argument'): |
|---|
| 39 |
"""Verify no illegal keyword arguments were passed to a function. |
|---|
| 40 |
|
|---|
| 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 |
|
|---|
| 49 |
for k in dic.keys(): |
|---|
| 50 |
if k not in legalKeywords: |
|---|
| 51 |
raise TypeError("'%s' is not a valid %s" % (k, what)) |
|---|
| 52 |
|
|---|
| 53 |
|
|---|
| 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 |
|---|
| 63 |
|
|---|
| 64 |
|
|---|
| 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') |
|---|
| 78 |
f.close() |
|---|
| 79 |
|
|---|
| 80 |
|
|---|
| 81 |
|
|---|
| 82 |
|
|---|
| 83 |
|
|---|