在Linux

时间:2016-08-22 17:13:17

标签: python linux python-2.7

我正在尝试增加一个循环并打印一个值。当它正在运行时,我想按一个键(例如空格或移位)并打印出按键被按下的键。以下是我想要的示例代码。

def space():
    print 'You pressed space'    

def shift():
    print 'You pressed shift'

x = 0
while True:    
    print(x)
    #if space is pressed
    space()
    #if shift is pressed    
    shift()
    x = x + 1;
    time.sleep(1)

编辑:这是一个示例输出

0
1
2
You pressed shift
3
4
5
You pressed space
6
7
.
.
.

2 个答案:

答案 0 :(得分:1)

我可以在这里帮助您修改答案表格:

https://stackoverflow.com/questions/11918999/key-listeners-in-python

仅限空格并输入:

import contextlib
import sys
import termios
import time


@contextlib.contextmanager
def raw_mode(file):
    old_attrs = termios.tcgetattr(file.fileno())
    new_attrs = old_attrs[:]
    new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
    try:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
        yield
    finally:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)


def space(ch):
    if ord(ch) == 32:
        print 'You pressed space'

def enter(ch):
    if ord(ch) == 10:
        print 'You pressed enter'


def main():
    print 'exit with ^C or ^D'
    with raw_mode(sys.stdin):
        try:
            x = 0
            while True:
                print(x)
                ch = sys.stdin.read(1)
                space(ch)
                enter(ch)
                x = x + 1;
                time.sleep(1)
        except (KeyboardInterrupt, EOFError):
            pass

if __name__ == '__main__':
    main()

答案 1 :(得分:-1)

如果你在Windows上,请查看msvcrt

if(spSemester.getSelectedItemPosition() == 1)
{

    ArrayAdapter<String> adapter4 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,items4);
    spSubject.setAdapter(adapter4);

 }
 else{

    ArrayAdapter<String> adapter4 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,items5);
                spSubject.setAdapter(adapter4);

}