标签:
反射是利用字符串的形式去对象 (模块) 中操作 (寻找/检查) 成员
假设创建了一个common.py 程序里而有3个功能,比如网站里的登录页面、主页页面还有登出页面都是不同的页面,要显示的内容都不一样。
def login(): print("Login Page") def logout(): print("Logout Page") def home(): print("HomePage")
再创建一个py程序:index.py,程序一般是做一个判断然后会基于调用不同的功能来返回不同的结果(参考调用方法一的代码)。
import common #根据用户不同的输入而返回不同的信息 def run(): inp = input("请输入要访问的 url: ") if inp == "login": # 当用户输入 login,还看到 login 页面 common.login() elif inp == "logout": # 当用户输入 logout,还看到 logout 页??面 common.logout() elif inp == "home": # 当用户输入 home,还看到 home 页面 common.home() else: print("404") if __name__ == "__main__": run()
其实此时可以使用反射的方法(参考调用方法二的代码),直接基于用户输入,
# 利用字符串的形式去对象 (模块) 中操作 (寻找/检查) 成员 import common def run(): inp = input("请输入要访问的 url: ") is_exists = hasattr(common,inp) # 检查用户输入是否在common模块里存在的一个成员 if is_exists: func = getattr(common, inp) # 到common模块寻找用户输入的一个成员 func() else: print("404") if __name__ == "__main__": run()
运用 hasattr( ) 和 getattr( )函数来实现,這兩個反射函数分別接收兩個参数(参数一可以是模块, 参数二是参数一的成員)。
hasattr(参数一,参数二) # 到模块里检查成员 #参数一可以是模块, 参数二是参数一的成员
getattr(参数一,参数二) # 到模块里寻找成员 #参数一可以是模块, 参数二是参数一的成员
random( ) 函数是用来随机生成数字
import random word_list = [] for i in range(6): random_num = random.randrange(0, 5) if random_num == 2 or random_num == 4: num = random.randrange(0, 10) word_list.append(str(num)) else: temp = random.randrange(65, 91) word = chr(temp) word_list.append(word) words = "".join(word_list) print(words)
time
import time >>> print(time.time()) 1473427097.89171
import time >>> print(time.ctime()) Fri Sep 9 21:28:13 2016 >>> print(time.ctime(time.time()-86400)) Thu Sep 8 21:29:06 2016
>>> import time >>> time_obj = time.gmtime() >>> print(time_obj) time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=13, tm_min=29, tm_sec=41, tm_wday=4, tm_yday=253, tm_isdst=0) >>> print(time_obj.tm_year,time_obj.tm_mon) 2016 9 >>> type(time_obj) <class ‘time.struct_time‘> >>> ret = "Year={year} Month={mnth}".format(year=time_obj.tm_year,mnth=time_obj.tm_mon) >>> print(ret) Year=2016 Month=9 >>> time_pre_obj = time.gmtime(time.time()-86400) # 返回struct_time类型 >>> print(time_pre_obj) time.struct_time(tm_year=2016, tm_mon=9, tm_mday=8, tm_hour=13, tm_min=34, tm_sec=49, tm_wday=3, tm_yday=252, tm_isdst=0)
>>> print(time.localtime()) time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=21, tm_min=38, tm_sec=47, tm_wday=4, tm_yday=253, tm_isdst=0) >>> time_obj = time.localtime() >>> print(time_obj) time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=21, tm_min=38, tm_sec=59, tm_wday=4, tm_yday=253, tm_isdst=0) >>> type(time_obj) <class ‘time.struct_time‘>
>>> print(time.mktime(time_obj)) 1473428339.0
>>> time.sleep(4) >>> print("--------")
>>> print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())) 2016-09-09 13:47:50 >>> print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) 2016-09-09 21:47:51
>>> tm = time.strptime("2016-09-03","%Y-%m-%d") # 將字符串类型转换成struct_time类型 >>> print(tm) time.struct_time(tm_year=2016, tm_mon=9, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=247, tm_isdst=-1) >>> type(tm) <class ‘time.struct_time‘> >>> print(time.mktime(tm)) 1472832000.0
Datetime
>>> import datetime >>> d1 = datetime.date.today() >>> print(d1)
>>> d2 = datetime.date.fromtimestamp(time.time()); >>> print(d2) 2016-09-09
>>> current_time = datetime.datetime.now() >>> print(current_time) 2016-09-09 21:59:45.125933
>>> t = current_time.timetuple() >>> print(t) time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=21, tm_min=59, tm_sec=45, tm_wday=4, tm_yday=253, tm_isdst=-1) >>> type(t) <class ‘time.struct_time‘>
>>> d3 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") >>> print(d3) 2016-09-09 22:03:29 >>> new_date = datetime.datetime.now() + datetime.timedelta(days=10) >>> print(new_date) 2016-09-19 22:03:38.745696 >>> new_hour = datetime.datetime.now() + datetime.timedelta(hours=4) >>> print(new_hour) 2016-09-10 02:03:41.642530 >>> new_hour = datetime.datetime.now() + datetime.timedelta(hours=4) >>> print(new_hour) 2016-09-10 02:03:44.630359
>>> tm = datetime.datetime.strptime("2016-09-03","%Y-%m-%d") >>> print(tm) 2016-09-03 00:00:00
>>> current_time = datetime.datetime.now() >>> print(current_time) 2016-09-09 22:07:10.352970 >>> replace_time = current_time.replace(2015,5) >>> print(replace_time) 2015-05-09 22:07:10.352970 >>> print(type(current_time)) <class ‘datetime.datetime‘> >>> print(type(replace_time)) <class ‘datetime.datetime‘>
[更新中]
每个程序都需要有日志记录,日志有几个级别:1. DEBUG; 2.INFO; 3. WARNING; 4.ERROR; 5.CRITICAL
import logging logging.warning("User [alex] attempt wrong password for more than 3 times") logging.critical("Server is down") logging.debug(‘This message should go to the log file‘) logging.info(‘So should this‘) logging.warning(‘And this, too‘) #WARNING:root:User [alex] attempt wrong password for more than 3 times #CRITICAL:root:Server is down #WARNING:root:And this, too
想输出日志到文件可以调用以下函数,filename: 文件名,filemode: 写入模式,level: 日志的级别 (跟这个级别同等或者是比这个更高级别的日志才会写入文件)
logging.basicConfig(filename=‘log.txt‘,filemode=‘w‘,level=logging.INFO)
把 basicConfig 加到程序中然后执行程序,因为日志级别是INFO,所以这里的结果是只有INFO级别或以上的,才会写入log.txt的文件里
import logging logging.basicConfig(filename=‘log.txt‘,filemode=‘w‘,level=logging.INFO) logging.warning("User [alex] attempt wrong password for more than 3 times") logging.critical("Server is down") logging.debug(‘This message should go to the log file‘) logging.info(‘So should this‘) logging.warning(‘And this, too‘) #log.txt 会有INFO级别或以上的日志 """ WARNING:root:User [alex] attempt wrong password for more than 3 times CRITICAL:root:Server is down INFO:root:So should this WARNING:root:And this, too """
basicConfig可以传入很多不同的参数
logging.basicConfig(filename=‘log.txt‘, level=logging.DEBUG, format=‘%(asctime)s %(message)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘)
執行
import logging logging.basicConfig(filename=‘log.txt‘, level=logging.DEBUG, format=‘%(asctime)s %(message)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘) logging.warning("User [alex] attempt wrong password for more than 3 times") logging.critical("Server is down") logging.debug(‘This message should go to the log file‘) logging.info(‘So should this‘) logging.warning(‘And this, too‘) # log.tx. """ 09/09/2016 11:15:35 PM User [alex] attempt wrong password for more than 3 times 09/09/2016 11:15:35 PM Server is down 09/09/2016 11:15:35 PM This message should go to the log file 09/09/2016 11:15:35 PM So should this 09/09/2016 11:15:35 PM And this, too """
如果想打印日誌到文件和 Console 上,必需要了解以下概念:
logger = logging.getLogger(‘TEST-LOG‘) logger.setLevel(logging.INFO) #configure a global logging level
console_handler = logging.StreamHandler() #print the log on the console console_handler.setLevel(logging.DEBUG)
file_handler = logging.FileHandler("access.log") file_handler.setLevel(logging.WARNING)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(filename)s - %(levelname)s - %(message)s - %(lineno)s - %(process)d‘)
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
把以上第1步 到 第6步加起來:
import logging #create logger logger = logging.getLogger(‘TEST-LOG‘) logger.setLevel(logging.INFO) #configure a global logging level # create console handler and set the level to debug console_handler = logging.StreamHandler() #print the log on the console console_handler.setLevel(logging.DEBUG) #override the global logging configuration level and specifiy the configuration on the console # create file handler and set level to warning file_handler = logging.FileHandler("access.log") file_handler.setLevel(logging.WARNING) #override the global logging configuration level and specifiy the configuration on the file_system # create formatter formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(filename)s - %(levelname)s - %(message)s - %(lineno)s - %(process)d‘) # add formatter to ch and fh console_handler.setFormatter(formatter) file_handler.setFormatter(formatter) # add console_handler and ffile_handler to logger # 把日志打印到指定的Handler里 logger.addHandler(console_handler) logger.addHandler(file_handler) # ‘application‘ code logger.debug(‘debug message‘) logger.info(‘info message‘) logger.warn(‘warn message‘) logger.error(‘error message‘) logger.critical(‘critical message‘) # Console """ 2016-09-09 23:26:25,907 - TEST-LOG - loggingOps_2.py - INFO - info message - 32 - 1168 2016-09-09 23:26:25,908 - TEST-LOG - loggingOps_2.py - WARNING - warn message - 33 - 1168 2016-09-09 23:26:25,909 - TEST-LOG - loggingOps_2.py - ERROR - error message - 34 - 1168 2016-09-09 23:26:25,910 - TEST-LOG - loggingOps_2.py - CRITICAL - critical message - 35 - 1168 """ # access.log """ 2016-09-04 00:54:05,713 - TEST-LOG - loggingOps_2.py - WARNING - warn message - 33 - 4827 2016-09-04 00:54:05,714 - TEST-LOG - loggingOps_2.py - ERROR - error message - 34 - 4827 2016-09-04 00:54:05,714 - TEST-LOG - loggingOps_2.py - CRITICAL - critical message - 35 - 4827 2016-09-09 23:26:25,908 - TEST-LOG - loggingOps_2.py - WARNING - warn message - 33 - 1168 2016-09-09 23:26:25,909 - TEST-LOG - loggingOps_2.py - ERROR - error message - 34 - 1168 2016-09-09 23:26:25,910 - TEST-LOG - loggingOps_2.py - CRITICAL - critical message - 35 - 1168 """
[更新中]
首先创建一个MD5对象
計算器, +-*/
8*12+(6-(5*6-2)/77+2)*(3-7)+8
需求
[金角大王] Python 之路 Day5 - 常用模块学习 http://www.cnblogs.com/alex3714/articles/5161349.html
[銀角大王] Python开发【第六篇】:模块 - http://www.cnblogs.com/wupeiqi/articles/5501365.html
标签:
原文地址:http://www.cnblogs.com/jcchoiling/p/5838598.html