【问题标题】:How to catch error from bluetooth socket and print custom message?如何从蓝牙套接字捕获错误并打印自定义消息?
【发布时间】:2021-10-06 06:19:02
【问题描述】:

我有一个问题,我是 python 的初学者,我有一个蓝牙连接脚本,我想修改它以捕获错误(如果发生错误)。

脚本(有效):

sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port)) 
print('Succeed!')
sock.close()

我怎么能抓住它?如果主机关闭,我会得到这个:

bluetooth.btcommon.BluetoothError: [Errno 112] Host is down

我只想打印我自己的错误信息。

【问题讨论】:

    标签: python bluetooth


    【解决方案1】:

    Python 中通常的方式是使用 try/except 类似这样的东西:

    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    try:
        sock.connect((bd_addr, port))
    except bluetooth.btcommon.BluetoothError:
        print('Host is down')
    else:
        print('Succeed!')
        sock.close()
    

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2016-12-03
      • 2023-03-26
      • 2016-02-24
      • 1970-01-01
      • 2021-12-06
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多