-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathask.py
executable file
·104 lines (84 loc) · 2.75 KB
/
ask.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
asks a yes/no question via audio (text-to-speech).
returncode reflects answer in common unix-style (0 == yes/ok, 1 == nope)
Usage:
ask [<msg>] [--yes=<reply_yes>] [--no=<reply_no>] [--engine=<tts-engine>]
Options:
--engine=<str> TTS-engine to use {'google', 'espeak', 'festival'}
[default: espeak]
--no=<str> Message for negative answer
--yes=<str> Message for positive answer
-h, --help Print this
--version Print version
Examples:
$ ask "Do you want to play a game?" && echo "Splendid! :)"
$ ask "Do you want to play a game?" --yes="Splendid, let's play!" --no="Okidoki. Maybe another time."
"""
import logging
import sys
from docopt import docopt
from say import available_engines, ENGINE_DEFAULT, __version__, say
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler() # console-handler
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
def ask(question,reply_y,reply_n,engine=ENGINE_DEFAULT):
"""
"""
say(msg,engine)
uinp = getch()
logger.debug("answer was : {}".format(uinp))
if uinp in ['y','Y','j','J']:
if reply_y:
say(reply_y,engine)
return 0
else:
if reply_n:
say(reply_n,engine)
return 1
if __name__ == '__main__':
kwargs = docopt(__doc__, version=str('.'.join([str(el) for el in __version__])))
logger.debug("kwargs={}".format(kwargs))
if '<msg>' in kwargs:
msg = kwargs['<msg>']
reply_y = kwargs['--yes']
reply_n = kwargs['--no']
engine = kwargs['--engine']
if not engine in available_engines():
engine=ENGINE_DEFAULT
if not msg:
msg = input("what should i ask? : ".format(msg))
yn_rc = ask(msg,reply_y,reply_n,engine)
sys.exit(yn_rc)