views:

52

answers:

1

Hey,

I'm running a function which evaluates commands passed in using stdin and another function which runs a bunch of jobs. I need to make the latter function sleep at regular intervals but that seems to be blocking the stdin. Any advice on how to resolve this would be appreciated.

The source code for the functions is

def runJobs(comps, jobQueue, numRunning, limit, lock):
  while len(jobQueue) >= 0:
      print(len(jobQueue));
      if len(jobQueue) > 0:
          comp, tasks = find_computer(comps, 0);
            #do something
        time.sleep(5);

def manageStdin():
    print "Global Stdin Begins Now"
    for line in fileinput.input():
        try:
            print(eval(line));
        except Exception, e:
            print e;

--Thanks

+1  A: 

Use a single thread:

import time
import select
import logging
import sys

def stdinWait(interval):
    start = time.time()
    while True:
        time_left = interval - (time.time() - start)
        if time_left <= 0:
            break
        r, w, x = select.select([sys.stdin], [], [], time_left)
        if r:
            line = r[0].readline()
            try:
                print(eval(line));
            except Exception, e:
                logging.exception(e)

def runJobs(comps, jobQueue, numRunning, limit, lock):
  while len(jobQueue) >= 0:
      print(len(jobQueue));
      if len(jobQueue) > 0:
          comp, tasks = find_computer(comps, 0);
          #do something
          stdinWait(5) # wait 5 seconds while watching stdin
nosklo
What would happen if the input to stdin took more than 5 seconds to type?
Sid
@Sid: `select` call would time out and it would work just fine.
nosklo
@nosklo: But then how would I be ever able to enter something into the stdin if it took longer than 5 seconds to type since it would time out before I had a chance to finish typing the input.
Sid
@Sid: You can still type, stuff will be the in the stdin buffer and will be read on the next 5 seconds time.
nosklo
@nosklo: Thanks for the reply. I've one more question - If one of the methods, say "find_computer" are compute-intensive, wouldn't that mean that the stdin may not be available for a long time though?
Sid
if the method is compute-intensive you shoud either 1) divide it in smaller methods and process stdin in-between or 2) defer to another process to use multiple CPUs/cores. Using the same process to deal with both compute-intensive methods and IO is something you want to avoid.
nosklo