-
Notifications
You must be signed in to change notification settings - Fork 1
/
getch.c
103 lines (89 loc) · 1.79 KB
/
getch.c
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
#include <stdio.h>
#if defined(__linux__) || defined(__CYGWIN__)
#include <termios.h>
static struct termios old, new;
static void
initTermios(int echo)
{
tcgetattr(0, &old);
new = old;
new.c_lflag &= ~ICANON;
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
static void
resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
static char
getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
static char
getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
static char
getche(void)
{
return getch_(1);
}
#elif defined(MS_WINDOWS) || defined(_WIN32)
#include <conio.h>
#endif
#if 0
/* Let's test it out */
int
main(void)
{
char c;
printf("(getche example) please type a letter: ");
c = getche();
printf("\nYou typed: %c\n", c);
printf("(getch example) please type a letter...");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}
#endif
#include <Python.h>
static PyObject *
Getch_getch(PyObject *self, PyObject *args)
{
char c = getch();
return Py_BuildValue("c", c);
}
static PyObject *
Getch_getche(PyObject *self, PyObject *args)
{
char c = getche();
return Py_BuildValue("c", c);
}
static PyMethodDef GetchMethods[] = {
{ "getch", Getch_getch, METH_NOARGS, "getch" },
{ "getche", Getch_getche, METH_NOARGS, "getche" },
{ NULL, NULL, 0, NULL }
};
static PyModuleDef getchmodule = {
PyModuleDef_HEAD_INIT,
"_getch",
NULL,
-1,
GetchMethods
};
PyMODINIT_FUNC
PyInit__getch(void)
{
return PyModule_Create(&getchmodule);
}