Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,如何中途停止脚本?_Python_Python 2.7_Windows 7_Interrupt_Pause - Fatal编程技术网

Python,如何中途停止脚本?

Python,如何中途停止脚本?,python,python-2.7,windows-7,interrupt,pause,Python,Python 2.7,Windows 7,Interrupt,Pause,假设我有这个脚本: 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) de

假设我有这个脚本:

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()
导入时间
def菜单():
n=原始输入(“您希望脚本做什么:”).lower()
如果n==“运行”:
r=运行()
elif n==“退出”:
退出()
其他:
打印(“未知命令”)
打印(“结果:+r)
def run():
t=0
当t<60时:
打印(“此脚本正在执行某些操作”)
时间。睡眠(1)
t=t+1
返回“某种结果”
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
打印(“启动有史以来最无用的脚本”)
尽管如此:
菜单()

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

下面的内容如何:

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

你要找的是信号库,你需要做的就是创建一个函数来处理它

import signal

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

signal.signal(signal.SIGINT,a)

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

您的意思是要以交互方式停止它吗?使用Ctrl+C使触发信号中断,也称为
signal.SIGINT