在R中,有一个on.exit()
函数,它记录了当前函数退出时需要执行的表达式(自然地或由于错误的结果),这是用于重置图形参数或执行其他清理操作。例如:
f <- function(...) {
... # some operations that the function performs
on.exit(...) # operations to perform right before the function exits
}
我想知道是否有任何可以达到类似效果的Python等价物?
编辑:这是我想用Python做的事情:
我一直在编写一个使用pyautogui
模块执行GUI自动化的脚本。
有一个pyautogui.PAUSE
变量控制每个操作(键盘或鼠标)之间的PAUSE,默认值为0.1秒。
我是python的新手,我发现我以前知道的全局/本地范围规则不适用于此变量。当在函数内部更改值时,它会影响函数外部的其他操作的行为。例如:
import pyautogui
print(pyautogui.PAUSE) # default is 0.1 secs
def f():
pyautogui.PAUSE = 0 # simply change the value inside a function
f() # call the function
print(pyautogui.PAUSE) # now becomes 0 sec
所以我想知道如何在函数退出时自然地或由于错误而恢复默认值。
答案 0 :(得分:-1)
您似乎需要atexit 这样的事情可能会有所帮助(链接示例)
def goodbye(name, adjective):
print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
import atexit
atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')