Python初探

作者: 安静的风筝 | 来源:发表于2018-01-12 15:45 被阅读0次

Python现在火了,估计很大一方面是因为AI技术的兴起,现在 AI 编程语言Python占了绝大多数。

今天上午活干完了,简单看了下Python,也是了解个皮毛,简单记录介绍下,也是学习的一个巩固,结合上篇打印机的工作展开,如果直说语法那不是耍流氓嘛是不是,语法介绍网上随便搜

上篇蓝牙打印 demo 再调试起来很不方面,我得生成 byte 再拷贝到客户端 demo 里,然后再调试,很麻烦。

思路:都通过电脑链接蓝牙,写一个Python脚本发送数据,打印。我给大家做了详细注释,你一定能看得懂。

首页我在网上找了一段 code,先看便与大家理解后面的:https://www.programcreek.com/python/example/98062/PyObjCTools.AppHelper.runEventLoop

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
""" # -*- coding: UTF-8 -*-  #这句一定要加,我加了很多中文注释,会报编码错误  或者#coding=utf-8也可以"""
import select
import socket
import sys

import objc
from PyObjCTools import AppHelper
from CoreBluetooth import *
from AppKit import *
from Foundation import *
import subprocess

printerName = "DL581printer" #//外围设备名称--目标蓝牙打印机
blebee_service = CBUUID.UUIDWithString_(u'E7810A71-73AE-499D-8C15-FAA9AEF0C3F2') #服务的UUID
blebee_characteristic = CBUUID.UUIDWithString_(u'BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F') #特征的UUID

class RobotDelegate(object): #这部分蓝牙代理和 ios 端是相同的 其实都是调用的是CoreBluetooth,只是客户端要考虑体验,以及真实项目的原因,写的要比这里复杂,可参考我上篇简书.android也差求不多,这里不多做介绍,可出面右转看上篇帖子。
    def __init__(self):#python 构造函数
        self.manager = None
        self.peripheral = None

        self.service = None

        self.characteristic = None

        self.comms = None

    def centralManagerDidUpdateState_(self, manager): #获取CentralManager的状态state
        self.manager = manager

        if manager.state() == CBCentralManagerStatePoweredOn: #设备开启状态 -- 可用状态
            manager.scanForPeripheralsWithServices_options_(None, None) #扫描


    def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, manager, peripheral, data, rssi):#当调用scanForPeripheralsWithServices_options_扫描的时候 会回调这个方法,在这个方法中获取扫描到的设备的信息
        if self.peripheral != None: #没发现
            return

        name = peripheral.name() #发现设备打印名称
        print name

        if name == printerName: #发现目标蓝牙打印机
            self.peripheral = peripheral
            manager.stopScan() #停止扫描
            manager.connectPeripheral_options_(peripheral, None) #调用此方法后链接到蓝牙设备,链接不会超时,根据不同的结果,启用不同的回调方法.


    def centralManager_didConnectPeripheral_(self, manager, peripheral): #链接成功后走这个代理方法
        name = peripheral.name()
        if name == None:
            return

        print 'connected'

        self.peripheral.setDelegate_(self) #设置目标打印机代理
        self.peripheral.discoverServices_(None) #查找服务 参数可以为nil

    def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error): #失去链接后走这个代理方法
        AppHelper.stopEventLoop()

    def peripheral_didDiscoverServices_(self, peripheral, services):#调用查找服务discoverServices:后 会回调此方法
        for service in peripheral.services():
            print service
            if service.UUID() == blebee_service:#蓝牙4.0设备因为低耗电,所以也叫做BLE
                self.service = service
                self.peripheral.discoverCharacteristics_forService_([blebee_characteristic], self.service)#查找特征


    def peripheral_didDiscoverCharacteristicsForService_error_(self, peripheral, service, error):#调用查找特征discoverCharacteristics后 会回调此方法一般会在此方法中遍历服务的特征
        for characteristic in self.service.characteristics():
            if characteristic.UUID() == blebee_characteristic:
                self.characteristic = characteristic

        proc = subprocess.Popen("php printer.php", shell=True, stdout=subprocess.PIPE) #从python2.4版本开始,可以用subprocess这个模块来产生子进程,并连接到子进程的标准输入/输出/错误中去,还可以得到子进程的返回值
        script_response = proc.stdout.read() #得到返回值,此返回值,是printer.php经过 base64后得到 bye 数据,这部分内容,请出门右转看我上篇帖子

        data = NSData.alloc().initWithBase64EncodedString_options_(NSString.stringWithString_(script_response), 0) #这句做过 ios 都知道 base64解码
        #下面的byte 数据对蓝牙设备的写入,佳博的打印机是支持146长度的写入的,很多不支持,会溢出调短成32位
        pos = 0
        len = data.length()
        while pos < len:
            if pos + 32 < len:
                sublen = 32
            else:
                sublen = len - pos

            subdata = data.subdataWithRange_(NSMakeRange(pos, sublen))
            peripheral.writeValue_forCharacteristic_type_(subdata, self.characteristic, CBCharacteristicWriteWithResponse)#写入没啥好说的
            pos += sublen

    #游戏结束
    def shutdown(self):
        if self.peripheral is not None:
            self.manager.cancelPeripheralConnection_(self.peripheral)#断开蓝牙连接,之前我在做客户端ios demo 的时候有发现,这地方不是立马断开的,应该是延迟5秒,具体嘛原因没细纠
        else:
            AppHelper.stopEventLoop()

#设置 socket 部分
class CommsManager(object):
    def __init__(self, robot): #python 构造函数
        self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #SocketListener
        self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #setsockopt()函数用于任意类型、任意状态套接口的设置选项值
        self.listener.bind(("127.0.0.1", 9999)) #//绑定端口ip
        self.listener.listen(1) #开始监听,并设置最大排队连接数

        self.connection = None

        self.robot = robot
        self.robot.comms = self

    def loop(self):
        endpoints = [sys.stdin, self.listener] #python中使用sys.stdin.readline()可以实现标准输入,注意默认输入的是字符串(注意这里的strip('\n')表示以\n分隔,否则输出是“字符串+\n”的形式 ),如果是int,float类型则需要强制转换。
        if self.connection is not None:
            endpoints.append(self.connection)
            # XXX: Consider using another file descriptor or
            # connecting to the socket to wake this up instead of
            # polling. Polling reduces our responsiveness to a
            # shutdown request and wastes cpu at all other times.
        r, w, e = select.select(endpoints, [], [], 0)
        if sys.stdin in r:
            delegate.shutdown()
            return
        if self.listener in r:
            self.connection, _ = self.listener.accept()
        if self.connection in r:
            c = self.connection.recv(1)
            if len(c) == 0:
                print "closed"
                self.connection.close()
                self.connection = None
            elif c not in ('\r', '\n'):
                print repr(c)
                self.robot.send(c)

        AppHelper.callLater(0.1, self.loop)

    def send(self, data):
        while len(data):
            sent = self.connection.send(data)
            data = data[sent:]

'''Python 与其他语言最大的区别就是,Python 的代码块不使用大括号 {} 来控制类,函数以及其他逻辑判断。python 最具特色的就是用缩进来写模块。
缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行 所以脚本是这里开始执行'''
delegate = RobotDelegate() #初始化蓝牙代理类
manager = CBCentralManager.alloc() ##初始化蓝牙管理
manager.initWithDelegate_queue_options_(delegate, None, None) #绑定代理

comms = CommsManager(delegate)

AppHelper.callLater(0.1, comms.loop)
AppHelper.runConsoleEventLoop() #走起

要执行上面脚本 要先给 py 文件加可执行权限。

$ chmod +x test.py # 脚本文件添加可执行权限

$ ./test.py 走起。

更新下:

我电脑上Python 环境是Python 2.7.10 (default, Feb 7 2017, 00:08:15) Python3.0并不向下兼容。。。

相关文章

网友评论

    本文标题:Python初探

    本文链接:https://www.haomeiwen.com/subject/ffufoxtx.html