]> jfr.im git - z_archive/twitter.git/blame - twitter/util.py
twitter-archiver and twitter-follow initial import
[z_archive/twitter.git] / twitter / util.py
CommitLineData
8ad2cf0b 1"""
2Internal utility functions.
3
4`htmlentitydecode` came from here:
5 http://wiki.python.org/moin/EscapingHtml
6"""
7
a7282452 8from __future__ import print_function
8ad2cf0b 9
10import re
098660ce 11import sys
a7282452
S
12import time
13
3930cc7b
MV
14try:
15 from html.entities import name2codepoint
d9e92207 16 unichr = chr
3930cc7b
MV
17except ImportError:
18 from htmlentitydefs import name2codepoint
8ad2cf0b 19
20def htmlentitydecode(s):
21 return re.sub(
a5e40197 22 '&(%s);' % '|'.join(name2codepoint),
1bb6d474 23 lambda m: unichr(name2codepoint[m.group(1)]), s)
8ad2cf0b 24
a5e40197
MV
25def smrt_input(globals_, locals_, ps1=">>> ", ps2="... "):
26 inputs = []
27 while True:
28 if inputs:
29 prompt = ps2
30 else:
31 prompt = ps1
7bfe7d97 32 inputs.append(input(prompt))
a5e40197
MV
33 try:
34 ret = eval('\n'.join(inputs), globals_, locals_)
35 if ret:
30e61103 36 print(str(ret))
a5e40197
MV
37 return
38 except SyntaxError:
39 pass
40
098660ce
MV
41def 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
a5e40197 48__all__ = ["htmlentitydecode", "smrt_input"]
a7282452
S
49
50def err(msg=""):
51 print(msg, file=sys.stderr)
52
53class 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)