A: preparation of function (the time function performed by time.sleep (n) analog)
Two: write a decorator, as a function of time together with statistical functions
import time def timmer(func): def wrapper(*args,**kwargs): start=time.time() res=func(*args,**kwargs) stop=time.time() print(stop - start) return res
Three: write a decorator, as a function of plus certified function
Four: write a decorator for multiple functions plus certified function (from the user's account password file) require a login is successful, the follow-up functions are no longer need to enter a user name and password
Note: read a string from a file the dictionary can be used eval ( '{ "name": "egon", "password": "123"}') turn into a dictionary format
Five: write a decorator for several functions plus authentication, requires a successful login, without having to repeat the login within the timeout period, exceeding the timeout, you must log in again
import time login_user = None login_time = None def check_session(func): time_out = 4 def wrapper(*args,**kwargs): global login_user,login_time res = func(*args,**kwargs) end = time.time() if end - login_time > time_out: login_user = None print('登陆超时') login_time = None return res return wrapper def check_login(func): def wrapper(*args, **kwargs): global login_user,login_time if login_user: func(*args, **kwargs) else: ipt_account = input('输入账号:').strip() ipt_pwd = input('输入密码:').strip() with open('db.txt', mode='rt', encoding=' UTF-. 8 ' ) AS F: for I in F: IF [ipt_account, ipt_pwd] == i.strip ( ' \ n- ' ) .split ( ' : ' ): login_user = ipt_account Print ( ' successful login, now use function ' ) login_time = time.time () BREAK the else : Print ( ' account name or password is incorrect, you can not use function ' ) return wrapper @check_session @check_login def func1(cmd): print('func1', cmd) @check_session @check_login def func2(cmd): print('func2', cmd) menu = { '1': ['func1', func1], '2': ['func2', func2], '3': ['exit', exit] } while True: for i in menu: print(i, menu[i][0]) cmd = input('cmd:').strip() menu[cmd][1](cmd)