Документ взят из кэша поисковой машины. Адрес оригинального документа : http://kodomo.fbb.msu.ru/hg/allpy/file/bc1a7595d9d1/allpy/util.py
Дата изменения: Unknown
Дата индексирования: Sun Feb 3 20:41:20 2013
Кодировка:
allpy: bc1a7595d9d1 allpy/util.py

allpy

view allpy/util.py @ 1107:bc1a7595d9d1

Clean rewrite or markup_to_file.py util; --markup is now optional and allows specifying multiple markups as a comma-separated list
author Daniil Alexeyevsky <dendik@kodomo.fbb.msu.ru>
date Thu, 14 Jun 2012 19:05:28 +0400
parents c1091715f8a3
children 0736e1bbd186
line source
1 """Miscellanous utilities.
2 """
3 import sys
4 import warnings
5 import os
6 import inspect
7 import functools
8 from tempfile import mkstemp
9 from StringIO import StringIO
11 def unzip(seq):
12 """The oppozite of zip() builtin."""
13 a, b = [], []
14 for x, y in seq:
15 a.append(x)
16 b.append(y)
17 return a, b
19 def open(filename, mode='r'):
20 """Open file. Return stdin/stdout for filename '-'."""
21 if filename == '-':
22 if 'w' in mode or 'a' in mode or '+' in mode:
23 return sys.stdout
24 if 'r' in mode:
25 return sys.stdin
26 raise AssertionError("Unknown file mode: %s" % mode)
27 else:
28 return file(filename, mode)
30 def remove_each(string, substrings):
31 """Remove each of substrings from string."""
32 for sub in substrings:
33 string = string.replace(sub, "")
34 return string
36 class UserDict(dict):
37 """Clone of dict that user may add attributes to."""
38 pass
40 class UserList(list):
41 """Clone of list that user may add attributes to."""
42 pass
44 class UserString(str):
45 """Clone of str that user may add attributes to."""
46 pass
48 def deprecated(message=None, what=None, in_favor=None, removed_in=None):
49 """Warn about function being deprecated."""
50 if not message:
51 if what is None:
52 frame = inspect.currentframe().f_back
53 caller = []
54 if inspect.getmodule(frame):
55 caller.append(inspect.getmodule(frame).__name__)
56 if 'self' in frame.f_locals:
57 caller.append(frame.f_locals['self'].__class__.__name__)
58 elif 'cls' in frame.f_locals:
59 caller.append(frame.f_locals['cls'].__name__)
60 caller.append(frame.f_code.co_name)
61 what = ".".join(caller) + "(...)"
62 message = "{0} is deprecated".format(what)
63 if in_favor:
64 message = "{0} in favor of {1}".format(message, in_favor)
65 if removed_in:
66 message = "{0}; will be removed in allpy version {1}".format(message, removed_in)
67 warnings.warn(message, DeprecationWarning, stacklevel=2)
69 def Deprecated(message=None, in_favor=None, removed_in=None):
70 def decorator(function):
71 @functools.wraps(function)
72 def decorated(*args, **kws):
73 text = "{0} is deprecated".format(function)
74 if in_favor:
75 text = "{0} in favor of {1}".format(text, in_favor)
76 if removed_in:
77 text = "{0}\n\nWill be removed in allpy version {1}.".format(text, removed_in)
78 if message:
79 text = "{0}\n\n{1}".format(text, message)
80 warnings.warn(text, DeprecationWarning, stacklevel=2)
81 return function(*args, **kws)
82 return decorated
83 return decorator
85 class Silence(object):
86 """Context manager for use with `with`.
88 Run code in context without any message to the screen, but show all output
89 that was there if an error occured. E.g.::
91 with Silence():
92 structure = PDBParser().get_structure(name, file)
94 There are two mutually exclusive ways of silencing:
96 1. By replacing OS'es stdout/stderr with tempfile (called `dup`)
97 2. By replacing python's sys.stdout/sys.stderr with StringIO (`hide`)
99 For each of ways you may specify values: 'stdout', 'stderr' or 'both'.
100 E.g::
102 with Silence(dup="both"):
103 check_call(["mucle", alignment])
105 `Silence()` is equivalent to `Silence(hide='stderr')`
106 """
108 def __init__(self, hide=None, dup=None):
109 if dup is None and hide is None:
110 hide = "stderr"
111 assert not (dup is not None and hide is not None)
112 self.stderr = self.stdout = self.dup_stderr = self.dup_stdout = False
113 if dup == "stdout" or dup == "both":
114 self.dup_stdout = True
115 if dup == "stderr" or dup == "both":
116 self.dup_stderr = True
117 if hide == "stdout" or hide == "both":
118 self.stdout = True
119 if hide == "stderr" or hide == "both":
120 self.stderr = True
122 def __enter__(self):
123 assert not (self.stderr and self.dup_stderr)
124 assert not (self.stdout and self.dup_stdout)
125 if self.dup_stdout or self.dup_stderr:
126 fd, name = mkstemp(prefix="allpy-silent-")
127 self.captured_dup = os.fdopen(fd)
128 self.captured_dup_name = name
129 if self.dup_stdout:
130 self.dup_stdout = os.dup(sys.stdout.fileno())
131 os.dup2(self.captured_dup.fileno(), sys.stdout.fileno())
132 if self.dup_stderr:
133 self.dup_stderr = os.dup(sys.stderr.fileno())
134 os.dup2(self.captured_dup.fileno(), sys.stderr.fileno())
135 if self.stdout or self.stderr:
136 self.captured_output = StringIO()
137 if self.stdout:
138 self.stdout, sys.stdout = sys.stdout, self.captured_output
139 if self.stderr:
140 self.stderr, sys.stderr = sys.stderr, self.captured_output
142 def __exit__(self, exc_type, exc_value, traceback):
143 if self.stdout or self.stderr:
144 if self.stdout:
145 sys.stdout = self.stdout
146 if self.stderr:
147 sys.stderr = self.stderr
148 if exc_type is not None:
149 sys.stderr.write(self.captured_output.getvalue())
150 if self.dup_stdout or self.dup_stderr:
151 if self.dup_stdout:
152 os.dup2(self.dup_stdout, sys.stdout.fileno())
153 os.close(self.dup_stdout)
154 if self.dup_stderr:
155 os.dup2(self.dup_stderr, sys.stderr.fileno())
156 os.close(self.dup_stderr)
157 if exc_type is not None:
158 self.captured_dup.seek(0)
159 sys.stderr.write(self.captured_dup.read())
160 os.unlink(self.captured_dup_name)
162 # vim: set et ts=4 sts=4 sw=4: