简体   繁体   中英

End a python script after a certain amount of time

I am trying to make a simple python game to train my skills,it's something like a dungeon with traps and things like that here's a part of the game code:

from sys import exit

def trap():
    print "You've fallen into a trap,you have 10 seconds to type the word \"Get me out\""

    user_input = raw_input("> ")

    right_choice = "Get me out"

    if *SOME CODE*:
        *MORE CODE*
    else:
        die("you died,you were too slow")

def die(why):
    print why , "Try again"
    exit(0)

as u can see i want to end the python script after 10 seconds if the user_input wasn't equal to right_choice by replacing SOME CODE , MORE CODE in the code example above,how to do that?

What your looking to accomplish can be done with signals: https://stackoverflow.com/a/2282656/2896976

Unfortunately there isn't really a friendly way to handle this. Normally for a game you would call this every frame, but a call like raw_input is what's known as blocking. That is, the program can't do anything until it finishes (but if the user never says anything it won't finish).

Try this. It uses signal to send a signal back within 10 seconds from the print statement. If you want it to be after the first input, move the signal calls.

import signal
from sys import exit

def trap():
    print "You've fallen into a trap,you have 10 seconds to type the word \"Get me out\""
    signal.signal(signal.SIGALRM, die)
    signal.alarm(10)

    user_input = raw_input("> ")
    right_choice = "Get me out"

    if *SOME CODE*:
        *MORE CODE*
        signal.alarm(0)

def die(signum, frame):
    print "Try again"
    signal.alarm(0)
    exit(0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM