zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Python-自定义函数,手动Ctrl+c中断程序(可用于循环比如录音)

2023-04-18 14:13:39 时间

//以下代码片段星号显示不出来
def make_pizza(toppings): #形参名toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装在内
print(toppings,type(toppings))
make_pizza(‘a’)
make_pizza(‘b’,‘c’,‘d’)

def build_profile(first,last,user_info):#形参user_info中的两个星号让Python创建一个名为user_info的空字典
profile={}
profile[‘first_name’]=first
profile[‘last_name’]= last
for key,value in user_info.items():
profile[key]=value
return profile
user_profile=build_profile(‘albert’, ‘einstein’,location=‘princeton’,field=‘physics’)
print(user_profile)

import sys
a=r"D:Notepad++ otepadPython_批量查找替换文档"
sys.path.append(a) #对于模块和自己写的脚本不在同一个目录下,在脚本开头加sys.path.append(‘xxx’)
from file_chuli import replace_txt

#给形参指定默认值时,等号两边不要有空格:
def function_name (parameter_0 , parameter_1=‘default value’):
#对于函数调用中的关键字实参,也应遵循这种约定:
function_name (value_0 , parameter_1=‘value’)

函数内的参数如果需要在其他地方使用除了函数之间传参外也可以在函数内使用global声明全局变量

中断程序
命令行程序运行期间,如果用户想终止程序,一般都会采用Ctrl-C快捷键,这个快捷键会引发python程序抛出KeyboardInterrupt异常。
我们可以捕获这个异常,在用户按下Ctrl-C的时候,进行一些清理工作。
从python自带的异常对象来看,与退出程序有关的异常,都继承自BaseException。KeyboardInterrupt异常也在其中。
因此,我们要捕获这个异常,就要以如下方式写python代码:

try:
# many code here
except BaseException as e:
if isinstance(e, KeyboardInterrupt):
# ctrl-c goes here
这段代码在except中使用isinstance函数来判断具体是哪一个异常发生了,这种写法可以区分具体的异常,进而分别处理。
或者,直接在except语句中对接KeyboardInterrupt异常:

try:
# many code here
except KeyboardInterrupt as e:
# do something