Impmaster
Impmaster

Reputation: 187

How can I build a counter in python?

I want to have it so that each time I hit the space bar, the number in the terminal increases by one, so that I can keep a number in my head and not forget it. However, if I use raw_input for this, I have to hit enter each time, which is annoying. How can I make it so that I build a counter that increases a variable by one each time the space bar is pressed?

Here is what I have.

x=0

while x<10000000:
    press = raw_input()
    if  press == "z":
        x=x+1
        print x

Upvotes: 1

Views: 3882

Answers (3)

lanco
lanco

Reputation: 1

import os

while True:
    cmd = "read -n 1 c; print $c"
    key = os.popen(cmd).read()
    if key[0] == "z":
        x=x+1
        print x

Upvotes: 0

Anthon
Anthon

Reputation: 76598

If you are using Linux/Unix, there is the curses module.

import curses

def check_press(scr):
    c = None
    x = 0
    while c != 120: # exit on x
        c = scr.getch()
        if c == 122: # count on 'z'
            x += 1
            scr.addstr(0, 0, "%5d" % x)
            scr.refresh()

if __name__ == '__main__':
    curses.wrapper(check_press)

Upvotes: 0

gustavo scharf
gustavo scharf

Reputation: 31

If you're using Windows, there's the msvcrt module. So,

import msvcrt

while x = True:
    keypress = msvcrt.getch()
    if keypress == "z":
        x=x+1
        print x

Upvotes: 3

Related Questions