You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pymavlink中通过input()获取type_mask触发ValueError的解决方法

问题原因

直接用int(type_mask)转换带0b前缀的字符串时,Python默认按十进制解析,0b属于非法字符,因此触发ValueError。

两种可行解决方式

方式1:允许用户输入带0b前缀的二进制字符串

利用int()函数的第二个参数0,它会自动识别字符串前缀(0b=二进制、0o=八进制、0x=十六进制)完成转换:

# 获取用户输入的type_mask
type_mask_input = input("请输入type_mask(可带0b前缀的二进制值):")
# 自动识别进制转换为整数
type_mask = int(type_mask_input, 0)

方式2:让用户输入不带0b的纯二进制数字串

指定int()的第二个参数为2,明确按二进制规则解析输入:

# 获取用户输入的type_mask(无需0b前缀)
type_mask_input = input("请输入type_mask的纯二进制数字:")
# 按二进制转换为整数
type_mask = int(type_mask_input, 2)

修改后的完整代码示例

from pymavlink import mavutil

# 建立UDP连接
the_connection = mavutil.mavlink_connection('udpin:localhost:14551')

# 等待心跳包
the_connection.wait_heartbeat()
print("Heartbeat from system (system %u component %u)" %
      (the_connection.target_system, the_connection.target_component))

# 获取用户输入参数(以方式1为例)
while True:
    try:
        type_mask_input = input("请输入type_mask(可带0b前缀的二进制值):")
        type_mask = int(type_mask_input, 0)
        break
    except ValueError:
        print("输入格式错误,请输入有效的二进制值")

x = input("请输入X坐标:")
y = input("请输入Y坐标:")
z = input("请输入Z坐标:")
yaw = input("请输入偏航角:")
yaw_rate = input("请输入偏航角速度:")

# 发送位置控制指令
the_connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_local_ned_message(
    10, the_connection.target_system,
    the_connection.target_component, mavutil.mavlink.MAV_FRAME_LOCAL_NED,
    type_mask, float(x), float(y), float(z),
    0, 0, 0, 0, 0, 0, int(yaw), int(yaw_rate)
))

补充说明

  • 如果只需要二进制输入,优先选方式2,避免用户误输入其他进制值;需要兼容多进制输入则选方式1。
  • 代码中加入了循环校验逻辑,可避免用户输入格式错误导致程序直接崩溃。

内容的提问来源于stack exchange,提问作者Eric Maniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:31:07