]>
Commit | Line | Data |
---|---|---|
1 | """ | |
2 | Internal utility functions. | |
3 | ||
4 | `htmlentitydecode` came from here: | |
5 | http://wiki.python.org/moin/EscapingHtml | |
6 | """ | |
7 | ||
8 | from __future__ import print_function | |
9 | ||
10 | import re | |
11 | import sys | |
12 | import time | |
13 | ||
14 | try: | |
15 | from html.entities import name2codepoint | |
16 | unichr = chr | |
17 | except ImportError: | |
18 | from htmlentitydefs import name2codepoint | |
19 | ||
20 | def htmlentitydecode(s): | |
21 | return re.sub( | |
22 | '&(%s);' % '|'.join(name2codepoint), | |
23 | lambda m: unichr(name2codepoint[m.group(1)]), s) | |
24 | ||
25 | def smrt_input(globals_, locals_, ps1=">>> ", ps2="... "): | |
26 | inputs = [] | |
27 | while True: | |
28 | if inputs: | |
29 | prompt = ps2 | |
30 | else: | |
31 | prompt = ps1 | |
32 | inputs.append(input(prompt)) | |
33 | try: | |
34 | ret = eval('\n'.join(inputs), globals_, locals_) | |
35 | if ret: | |
36 | print(str(ret)) | |
37 | return | |
38 | except SyntaxError: | |
39 | pass | |
40 | ||
41 | def printNicely(string): | |
42 | if hasattr(sys.stdout, 'buffer'): | |
43 | sys.stdout.buffer.write(string.encode('utf8')) | |
44 | print() | |
45 | else: | |
46 | print(string.encode('utf8')) | |
47 | ||
48 | __all__ = ["htmlentitydecode", "smrt_input"] | |
49 | ||
50 | def err(msg=""): | |
51 | print(msg, file=sys.stderr) | |
52 | ||
53 | class Fail(object): | |
54 | """A class to count fails during a repetitive task. | |
55 | ||
56 | Args: | |
57 | maximum: An integer for the maximum of fails to allow. | |
58 | exit: An integer for the exit code when maximum of fail is reached. | |
59 | ||
60 | Methods: | |
61 | count: Count a fail, exit when maximum of fails is reached. | |
62 | wait: Same as count but also sleep for a given time in seconds. | |
63 | """ | |
64 | def __init__(self, maximum=10, exit=1): | |
65 | self.i = maximum | |
66 | self.exit = exit | |
67 | ||
68 | def count(self): | |
69 | self.i -= 1 | |
70 | if self.i == 0: | |
71 | err("Too many consecutive fails, exiting.") | |
72 | raise SystemExit(self.exit) | |
73 | ||
74 | def wait(self, delay=0): | |
75 | self.count() | |
76 | if delay > 0: | |
77 | time.sleep(delay) |