In R, there's an on.exit()
function that records the expression given as its argument as needing to be executed when the current function exits (either naturally or as the result of an error), which is useful for resetting graphical parameters or performing other cleanup actions. For example:
f <- function(...) {
... # some operations that the function performs
on.exit(...) # operations to perform right before the function exits
}
I wonder if there's any Python equivalents that can achieve similar effects?
Edit: here's what I wanted to do in Python:
I have been writing a script that performs GUI automation using the pyautogui
module.
There's a pyautogui.PAUSE
variable that controls the PAUSE between each operation(keyboard or mouse), and the default is 0.1 seconds.
I am new to python and I found that the global/local scoping rules that I used to know do not apply to this variable. When the value is changed inside a function, it affects the behaviors of other operations outside the function. For example:
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
So I would like to know how to restore the default value when the function exits(either naturally or as the result of an error).
It looks like you need atexit something like this could help (example from link)
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.