json模块
import json dic = {‘name‘:‘egon‘,‘age‘:32} # ------------------------------>序列化 f = open(‘json.txt‘,‘w‘) data = json.dumps(dic) print(data) print(type(data)) f.write(data) f.close() # ------------------------------>返序列化 f = open(‘json.txt‘,‘r‘) data = f.read() dic1 = json.loads(data) print(dic1) print(type(dic1)) f.close()
二、logging模块
import logging logger = logging.getLogger() fh = logging.FileHandler(‘test.log‘) # 用于写入日志文件 ch = logging.StreamHandler() # 用于输入到终端 # 自定义格式 formatter = logging.Formatter(‘%(asctime)s-%(name)s-%(levelname)s-%(message)s‘) fh.setFormatter(formatter) sh.setFormatter(formatter) logger.addHandler(fh) #logger对象可以添加多个fh和sh对象 logger.addHandler(sh) logger.debug(‘logger debug message‘) logger.info(‘logger info message‘) logger.warning(‘logger warning message‘) logger.error(‘logger error message‘) logger.critical(‘logger critical message‘)
三、sys模块
import sys
sys.exit(n) 退出程序,正常退出时exit(0)sys.argv 命令行参数List,第一个元素是程序本身路径sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.exit()
import sys count=1 while count<10: print(count) if count==8: sys.exit() # 退出程序 count+=1 print("ending")
sys.argv
# cmd终端输入python sys模块.py egon 666 print("begin..... ") ret=sys.argv # [sys模块.py‘,"egon",666] print(ret) # [‘sys模块.py‘, ‘-u‘, ‘egon‘, ‘-p‘, ‘666‘] username=ret[1] password=ret[2] if username==‘egon‘ and password=="666": print("login")
sys.path
import sys print(sys.path)# [“C:\Users\Administrator\PycharmProjects\python5期\day13”,"python环境"] :执行文件的目录会添加到sys.path Base_dir=r"C:\Users\Administrator\PycharmProjects\python5期\day12" sys.path.append(Base_dir) import lesson1 # 自定义的模块 lesson1.foo()
时间: 2024-10-27 05:36:11