简体   繁体   English

Python:错误:(9,“错误的文件描述符”)

[英]Python: error: (9, 'Bad file descriptor')

I have error at: 我在以下地方有错误:

"File "/home/pi/blescan.py", line 78, in hci_le_set_scan_parameters
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

error: (9, 'Bad file descriptor')"

I am unsure what is the cause of the error, and I have tried whatever solution that is available online, but it resulted in the same error. 我不确定错误的原因是什么,我已经尝试了在线上可用的任何解决方案,但是导致了同样的错误。

DEBUG = False

import os
import sys
import struct
import bluetooth._bluetooth as bluez
from time import gmtime, strftime


LE_META_EVENT = 0x3e
LE_PUBLIC_ADDRESS=0x00
LE_RANDOM_ADDRESS=0x01
LE_SET_SCAN_PARAMETERS_CP_SIZE=7
OGF_LE_CTL=0x08
OCF_LE_SET_SCAN_PARAMETERS=0x000B
OCF_LE_SET_SCAN_ENABLE=0x000C
OCF_LE_CREATE_CONN=0x000D

LE_ROLE_MASTER = 0x00
LE_ROLE_SLAVE = 0x01

# these are actually subevents of LE_META_EVENT
EVT_LE_CONN_COMPLETE=0x01
EVT_LE_ADVERTISING_REPORT=0x02
EVT_LE_CONN_UPDATE_COMPLETE=0x03
EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE=0x04

# Advertisment event types
ADV_IND=0x00
ADV_DIRECT_IND=0x01
ADV_SCAN_IND=0x02
ADV_NONCONN_IND=0x03
ADV_SCAN_RSP=0x04


def returnnumberpacket(pkt):
    myInteger = 0
    multiple = 256
    for c in pkt:
        myInteger +=  struct.unpack("B",c)[0] * multiple
        multiple = 1
    return myInteger 

def returnstringpacket(pkt):
    myString = "";
    for c in pkt:
        myString +=  "%02x" %struct.unpack("B",c)[0]
    return myString 

def printpacket(pkt):
    for c in pkt:
        sys.stdout.write("%02x " % struct.unpack("B",c)[0])

def get_packed_bdaddr(bdaddr_string):
    packable_addr = []
    addr = bdaddr_string.split(':')
    addr.reverse()
    for b in addr: 
        packable_addr.append(int(b, 16))
    return struct.pack("<BBBBBB", *packable_addr)

def packed_bdaddr_to_string(bdaddr_packed):
    return ':'.join('%02x'%i for i in struct.unpack("<BBBBBB",bdaddr_packed[::-1]))

def hci_enable_le_scan(sock):
    hci_toggle_le_scan(sock, 0x01)

def hci_disable_le_scan(sock):
    hci_toggle_le_scan(sock, 0x00)

def hci_toggle_le_scan(sock, enable):
    cmd_pkt = struct.pack("<BB", enable, 0x00)
    bluez.hci_send_cmd(sock, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, cmd_pkt)


def hci_le_set_scan_parameters(sock):
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)



    SCAN_RANDOM = 0x01
    OWN_TYPE = SCAN_RANDOM
    SCAN_TYPE = 0x01


def parse_events(sock, loop_count=100):
    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

    CurrentTime = strftime("%H:%M,%S", gmtime())
    flt = bluez.hci_filter_new()
    bluez.hci_filter_all_events(flt)
    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
    done = False
    results = []
    myFullList = []
    for i in range(0, loop_count):
        pkt = sock.recv(255)
        ptype, event, plen = struct.unpack("BBB", pkt[:3])
        #print "--------------" 
        if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
                i =0
        elif event == bluez.EVT_NUM_COMP_PKTS:
                i =0 
        elif event == bluez.EVT_DISCONN_COMPLETE:
                i =0 
        elif event == LE_META_EVENT:
            subevent, = struct.unpack("B", pkt[3])
            pkt = pkt[4:]
            if subevent == EVT_LE_CONN_COMPLETE:
                le_handle_connection_complete(pkt)
            elif subevent == EVT_LE_ADVERTISING_REPORT:
                #print "advertising report"
                num_reports = struct.unpack("B", pkt[0])[0]
                report_pkt_offset = 0
                for i in range(0, num_reports):

                    if (DEBUS == True):
                        print "-------------"
                        print "\tMAC address: ",        packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
                        TxPower, = struct.unpack("b",  pkt[report_pkt_offset -2])
                        print "\tTxpower:", -TxPower
                        rssi, = struct.unpack("b", pkt[report_pkt_offset -1])
                        print "\tRSSI:", rssi
                        print "\tTime:", CurrentTime
                    # build the return string
                    Adstring = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
                    Adstring += ","
                    Adstring += returnstringpacket(pkt[report_pkt_offset -22: report_pkt_offset - 6])
                    Adstring += ","
                    Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -6: report_pkt_offset - 4])
                    Adstring += ","
                    Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -4: report_pkt_offset - 2])
                    Adstring += ","
                    Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -2])
                    Adstring += ","
                    Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -1])
                    #print "\tAdstring=", Adstring
                    myFullList.append(Adstring)
                done = True
    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
    return myFullList

Full Traceback error: 完全回溯错误:

Traceback (most recent call last):
  File "/home/pi/blescan.py", line 79, in hci_le_set_scan_parameters
    old_filter = socket.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
error: (9, 'Bad file descriptor')

Traceback (most recent call last):
  File "/home/pi/testblescan.py", line 15, in <module>
    blescan.hci_enable_le_scan(socket)
  File "/home/pi/blescan.py", line 67, in hci_enable_le_scan
    hci_toggle_le_scan(socket, 0x01)
  File "/home/pi/blescan.py", line 74, in hci_toggle_le_scan
    bluez.hci_send_cmd(socket, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, cmd_pkt)
error: (9, 'Bad file descriptor')

The output appears to be reporting an OSError, which is accompanied by an error code. 输出似乎正在报告OSError,并伴有错误代码。 This isn't a Python-specific problem, because it is being raised by the underlying operating system. 这不是特定于Python的问题,因为它是由底层操作系统提出的。

You can use the standard library's errno feature to get information about the operating system's error codes. 您可以使用标准库的errno功能来获取有关操作系统错误代码的信息。

You can also ask for the description of an error code via the os.strerror function : 您还可以通过os.strerror函数要求提供错误代码的描述:

import os

os.strerror(9)   # Returns the text value “Bad file descriptor”.

So, something your program is doing makes use of a file descriptor (the integer that represents an input/output stream in the running program) that doesn't actually have a file attached. 因此,您的程序正在执行的操作利用了文件描述符(表示正在运行的程序中输入/输出流的整数),该描述符实际上没有附加文件。 The operating system complains, and Python reports that as an OSError. 操作系统抱怨,Python将其报告为OSError。

You can interrogate the OSError object you catch for its error code (the errno attribute) and what filename was reported (the filename attribute): 您可以查询捕获到的OSError对象的错误代码( errno属性)和报告的filenamefilename属性):

try:
    do_the_thing()
except OSError as exc:
    logger_for_this_program(
            "Got OSError (code {exc.errno:d}, filename {exc.filename})".format(
                exc=exc))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM