Python,如何中途停止脚本?

2024-04-18 03:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个脚本:

import time

def menu():
    n = raw_input("What do you want the script to do: ").lower()
    if n == "run":
        r = run()
    elif n == "exit":
        exit()
    else:
        print("Unknown command")
    print("Result: " + r)    

def run():
    t = 0
    while t < 60:
        print("This script is doing some stuff")
        time.sleep(1)
        t = t + 1
    return "Some kind of result"

if __name__ == '__main__':
    print("Starting the most useless script ever")
    while True:
        menu()

如何在打印时停止脚本“此脚本正在执行某些操作”并返回Menu()?我不想完全退出程序,只想回到菜单。在


Tags: therunimport脚本inputrawiftime
2条回答

你要做的就是创建一个函数库。在

import signal

def a(sig_num, stack_frame):
    print("WORKS")

signal.signal(signal.SIGINT,a)

函数a必须有两个位置参数

关于这件事呢:

while True:
    try:
        # whatever logic
        pass 
    except(KeyboardInterrupt):
        print 'Ctrl-C was pressed... interupt while loop.'
        break
print 'program still running'

相关问题 更多 >