我正在使用 cwiid 库,这是一个用 C 编写的库,但在 python 中使用。该库允许我使用 Wiimote 来控制机器人上的一些电机。该代码在没有监视器、键盘或鼠标的嵌入式设备上作为守护程序运行。
当我尝试初始化对象时:
import cwiid
while True:
try:
wm = cwiid.Wiimote()
except RuntimeError:
# RuntimeError exception thrown if no Wiimote is trying to connect
# Wait a second
time.sleep(1)
# Try again
continue
99% 的时间,一切正常,但有时,库会进入某种奇怪的状态,调用cwiid.Wiimote()
导致库将“套接字连接错误(控制通道)”写入标准错误,并且 python 抛出异常. 发生这种情况时,每次后续调用都会cwiid.Wiimote()
导致将相同的内容写入 stderr,并引发相同的异常,直到我重新启动设备。
我想要做的是检测到这个问题,并让 python 自动重启设备。
如果 cwiid 库处于怪异状态,它抛出的异常类型也是RuntimeError
,这与连接超时异常(这很常见)没有什么不同,所以我似乎无法以这种方式区分它。我要做的是在运行后立即读取 stderrcwiid.Wiimote()
以查看是否出现消息“套接字连接错误(控制通道)”,如果出现,则重新启动。
到目前为止,我可以使用一些os.dup()
和os.dup2()
方法重定向stderr以防止消息出现,但这似乎并不能帮助我阅读stderr。
如果您使用子进程运行某些东西,则大多数在线示例都涉及读取 stderr,这在这种情况下不适用。
我怎么能去阅读 stderr 来检测写入它的消息?
我想我正在寻找的是这样的:
while True:
try:
r, w = os.pipe()
os.dup2(sys.stderr.fileno(), r)
wm = cwiid.Wiimote()
except RuntimeError:
# RuntimeError exception thrown if no Wiimote is trying to connect
if ('Socket connect error (control channel)' in os.read(r, 100)):
# Reboot
# Wait a second
time.sleep(1)
# Try again
continue
这似乎并不像我认为的那样起作用。