简体   繁体   English

一定时间后结束python脚本

[英]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: 我正在尝试制作一个简单的Python游戏来训练我的技能,这就像是带有陷阱的地牢,而这是游戏代码的一部分:

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? 如您所见,如果通过替换上面代码示例中的SOME CODEMORE CODE ,如果user_input不等于right_choice,我想在10秒后结束python脚本,该怎么做?

What your looking to accomplish can be done with signals: https://stackoverflow.com/a/2282656/2896976 您希望通过信号完成的目标: 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. 通常,对于游戏,您会在每一帧都调用它,但是像raw_input这样的调用就是所谓的阻塞。 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. 它使用signal在打印语句后的10秒钟内将signal发送回去。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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