python - Python 机器人控制器代码中的 SyntaxError
问题描述
我将approxeng.input.selectbinder用于机器人控制器并
def __init__(self, *requirements, print_events=False, **kwargs):
抛出一个SyntaxError
,特别是print_events
语句。我不明白为什么。这是给出错误的完整代码:
from functools import reduce
from select import select
from threading import Thread
import approxeng.input.sys as sys
from approxeng.input.controllers import *
EV_KEY = 1
EV_REL = 2
EV_ABS = 3
class ControllerResource:
"""
General resource which binds one or more controllers on entry and unbinds the event listening thread on exit.
"""
def __init__(self, *requirements, print_events=True, **kwargs):
"""
Create a new resource to bind and access one or more controllers. If no additional arguments are supplied this
will find the first controller of any kind enabled by the library. Otherwise the requirements must be provided
as a list of ControllerRequirement
:param requirements:
ControllerRequirement instances used, in order, to find and bind controllers. If empty this will
be equivalent to supplying a single unfiltered requirement and will match the first specified controller.
:param print_events:
Defaults to False, if set to True then all events picked up by the binder will be printed to stdout. Use
this when you're trying to figure out what events correspond to what axes and buttons!
:param kwargs:
Any addition keyword arguments are passed to the constructors for the controller classes. This is useful
particularly to specify e.g. dead and hot zone ranges on discovery.
:raises ControllerNotFoundError:
If the requirement can't be satisfied, or no requirements are specified but there aren't any controllers.
"""
self.discoveries = find_matching_controllers(*requirements, **kwargs)
self.unbind = None
self.print_events = print_events
def __enter__(self):
"""
Called on entering the resource block, returns the controller passed into the constructor.
"""
self.unbind = bind_controllers(*self.discoveries, print_events=self.print_events)
if len(self.discoveries) == 1:
return self.discoveries[0].controller
else:
return tuple(discovery.controller for discovery in self.discoveries)
def __exit__(self, exc_type, exc_value, traceback):
"""
Called on resource exit, unbinds the controller, removing the listening thread.
"""
self.unbind()
def bind_controllers(*discoveries, print_events=False):
"""
Bind a controller or controllers to a set of evdev InputDevice instances, starting a thread to keep those
controllers in sync with the state of the hardware.
:param discoveries:
ControllerDiscovery instances specifying the controllers and their associated input devices
:param print_events:
Defaults to False, if set to True then all events picked up by this binder will be printed to stdout
:return:
A function which can be used to stop the event reading thread and unbind from the device
"""
discoveries = list(discoveries)
class SelectThread(Thread):
def __init__(self):
Thread.__init__(self, name='evdev select thread')
self.daemon = True
self.running = True
self.device_to_controller_discovery = {}
for discovery in discoveries:
for d in discovery.devices:
self.device_to_controller_discovery[d.fn] = discovery
self.all_devices = reduce(lambda x, y: x + y, [discovery.devices for discovery in discoveries])
def run(self):
for discovery in discoveries:
discovery.controller.device_unique_name = discovery.name
while self.running:
try:
r, w, x = select(self.all_devices, [], [], 0.5)
for fd in r:
active_device = fd
controller_discovery = self.device_to_controller_discovery[active_device.fn]
controller = controller_discovery.controller
controller_devices = controller_discovery.devices
prefix = None
if controller.node_mappings is not None and len(controller_devices) > 1:
try:
prefix = controller.node_mappings[active_device.name]
except KeyError:
pass
for event in active_device.read():
if print_events:
print(event)
if event.type == EV_ABS or event.type == EV_REL:
controller.axes.axis_updated(event, prefix=prefix)
elif event.type == EV_KEY:
# Button event
if event.value == 1:
# Button down
controller.buttons.button_pressed(event.code, prefix=prefix)
elif event.value == 0:
# Button up
controller.buttons.button_released(event.code, prefix=prefix)
except Exception as e:
self.stop(e)
def stop(self, exception=None):
for discovery in discoveries:
discovery.controller.device_unique_name = None
discovery.controller.exception = exception
self.running = False
polling_thread = SelectThread()
# Force an update of the LED and battery system cache
sys.scan_cache(force_update=True)
for device in polling_thread.all_devices:
device.grab()
def unbind():
polling_thread.stop()
for dev in polling_thread.all_devices:
try:
dev.ungrab()
except IOError:
pass
polling_thread.start()
return unbind
解决方案
最小可重现示例
以下是问题中问题的最小可重现示例:
class ControllerResource:
def __init__(self, *requirements, print_events=True, **kwargs):
pass
使用 Python 3.x 编译得很好(即你可以毫无错误地导入它)。但是使用 Python 2.x 这会引发 SyntaxError:
File "test.py", line 3
def __init__(self, *requirements, print_events=True, **kwargs):
^
SyntaxError: invalid syntax
解释
原因是参数列表print_events=True
在可变参数参数(ie )之后包含一个常规(关键字)参数(ie *requirements
)。
在 Python 3.x 中这是有效的,它将使参数print_events
成为仅关键字参数(有关更多信息和示例,请参阅PEP 3102)。Python 2.x 不支持仅关键字参数,因此上述代码在 Python 2.x 中无效。
解决方案
首先,我强烈建议尽可能使用 Python 3.x,因为 Python 2.x 非常旧,并且在2020 年 1 月 1 日之后不再维护。
但是,如果您出于某种原因确实必须使用 Python 2.x,则可以重新排序该__init__
方法的参数,如下所示:
class ControllerResource:
def __init__(self, print_events=True, *requirements, **kwargs):
pass
推荐阅读
- laravel - Laravel 子关系
- python - ufunc 'add' 不包含签名匹配类型 dtype('
我正在使用 API google Geocoding API 绘制热图来绘制城市。我点击此链接在此处输入链接描述,因为我有相同类型
- javascript - 从表单呈现数据并将其与 API 一起使用
- android - 如何知道依赖项来自哪个远程存储库?
- css - 使用 Perl 发送带有进度条的邮件
- php - 为什么我的 Ajax 联系表没有收到电子邮件?
- dart - 一个人如何实现 150 个动画心在颤动?
- android - 出现“无法找到 ContentProvider 的提供者信息”错误
- php - 使用模型期间的 Codeigniter PHP 框架错误
- java - Firebase 数据库异常:类 java.sql.Timestamp 未定义无参数构造函数