python hex()

时间:2018-08-30 06:59:09

标签: python python-2.7 pyusb

我有如下json文件

{
   "devices"  :[
                 {
                 "Manufacturer name": "Sony",
                 "vendor_id":"8087" ,
                 "product_id" : "07da"
                 },
                 {
                 "Manufacturer name": "Sandisk",
                 "vendor_id": "1d6b",
                 "product_id" : "0002"
                 },
                 {
                 "Manufacturer name": "Chicony Electronics",
                 "vendor_id": "04f2",
                 "product_id" : "b381"
                 }
               ]

}

此json文件包含连接到我的笔记本电脑的USB设备的供应商和产品ID。我正在检查USB设备是否已使用此json文件连接到笔记本电脑。供应商和产品ID在hex中。由于json无法使用hex,因此我以字符串格式编写了这些值。我实际上正在使用python的pyusb模块来检查设备的连接性,如下所述

import usb.core
def get_hex(hex_str):
    hex_int = int(hex_str, 16)
    return hex(hex_int)

vendor_id = get_hex("8087")
product_id = get_hex("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)

if dev is None:
    print "Disconnected"
else:
    print "Connected"

但是,当我运行此代码时,我得到的打印消息为"Disconnected" 实际上,这里的问题是usb.core.find()函数需要int中的值,而函数返回的值get_hex()string。将以上代码中的行dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)更改为dev = usb.core.find(idVendor=0x8087, idProduct=0x07da)。上面的代码正常工作。请让我知道如何从get_hex()中的int返回值。

1 个答案:

答案 0 :(得分:2)

问题是您将十六进制字符串转换为int,然后又转换回十六进制字符串。将其转换为int后只需返回即可。而且最好将函数重命名为get_int,因为您只是将其转换为int

def get_int(hex_str):
    return int(hex_str, 16)

vendor_id = get_int("8087")
product_id = get_int("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)