python ca模块_Python学习——python的常用模块

模块:用一堆代码实现了某个功能的代码集合,模块是不带 .py 扩展的另外一个 Python 文件的文件名。

一、time & datetime模块

1 importtime2 importdatetime3

4 print(time.asctime()) #返回时间格式:Sun May 7 21:46:15 2017

5 print(time.time()) #返回时间戳 ‘1494164954.6677325’

6 print(time.gmtime()) #返回本地时间 的struct time对象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)

7 print(time.localtime()) #返回本地时间 的struct time对象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)

8 print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式

9 print(time.asctime(time.localtime())) #返回时间格式Sun May 7 22:15:09 2017

10 print(time.ctime()) #返回时间格式Sun May 7 22:15:09 2017

11 print(time.strftime('%Y-%m-%d')) #默认当前时间 2017-05-07

12 print(time.strftime('%Y-%m-%d',time.localtime())) #默认当前时间 2017-05-07

13

14 string_struct = time.strptime("2016/05/22","%Y/%m/%d") #将日期字符串 转成 struct时间对象格式

15 print(string_struct) #返回struct time对象格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1)

16

17 #将日期字符串转成时间戳

18 struct_stamp = time.mktime(string_struct) #将struct time时间对象转成时间戳

19 print(struct_stamp) #返回时间戳 ‘1463846400.0’

20

21 #将时间戳转为字符串格式

22 print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式

23 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式

24

25

26 #时间加减

27 print(datetime.datetime.now()) #返回当前时间 2017-05-07 22:36:45.179732

28 print(datetime.date.fromtimestamp(time.time())) #时间戳直接转换成日期格式 2017-05-07

29 print(datetime.datetime.now() + datetime.timedelta(3)) #返回时间在当前日期上 +3 天

30 print(datetime.datetime.now() + datetime.timedelta(-3)) #返回时间在当前日期上 -3 天

31 print(datetime.datetime.now() + datetime.timedelta(hours= 3)) #返回时间在当前时间上 +3 小时

32 print(datetime.datetime.now() + datetime.timedelta(minutes= 30)) #返回时间在当前时间上 +30 分钟

33

34 c_time =datetime.datetime.now()35 print(c_time) #当前时间为 2017-05-07 22:52:44.016732

36 print(c_time.replace(minute=3,hour=2)) #时间替换 替换时间为‘2017-05-07 02:03:18.181732’

37

38 print(datetime.timedelta) #表示时间间隔,即两个时间点之间的长度

39 print (datetime.datetime.now() - datetime.timedelta(days=5)) #返回时间在当前时间上 -5 天

40

41 #python 日历模块

42 importcalendar43

44 print(calendar.calendar(theyear= 2017)) #返回2017年整年日历

45 print(calendar.month(2017,5)) #返回某年某月的日历,返回类型为字符串类型

46

47 calendar.setfirstweekday(calendar.WEDNESDAY) #设置日历的第一天(第一天以星期三开始)

48 cal = calendar.month(2017, 4)49 print(cal)50

51 print(calendar.monthrange(2017,5)) #返回某个月的第一天和这个月的所有天数

52 print(calendar.monthcalendar(2017,5)) #返回某个月以每一周为元素的序列

53

54 cal =calendar.HTMLCalendar(calendar.MONDAY)55 print(cal.formatmonth(2017, 5)) #在html中打印某年某月的日历

56

57 print(calendar.isleap(2017)) #判断是否为闰年

58 print(calendar.leapdays(2000,2017)) #判断两个年份间闰年的个数

二、random模块

1 importrandom2

3 #随机数

4 print(random.random()) #返回一个随机小数'0.4800545746046827'

5 print(random.randint(1,5)) #返回(1-5)随机整型数据

6 print(random.randrange(1,10)) #返回(1-10)随机数据

7

8 #生成随机验证码

9 code = ''

10 for i in range(4):11 current = random.randrange(0,4)12 if current !=i:13 temp = chr(random.randint(65,90))14 else:15 temp = random.randint(0,9)16 code +=str(temp)17

18 print(code)

三、OS模块

1 importos2

3 print(os.getcwd()) #获得当前工作目录

4 print(os.chdir("dirname")) #改变当前脚本的工作路径,相当于shell下的cd

5 print(os.curdir) #返回当前目录‘.'

6 print(os.pardir) #获取当前目录的父目录字符串名‘..'

7 print(os.makedirs('dirname1/dirname2')) #可生成多层递归目录

8 print(os.removedirs('dirname1/dirname2')) #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

9 print(os.mkdir('test4')) #生成单级目录;相当于shell中mkdir dirname

10 print(os.rmdir('test4')) #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

11 print(os.listdir('/pythonStudy/s12/test')) #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

12 print(os.remove('log.log')) #删除一个指定的文件

13 print(os.rename("oldname","newname")) #重命名文件/目录)

14 print(os.stat('/pythonStudy/s12/test')) #获取文件/目录信息

15 print(os.pathsep) #输出用于分割文件路径的字符串';'

16 print(os.name) #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

17 print(os.system(command='bash')) #运行shell命令,直接显示

18 print(os.environ) #获得系统的环境变量

19 print(os.path.abspath('/pythonStudy/s12/test')) #返回path规范化的绝对路径

20 print(os.path.split('/pythonStudy/s12/test')) #将path分割成目录和文件名二元组返回

21 print(os.path.dirname('/pythonStudy/s12/test')) #返回path的目录。其实就是os.path.split(path)的第一个元素

22 print(os.path.basename('/pythonStudy/s12/test')) #返回path最后的文件名。如果path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素

23 print(os.path.exists('test')) #判断path是否存在

24 print(os.path.isabs('/pythonStudy/s12/test')) #如果path是绝对路径,返回True

25 print(os.path.isfile('test')) #如果path是一个存在的文件,返回True。否则返回False

26 print(os.path.isdir('/pythonStudy/s12/test')) #如果path是一个存在的目录,则返回True。否则返回False

27 print(os.path.getatime('/pythonStudy/s12/test')) #返回path所指向的文件或者目录的最后存取时间

28 print(os.path.getmtime('/pythonStudy/s12/test')) #返回path所指向的文件或者目录的最后修改时间

四、sys模块

1 importsys2

3 print(sys.argv) #命令行参数List,第一个元素是程序本身路径

4 print(sys.exit(n)) #退出程序,正常退出时exit(0)

5 print(sys.version) #获取python的版本信息

6 print(sys.path) #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

7 print(sys.platform) #返回操作平台的名称

五、shutil模块

1 importshutil2 shutil.copyfileobj(fsrc, fdst, length=16*1024) #将文件内容拷贝到另一个文件中,可以是部分内容

3 shutil.copyfile(src, dst) #拷贝文件

4 shutil.copymode(src, dst) #仅拷贝权限。内容、组、用户均不变

5 shutil.copystat(src, dst) #拷贝状态的信息,包括:mode bits, atime, mtime, flags

6 shutil.copy(src, dst) #拷贝文件和权限

7 shutil.copy2(src, dst) #拷贝文件和状态信息

8 shutil.move(src, dst) #递归的去移动文件

9

10 #base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径

11 #format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”

12 #root_dir: 要压缩的文件夹路径(默认当前目录)

13 #owner: 用户,默认当前用户

14 #group: 组,默认当前组

15 #logger: 用于记录日志,通常是logging.Logger对象

16 shutil.make_archive(base_name, format,root_dir,owner,group,logger) #创建压缩包并返回文件路径,例如:zip、tar

17

18 shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的:19

20 #zipfile 压缩解压

21

22 importzipfile23 #压缩

24 z = zipfile.ZipFile('laxi.zip', 'w')25 z.write('a.log')26 z.write('data.data')27 z.close()28

29 #解压

30 z = zipfile.ZipFile('laxi.zip', 'r')31 z.extractall()32 z.close()33

34 #tarfile 压缩解压

35

36 importtarfile37

38 #压缩

39 tar = tarfile.open('your.tar','w')40 tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')41 tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')42 tar.close()43

44 #解压

45 tar = tarfile.open('your.tar','r')46 tar.extractall() #可设置解压地址

47 tar.close()

六、XML处理模块

1 #xml的格式如下,就是通过<>节点来区别数据结构的:

2 xmltest.xml3

4 <?xml version="1.0"?>

5

6

7

8

9

10 2

11

12 2008

13

14 141100

15

16

17

18

19

20

21

22

23

24 5

25

26 2011

27

28 59900

29

30

31

32

33

34

35

36 69

37

38 2011

39

40 13600

41

42

43

44

45

46

47

48

49

50

51 #xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml

52

53 importxml.etree.ElementTree as ET54

55 tree = ET.parse("xmltest.xml")56 root =tree.getroot()57 print(root.tag)58

59 #遍历xml文档

60 for child inroot:61 print(child.tag, child.attrib)62 for i inchild:63 print(i.tag,i.text)64

65 #只遍历year 节点

66 for node in root.iter('year'):67 print(node.tag,node.text)68

69

70 #修改和删除xml文档内容

71

72 importxml.etree.ElementTree as ET73

74 tree = ET.parse("xmltest.xml")75 root =tree.getroot()76

77 #修改

78

79 for node in root.iter('year'):80 new_year = int(node.text) + 1

81 node.text =str(new_year)82 node.set("updated","yes")83 tree.write("xmltest.xml")84

85 #删除node

86

87 for country in root.findall('country'):88 rank = int(country.find('rank').text)89 if rank > 50:90 root.remove(country)91 tree.write('output.xml')92

93

94 #自己创建xml文档

95 importxml.etree.ElementTree as ET96

97 new_xml = ET.Element("namelist")98 name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})99 age = ET.SubElement(name, "age", attrib={"checked": "no"})100 age = ET.SubElement(name, "age")101 age.text = '33'

102 name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})103 age = ET.SubElement(name2, "age")104 age.text = '19'

105 et = ET.ElementTree(new_xml) #生成文档对象

106 et.write("test.xml", encoding="utf-8", xml_declaration=True)107 ET.dump(new_xml) #打印生成的格式

七、configparser模块

用于生成和修改常见配置文档

1 #好多软件的常见文档格式如下

2 [DEFAULT]3 compressionlevel = 9

4 serveraliveinterval = 45

5 compression =yes6 forwardx11 =yes7

8 [bitbucket.org]9 user =hg10

11 [topsecret.server.com]12 host port = 50022

13 forwardx11 =no14

15 #python 生成一个这样的文档

16

17 importconfigparser18

19 config =configparser.ConfigParser()20

21 config["DEFAULT"] = {'ServerAliveInterval': '45',22 'Compression': 'yes',23 'CompressionLevel': '9'}24

25 config['bitbucket.org'] ={}26 config['bitbucket.org']['User'] = 'hg'

27 config['topsecret.server.com'] ={}28 topsecret = config['topsecret.server.com']29 topsecret['Host Port'] = '50022'

30 topsecret['ForwardX11'] = 'no'

31 config['DEFAULT']['ForwardX11'] = 'yes'

32 with open('example.ini', 'w') as configfile:33 config.write(configfile)34

35

36

37 #写完了还可以再读出来

38

39 importconfigparser40 config =configparser.ConfigParser()41 config.sections()42 file = config.read('example.ini')43 print(file) #['example.ini']

44

45 title =config.sections()46 print(title) #['bitbucket.org', 'topsecret.server.com']

47

48 print('bitbucket.org' in config) #True

49 print('bytebong.com' in config) #False

50 print(config['bitbucket.org']['User']) #hg

51 print(config['DEFAULT']['Compression']) #yes

52

53 topsecret = config['topsecret.server.com']54 print(topsecret['ForwardX11']) #no

55 print(topsecret['Host Port']) #50022

56

57 for key in config['topsecret.server.com']:58 print(key)59 '''

60 输出结果:61 host port62 forwardx1163 compressionlevel64 serveraliveinterval65 compression66 '''

67 print(config['topsecret.server.com']['Compression']) #yes

68

69 #configparser增删改查语法

70 importconfigparser71

72 config =configparser.ConfigParser()73 config.read('i.cfg')74

75 secs = config.sections() #返回配置文件中的主节点

76 print(secs)77

78 options = config.options('bitbucket.org')79 print(options) #返回所有子节点信息

80

81 item_list = config.items('bitbucket.org')82 print(item_list) #列出所有子节点详细信息

83

84 val = config.get('topsecret.server.com','host port')85 print(val) #返回单个子节点信息

86

87 val2 = config.getint('topsecret.server.com','host port')88 print(val2)89

90 #删除'bitbucket.org'

91 sec = config.remove_section('bitbucket.org')92 config.write(open('i.cfg','w'))93

94

95 sec2 = config.add_section('huhuan2') #添加主节点

96 config.set('huhuan2','k','1111') #添加子节点

97 config.set('huhuan','kk','2222')98 config.remove_option('huhuan','kk') #删除子节点

99 config.write(open('i.cfg','w'))

八、hashlib模块

用于加密相关的操作

1 importhashlib2

3 #****** md5 ******

4 m =hashlib.md5()5 m.update(b'hello')6 print(m.hexdigest()) #16进制格式

7 print(m.digest()) #2进制格式

8

9 #****** shal ******

10 hash =hashlib.sha1()11 hash.update(b'hello')12 print(hash.hexdigest())13

14 #****** sha224 ******

15 hash =hashlib.sha224()16 hash.update(b'hello')17 print(hash.hexdigest())18

19 #****** sha256 ******

20 hash =hashlib.sha256()21 hash.update(b'hello')22 print(hash.hexdigest())23

24 #****** sha384 ******

25 hash =hashlib.sha384()26 hash.update(b'hello')27 print(hash.hexdigest())28

29 #****** sha512 ******

30 hash =hashlib.sha512()31 hash.update(b'hello')32 print(hash.hexdigest())33

34 运行结果:35 5d41402abc4b2a76b9719d911017c59236 b']A@*\xbcK*v\xb9q\x9d\x91\x10\x17\xc5\x92'

37 aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d38 ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa2419339 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b982440 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f41 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043

九、logging 模块

python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error() and

1 importlogging2

3 #%(message)s 日志信息

4 #%(levelno)s 日志级别

5 #datefmt 设置时间格式

6 #filename 设置日志保存的路径

7 #level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,

8 #在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。

9 logging.basicConfig(format='%(asctime)s %(message)s %(levelno)s', datefmt='%m/%d/%Y %I:%M:%S %p',filename='example.log',level=logging.INFO)10 logging.debug('This message should go to the log file')11 logging.info('So should this')

日志格式

%(name)s

Logger的名字

%(levelno)s

数字形式的日志级别

%(levelname)s

文本形式的日志级别

%(pathname)s

调用日志输出函数的模块的完整路径名,可能没有

%(filename)s

调用日志输出函数的模块的文件名

%(module)s

调用日志输出函数的模块名

%(funcName)s

调用日志输出函数的函数名

%(lineno)d

调用日志输出函数的语句所在的代码行

%(created)f

当前时间,用UNIX标准的表示时间的浮 点数表示

%(relativeCreated)d

输出日志信息时的,自Logger创建以 来的毫秒数

%(asctime)s

字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

%(thread)d

线程ID。可能没有

%(threadName)s

线程名。可能没有

%(process)d

进程ID。可能没有

%(message)s

用户输出的消息

1 #对于等级:

2

3 CRITICAL = 50

4

5 ERROR = 40

6

7 WARNING = 30

8

9 INFO = 20

10

11 DEBUG = 10

12

13 NOTSET = 0

Python 使用logging模块记录日志涉及四个主要类:

logger提供了应用程序可以直接使用的接口;

handler将(logger创建的)日志记录发送到合适的目的输出;

filter提供了细度设备来决定输出哪条日志记录;

formatter决定日志记录的最终输出格式。

logger :

每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger: LOG=logging.getLogger(”chat.gui”)

而核心模块可以这样: LOG=logging.getLogger(”chat.kernel”)

Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高

Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter

Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler

Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别

handler

handler

对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过

addHandler()方法添加多个多handler

Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略

Handler.setFormatter():给这个handler选择一个格式

Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象

每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:

1)    logging.StreamHandler

使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:

StreamHandler([strm])

其中strm参数是一个文件对象。默认是sys.stderr

2)   logging.FileHandler

和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:

FileHandler(filename[,mode])

filename是文件名,必须指定一个文件名。

mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。

3)   logging.handlers.RotatingFileHandler

这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:

RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])

其中filename和mode两个参数和FileHandler一样。

maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。

backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。

4)   logging.handlers.TimedRotatingFileHandler

这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:

TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])

其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。

interval是时间间隔。

when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:

S 秒

M 分

H 小时

D 天

W 每星期(interval==0时代表星期一)

midnight 每天凌晨

1 importlogging2

3 logger = logging.getLogger('TEST_LOG') #获得一个Logger

4 logger.setLevel(logging.DEBUG) #设置日志级别

5

6 ch = logging.StreamHandler() #logging.StreamHandler这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。

7 ch.setLevel(logging.DEBUG)8

9 fh = logging.FileHandler("access.log") #用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件

10 fh.setLevel(logging.WARNING)11

12 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') #设置日志记录的最终输出格式

13

14 ch.setFormatter(formatter)15 fh.setFormatter(formatter)16

17 #添加ch,fh到logger

18 logger.addHandler(ch)19 logger.addHandler(fh)20

21

22 logger.debug('debug message')23 logger.info('info message')24 logger.warn('warn message')25 logger.error('error message')26 logger.critical('critical message')

文件自动截断实例:

1 importlogging2 from logging importhandlers3

4 logger = logging.getLogger(__name__)5 log_file = "timelog.log"

6 fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)7 #fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)

8

9 formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')10 fh.setFormatter(formatter)11

12 logger.addHandler(fh)13

14 logger.warning("test1")15 logger.warning("test12")16 logger.warning("test13")17 logger.warning("test14")

十、subprocess模块(待定)

十一、json & pickle 模块

用于序列化的两个模块

json,用于字符串 和 python数据类型间进行转换

pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

1 importpickle2

3 date = {'k1':'123','k2':'hello'}4

5 str = pickle.dumps(date) #pickle.dumps 将数据通过特殊的形式转换为只有python认识的字符串

6 print(str)7

8 with open('result.pk','w') as fp: #pickle.dump 将数据通过特殊的形式转换为只有python认识的字符串并写入文件

9 pickle.dump(date,fp)10

11 importjson12

13 str1 = json.dumps(date) #json.dumps 将数据通过特殊形式转换为所有程序语言都认识的字符串

14 print(str1)15

16 with open('result1.json','w') as fp: #json.dump 将数据通过特殊的形式转换为只有python认识的字符串并写入文件

17 json.dump(date,fp)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中使用MQTT协议进行通信可以使用paho-mqtt库,同时也支持TLS/SSL加密。下面是一个简单的示例程序: ```python import ssl import paho.mqtt.client as mqtt # MQTT连接信息 mqtt_broker = "broker.example.com" mqtt_port = 8883 mqtt_username = "username" mqtt_password = "password" # TLS/SSL证书信息 ca_cert = "/path/to/ca.crt" client_cert = "/path/to/client.crt" client_key = "/path/to/client.key" def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("test/topic") def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) client = mqtt.Client() client.tls_set(ca_cert, certfile=client_cert, keyfile=client_key, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2) client.username_pw_set(mqtt_username, mqtt_password) client.on_connect = on_connect client.on_message = on_message client.connect(mqtt_broker, mqtt_port, 60) client.loop_forever() ``` 在此示例中,我们导入了`ssl`和`paho.mqtt.client`库,然后设置MQTT连接信息和TLS/SSL证书信息。在`on_connect`和`on_message`函数中,我们定义了当连接成功和收到消息时的行为。最后,我们创建了一个MQTT客户端对象,设置TLS/SSL证书,连接到MQTT代理,并开始循环以处理所有MQTT事件。 如果您没有TLS/SSL证书,可以使用以下代码禁用TLS/SSL加密: ```python import paho.mqtt.client as mqtt # MQTT连接信息 mqtt_broker = "broker.example.com" mqtt_port = 1883 mqtt_username = "username" mqtt_password = "password" def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("test/topic") def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) client = mqtt.Client() client.username_pw_set(mqtt_username, mqtt_password) client.on_connect = on_connect client.on_message = on_message client.connect(mqtt_broker, mqtt_port, 60) client.loop_forever() ``` 在此示例中,我们将MQTT端口设置为1883,并禁用了TLS/SSL加密。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值