0

I use the following python code so that the program is constantly checking for a single key press (it's akin to a nonblocking getch() routine for unix platforms). When an appropriate key is pressed, let's say the 'p' key, I want the loop to pause. I try to achieve this by using a raw_input command to pause the loop once the 'p' key is registered. However, the loop appears to go on without pausing, even though the raw_input command is there. I verified this by adding a counter that prints the elapsed time to the screen every second - when the loop is resumed, the counter jumps forward in duration equal to that of the pause duration, instead of leaving where it left off prior to the pause. I'm not sure what I'm doing wrong... any help is much appreciated.

import termios, fcntl, sys, os

import sys

import select

import time

starttime=time.time()

counter=1

pauseflag=0;

while True:

    if time.time()-starttime>=counter:
        print"Seconds elapsed:", counter
        counter=counter+1

    try:
        fd = sys.stdin.fileno()
        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)
        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

        pausekey = sys.stdin.read(1)

        if pausekey=='p':
            print"Loop paused" 
            pauseflag=1   


    except IOError: pass

    finally: 
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) 

    if pauseflag==1:
        raw_input("Press ENTER to resume loop.") #pause program indefinitely until user hits enter key
        pauseflag=0;
Simon Streicher
  • 2,638
  • 1
  • 26
  • 30
MBL
  • 1
  • Take a look at a similar question of mine, the answer seems to contain exactly what you want: http://stackoverflow.com/a/26697759/1490584 – Simon Streicher Nov 02 '14 at 20:58

1 Answers1

0

This requires multiprocessing or threading as you are doing two things at the same time: 1. the loop, 2. the input and setting the flag (and you also have to code a way to communicate between the two processes like a multiprocessing manager dictionary http://pymotw.com/2/multiprocessing/communication.html)

Your code does nothing else until the while loop has finished, I think, but can not tell because the indentation is incorrect.