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

Python3调用LinuxCNC库报错:poll方法返回NULL未设置异常

LinuxCNC Python脚本报错:method 'poll' of 'linuxcnc.stat' objects> returned NULL without setting an exception

问题详情

使用LinuxCNC库编写Python3脚本尝试控制轴回零,代码如下:

import time
import linuxcnc

i = 0
s = linuxcnc.stat()
while i < 3:
  try:
    r = s.poll()
    print('homed=', getattr(s, 'homed'))
    c = linuxcnc.command()
    c.abort()
    c.mode(linuxcnc.MODE_MANUAL)
    c.wait_complete()
    c.home(i)
  except Exception as detail:
    print("Error:", detail)
  i += 1
  time.sleep(2)  # Wait for 2 second

运行时触发报错:

method 'poll' of 'linuxcnc.stat' objects> returned NULL without setting an exception

解决方法

  • 初始化stat对象:linuxcnc.stat()实例必须先调用new()方法完成初始化,否则poll()无法正常与LinuxCNC服务通信。修改stat对象创建代码:
    s = linuxcnc.stat()
    s.new()  # 新增初始化步骤
    
  • 优化command对象创建:无需在每次循环中创建新的linuxcnc.command()实例,将其移到循环外,减少资源开销。
  • 直接访问stat属性:无需使用getattr(),可以直接通过s.homed获取轴回零状态,代码更简洁。

修改后的完整代码:

import time
import linuxcnc

i = 0
s = linuxcnc.stat()
s.new()  # 初始化stat对象
c = linuxcnc.command()  # 一次性创建command对象

while i < 3:
  try:
    poll_result = s.poll()
    if poll_result == -1:
      print("无法获取状态数据")
      continue
    print('homed=', s.homed)
    c.abort()
    c.mode(linuxcnc.MODE_MANUAL)
    c.wait_complete()
    c.home(i)
  except Exception as detail:
    print("Error:", detail)
  i += 1
  time.sleep(2)
  • 环境检查:确保LinuxCNC服务已启动,且运行脚本的用户拥有足够权限(建议以root身份或加入linuxcnc用户组执行)。

内容的提问来源于stack exchange,提问作者9me

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 14:25:07