Python: Difference between revisions

From SoftwareGuy
Jump to navigation Jump to search
Mark (talk | contribs)
Created page with "=== Check for input #1 === <code> import sys, select print "You have ten seconds to answer!" i, o, e = select.select( [sys.stdin], [], [], 10 ) if (i): print "You said", sys.stdin.readline().strip() else: print "You said nothing!" </code> === Check for input #2 === <code> import signal TIMEOUT = 5 # number of seconds your want for timeout def interrupted(signum, frame): "called when read times out" print 'interrupted!' signal.signal(sig..."
 
Mark (talk | contribs)
 
Line 1: Line 1:
=== Check for input #1 ===
=== Check for input #1 ===
<code>
<code>
  import sys, select
  import sys, select
Line 13: Line 12:
   print "You said nothing!"
   print "You said nothing!"
</code>
</code>
=== Check for input #2 ===
=== Check for input #2 ===



Latest revision as of 18:49, 7 April 2024

Check for input #1[edit | edit source]

import sys, select

print "You have ten seconds to answer!"

i, o, e = select.select( [sys.stdin], [], [], 10 )

if (i):
  print "You said", sys.stdin.readline().strip()
else:
  print "You said nothing!"

Check for input #2[edit | edit source]

import signal
TIMEOUT = 5 # number of seconds your want for timeout

def interrupted(signum, frame):
    "called when read times out"
    print 'interrupted!'
signal.signal(signal.SIGALRM, interrupted)

def input():
    try:
            print 'You have 5 seconds to type in your stuff...'
            foo = raw_input()
            return foo
    except:
            # timeout
            return

# set alarm
signal.alarm(TIMEOUT)
s = input()
# disable the alarm after success
signal.alarm(0)
print 'You typed', s