Python, 如何中途停止脚本?
Python, How to stop a script midway?
假设我有这个脚本:
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()
如何在将 "This script is doing some stuff" 和 return 打印到 Menu() 时停止脚本?我不想完全退出程序,只是 return 到菜单。
关于这方面的事情:
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
必须有两个位置参数
假设我有这个脚本:
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()
如何在将 "This script is doing some stuff" 和 return 打印到 Menu() 时停止脚本?我不想完全退出程序,只是 return 到菜单。
关于这方面的事情:
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
必须有两个位置参数