(Python) Using streams to search for key input using getch

I am trying to write a piece of test code that will continuously print “Running” until a key is pressed. I tried to implement this by creating an additional thread (called thread1) that would listen for a keystroke.

When I run my code, the thread starts up fine and seems to execute correctly until getch.getch () is called. Although getch.getch () expects keystrokes, it seems to stop not only thread1, but also the main thread.

How can I make sure that although thread1 listens for a keystroke, the main thread continues to work?

I am using python 2.7 and getch 1.0 ( https://pypi.python.org/pypi/getch ).

Here is my code:

import threading
import time
import getch

class myThread (threading.Thread):
    def __init__(self, threadID, name, cont):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.cont = cont

    def run(self):
        print "Starting " + self.name +"\n"
        print "waiting 2 seconds"
        time.sleep(2)
        char = getch.getch()
        print 'You pressed %s' % char
        cont.append(1)
        print "Terminating" + self.name

cont = []

thread1 = myThread(1, "Thread1", cont)

thread1.start()

while cont == []:
    print "Running"
    time.sleep(0.5)

He outputs this:

Starting Thread1
Running

waiting 2 seconds
Running
Running
Running

,

+4
1

- GIL. , threading.Thread a multiprocessing.Process:

class myThread (multiprocessing.Process):
    def __init__(self, threadID, name, cont):
        super(myThread, self).__init__()
        #threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.cont = contdef run(self):
        print "Starting " + self.name +"\n"
        char = getch.getch()
        print 'You pressed %s' % char
        cont.append(1)
        print "Terminating" + self.name

cont = []

thread1 = myThread(1, "Thread1", cont)

thread1.start()

while cont == []: 
    print "Running"
    time.sleep(0.5)

:

dan@dantop:~$ ./get.py 
Running
Starting Thread1

Running
Running
Running
Running
Running
Running
Running
Running
You pressed f
TerminatingThread1
Running
Running
Running
Running
Running
Running
Running
Running

getch C- getchar(), GIL. Python , , getchar().

, GIL getch C-extension, Py_BEGIN_THREADS Py_ALLOW_THREADS:

static PyObject *getch_getche(PyObject *self, PyObject *args)
{
    int ok = PyArg_ParseTuple(args, "");
    char c;
    Py_BEGIN_ALLOW_THREADS
    c = getche();
    Py_END_ALLOW_THREADS
    return PyUnicode_FromFormat("%c", c); 
}

static PyObject *getch_getch(PyObject *self, PyObject *args)
{
    int ok = PyArg_ParseTuple(args, "");
    char c;
    Py_BEGIN_ALLOW_THREADS
    c = getch();
    Py_END_ALLOW_THREADS
    return PyUnicode_FromFormat("%c", c); 
}

getchmodule.c , , .

+3

Source: https://habr.com/ru/post/1544382/


All Articles