| 1 |
""" |
| 2 |
Miscellaneous functions/objects used by Cheetah but also useful standalone. |
| 3 |
""" |
| 4 |
import os |
| 5 |
import sys |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
def die(reason): |
| 12 |
sys.stderr.write(reason + '\n') |
| 13 |
sys.exit(1) |
| 14 |
|
| 15 |
|
| 16 |
def useOrRaise(thing, errmsg=''): |
| 17 |
"""Raise 'thing' if it's a subclass of Exception. Otherwise return it. |
| 18 |
|
| 19 |
Called by: Cheetah.Servlet.cgiImport() |
| 20 |
""" |
| 21 |
if isinstance(thing, type) and issubclass(thing, Exception): |
| 22 |
raise thing(errmsg) |
| 23 |
return thing |
| 24 |
|
| 25 |
|
| 26 |
def checkKeywords(dic, legalKeywords, what='argument'): |
| 27 |
"""Verify no illegal keyword arguments were passed to a function. |
| 28 |
|
| 29 |
in : dic, dictionary (**kw in the calling routine). |
| 30 |
legalKeywords, list of strings, the keywords that are allowed. |
| 31 |
what, string, suffix for error message (see function source). |
| 32 |
out: None. |
| 33 |
exc: TypeError if 'dic' contains a key not in 'legalKeywords'. |
| 34 |
called by: Cheetah.Template.__init__() |
| 35 |
""" |
| 36 |
|
| 37 |
for k in dic: |
| 38 |
if k not in legalKeywords: |
| 39 |
raise TypeError("'%s' is not a valid %s" % (k, what)) |
| 40 |
|
| 41 |
|
| 42 |
def removeFromList(list_, *elements): |
| 43 |
"""Save as list_.remove(each element) but don't raise an error if |
| 44 |
element is missing. Modifies 'list_' in place! Returns None. |
| 45 |
""" |
| 46 |
for elm in elements: |
| 47 |
try: |
| 48 |
list_.remove(elm) |
| 49 |
except ValueError: |
| 50 |
pass |
| 51 |
|
| 52 |
|
| 53 |
def mkdirsWithPyInitFiles(path): |
| 54 |
"""Same as os.makedirs (mkdir 'path' and all missing parent directories) |
| 55 |
but also puts a Python '__init__.py' file in every directory it |
| 56 |
creates. Does nothing (without creating an '__init__.py' file) if the |
| 57 |
directory already exists. |
| 58 |
""" |
| 59 |
dir, fil = os.path.split(path) |
| 60 |
if dir and not os.path.exists(dir): |
| 61 |
mkdirsWithPyInitFiles(dir) |
| 62 |
if not os.path.exists(path): |
| 63 |
os.mkdir(path) |
| 64 |
init = os.path.join(path, "__init__.py") |
| 65 |
f = open(init, 'w') |
| 66 |
f.close() |
| 67 |
|
| 68 |
|