[关闭]
@richey 2020-09-17T15:36:55.000000Z 字数 4814 阅读 1750

微型计算机技术应用讲义10-python基础(2)

python 讲义


1.最简单的python程序

  1. # coding=utf8
  2. print "hello world!\r\n"

2.语法

2.1 缩进(严格缩进4个空格)

  1. def fun1():
  2. print "你好!\r\n"
  3. fun1()

2.2 数据类型

-list列表

  1. def fun1():
  2. print "你好!\r\n"
  3. fun1()
  4. l=[1,2,5,6,8]
  5. print l
  6. print l[3]
  7. for item in l:
  8. print item

-元组
ython的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。

  1. tup1 = ('physics', 'chemistry', 1997, 2000);
  2. tup2 = (1, 2, 3, 4, 5 );
  3. tup3 = "a", "b", "c", "d";
  4. print tup1
  5. print tup2
  6. print tup3

-字典dict

  1. bdict = {'name':'allen', 'age':'40'}
  2. for key in bdict.keys():
  3. print key
  4. print bdict[key]

2.3 if、for、while、break

3 twisted异步网络通信库

3.1 介绍

参考:http://blog.csdn.net/hanhuili/article/details/9389433
Twisted是用Python实现的基于事件驱动的网络引擎框架。Twisted支持许多常见的传输及应用层协议,包括TCP、UDP、SSL/TLS、HTTP、IMAP、SSH、IRC以及FTP。Twisted对于其支持的所有协议都带有客户端和服务器实现,同时附带有基于命令行的工具,使得配置和部署产品级的Twisted应用变得非常方便。
twisted技术架构.jpg-56.3kB

3.2 Reactor

Reactor是事件管理器,用于注册、注销事件,运行事件循环,当事件发生时调用回调函数处理。Reactor可以感知网络、文件系统以及定时器事件。它等待然后处理这些事件,从特定于平台的行为中抽象出来,并提供统一的接口,使得在网络协议栈的任何位置对事件做出响应都变得简单。
关于reactor有下面几个结论:
Twisted的reactor只有通过调用reactor.run()来启动。
reactor循环是在其开始的进程中运行,也就是运行在主进程中。
一旦启动,就会一直运行下去。reactor就会在程序的控制下(或者具体在一个启动它的线程的控制下)。reactor循环并不会消耗任何CPU的资源。并不需要显式的创建reactor,只需要引入就OK了。

3.3 Transports

Transports代表网络中两个通信结点之间的连接。Transports负责描述连接的细节,比如连接是面向流式的还是面向数据报的,流控以及可靠性。TCP、UDP和Unix套接字可作为transports的例子。它们被设计为“满足最小功能单元,同时具有最大程度的可复用性”,而且从协议实现中分离出来,这让许多协议可以采用相同类型的传输。Transports实现了ITransports接口,它包含如下的方法:
write 以非阻塞的方式按顺序依次将数据写到物理连接上
writeSequence 将一个字符串列表写到物理连接上
loseConnection 将所有挂起的数据写入,然后关闭连接
getPeer 取得连接中对端的地址信息
getHost 取得连接中本端的地址信息
将transports从协议中分离出来也使得对这两个层次的测试变得更加简单。可以通过简单地写入一个字符串来模拟传输,用这种方式来检查。

3.4 Protocols

Protocols描述了如何以异步的方式处理网络中的事件。HTTP、DNS以及IMAP是应用层协议中的例子。Protocols实现了IProtocol接口,它包含如下的方法:
makeConnection 在transport对象和服务器之间建立一条连接
connectionMade 连接建立起来后调用
dataReceived 接收数据时调用
connectionLost 关闭连接时调用

3.5 Factory

切确的说,它取名不太好,应该叫做FactoryOfProtocals,即协议工厂(也就是工厂模式),用来管理协议对象实例的。

4 串口收发数据

  1. # coding=utf8
  2. import sys
  3. import re
  4. if sys.platform == 'win32':
  5. from twisted.internet import win32eventreactor
  6. win32eventreactor.install()
  7. from twisted.internet import defer, threads
  8. from twisted.internet.serialport import SerialPort
  9. from twisted.internet import protocol,task, reactor, error
  10. from twisted.protocols.basic import LineReceiver
  11. from twisted.python import log, usage
  12. class GasSim(LineReceiver):
  13. def __init__(self):
  14. self._lc1 = task.LoopingCall(self.sendCmd)
  15. self._lc1.start(3,False)
  16. def sendCmd(self):
  17. self.sendLine("@01c100001".encode('utf-8'))
  18. def lineReceived(self, line):
  19. line = line.decode('utf-8')
  20. print(line)
  21. if(re.match('@\d{2}\D\w{4}\d{2}',line)):
  22. if(line[3] == 'D'):
  23. print ('接收到1条命令!\r\n')
  24. tmpstr = "当前电压值=%.3f" % (int(line[4:8],16)/1000.0)
  25. print (tmpstr)
  26. if __name__ == '__main__':
  27. s = SerialPort(GasSim(), 'COM2', reactor, baudrate=9600)
  28. reactor.run()

5. socket网络数据通信

  1. # coding: utf-8
  2. import re
  3. import datetime
  4. import time
  5. import json
  6. import redis
  7. from twisted.internet import reactor, task, protocol
  8. from twisted.internet import defer, threads
  9. from twisted.internet.protocol import Protocol, error, Factory
  10. from twisted.protocols.basic import LineReceiver
  11. r = redis.Redis(host='127.0.0.1',port=6379,db=0)
  12. def getCurrentStrTime():
  13. return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  14. class GasServerProtocol(LineReceiver):
  15. def __init__(self, factory):
  16. self.id = ''
  17. self.factory = factory
  18. def connectionMade(self):
  19. print((
  20. "[%s]: %s连接到服务器端。" %
  21. (getCurrentStrTime(), self.transport.getPeer())))
  22. self.sendLine("$99'".encode('utf-8'))
  23. def connectionLost(self, reason):
  24. if self.id in self.factory.clients:
  25. del self.factory.clients[self.id]
  26. print("[%s]:ID %s 下线" % (getCurrentStrTime(), self.id))
  27. print((
  28. "[%s]: %s断开了连接,原因是%s" %
  29. (getCurrentStrTime(),
  30. self.transport.getPeer(),
  31. reason)))
  32. def lineReceived(self, data):
  33. data = data.decode('utf-8')
  34. tmpstr = ("[%s]: 收到数据 %s") % (getCurrentStrTime(), data)
  35. print(tmpstr)
  36. if(re.match("\$\d{2}\$", data)):
  37. self.id = str(data[1:3])
  38. dicttmp = {}
  39. dicttmp['handle'] = self
  40. dicttmp['timestamp'] = time.time()
  41. self.factory.clients[self.id] = dicttmp
  42. print("[%s]:ID %s 注册成功" % (getCurrentStrTime(), self.id))
  43. if(re.match('@\d{2}\D\w{4}\d{2}',data)):
  44. if(data[3] == 'D'):
  45. print('接收到1条命令!\r\n')
  46. volttmp = (int(data[4:8],16)/1000.0)
  47. tmpstr = "当前电压值=%.3f" % volttmp
  48. print(tmpstr)
  49. dicttmp = {}
  50. dicttmp['collecttime'] = getCurrentStrTime()
  51. dicttmp['volt'] = volttmp
  52. dicttmp['id'] = self.id
  53. r.set(self.id, json.dumps(dicttmp))
  54. print(r.get(self.id))
  55. class GasServerFactory(Factory):
  56. def __init__(self):
  57. self.clients = {} # maps clients ids to GasServerProtocol instances
  58. self._lc = task.LoopingCall(self.send_to_clients)
  59. self._lc.start(3,now=False)
  60. def buildProtocol(self, addr):
  61. return GasServerProtocol(self)
  62. def send_to_clients(self):
  63. for client_addr in self.clients :
  64. self.clients[client_addr]['handle'].sendLine('hello!'.encode('utf-8'))
  65. def startMoniter():
  66. print("[%s]启动监控服务" % getCurrentStrTime())
  67. cf = GasServerFactory()
  68. reactor.listenTCP(8234, cf)
  69. reactor.run()
  70. def stopMoniter():
  71. print("[%s]停止监控服务" % getCurrentStrTime())
  72. try:
  73. reactor.crash()
  74. except RuntimeError:
  75. return defer.fail()
  76. else:
  77. return defer.succeed(None)
  78. startMoniter()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注