-
Notifications
You must be signed in to change notification settings - Fork 12
/
urbandicli
executable file
·84 lines (66 loc) · 2.2 KB
/
urbandicli
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import sys
import subprocess
import textwrap
import urbandict
def paged_output(string):
pager = os.getenv("PAGER")
if not pager:
# no PAGER set, print stuff as is
print(string)
return
pager_args = []
if pager == 'less':
pager_args += ['-r', '-F', '-X']
p = subprocess.Popen([pager] + pager_args, stdin=subprocess.PIPE)
p.stdin.write(string.encode('utf-8'))
p.stdin.close()
p.wait()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-p', dest='use_pager', action='store_false',
help='do not use PAGER for output')
parser.add_argument('-r', dest='random', action='store_true',
help='pull random definition')
parser.add_argument('term', nargs='?')
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
if args.term:
translations = urbandict.define(term=args.term)
elif args.random:
translations = urbandict.define(term=urbandict.TermTypeRandom())
else:
print("You need to either specifiy term "
"or -r for random definition")
sys.exit(1)
output = []
for index in range(len(translations)):
if output:
output += ['\n']
output += ["%s. %s" % (index + 1, translations[index]['word'])]
output += ['\n'.join(textwrap.wrap(
translations[index]['def'],
initial_indent=' ',
subsequent_indent=' ')
)
]
if translations[index]['example'] != '':
output += [("\n Examples:\n")]
output += [('\n'.join(textwrap.wrap(
translations[index]['example'],
initial_indent=' * ',
subsequent_indent=' ' * 4)
))]
category = translations[index]['category']
if category != 'unknown':
output += ["\n Category: {}".format(category)]
output += ['\n']
output_string = ''.join(output)
if args.use_pager:
paged_output(output_string)
else:
print(output_string)