在 Python 中存储回调函数的值
Store value of a callback function in Python
我正在尝试存储回调函数的内容,以便在脚本中访问和操作数据。
就我而言,下面代码中的给定函数 .subscribe()
没有 return 任何东西 (None
)。我的函数仅作为函数的引用作为参数传递。有没有办法 return 来自调用我函数的函数的数据?
我的代码是 roslibpy 的一个简单示例(与开源机器人框架 交互的 Python 库ROS 通过 Websockets)。有人提到,每次将消息发布到主题 /turtle1/pose 时,数据都会通过 Websocket 作为流发布。我的目标是 return 将发布到主题中的数据。打印命令提供了一个很好的数据可视化效果,效果很好。
import roslibpy
client = roslibpy.Ros(host='localhost', port=9090)
client.run()
def myfunc(msg):
print(msg)
listener = roslibpy.Topic(client, '/turtle1/pose', 'turtlesim/Pose')
#my function is passed as an argument
listener.subscribe(myfunc)
try:
while True:
pass
except KeyboardInterrupt:
client.terminate()
roslibpy库中的subscribe()
方法定义如下:
def subscribe(self, callback):
"""Register a subscription to the topic.
Every time a message is published for the given topic,
the callback will be called with the message object.
Args:
callback: Function to be called when messages of this topic are published.
"""
# Avoid duplicate subscription
if self._subscribe_id:
return
self._subscribe_id = 'subscribe:%s:%d' % (
self.name, self.ros.id_counter)
self.ros.on(self.name, callback)
self._connect_topic(Message({
'op': 'subscribe',
'id': self._subscribe_id,
'type': self.message_type,
'topic': self.name,
'compression': self.compression,
'throttle_rate': self.throttle_rate,
'queue_length': self.queue_length
}))
是否有处理此类问题的通用方法?将输出存储为外部源(例如 .txt)然后通过脚本访问源是否更有意义?
您可以定义一个像函数一样运行的 Python class,通过定义神奇的 __call__
方法,它可以在调用时修改自己的状态。当 obj(whatever)
在非函数 obj
上完成时,Python 将 运行 obj.__call__(whatever)
。 subscribe
只需要它的输入是可调用的;它是实际函数还是具有 __call__
方法的对象与 subscribe
.
无关
这是您可以执行的操作的示例:
class MessageRecorder():
def __init__(self):
self.messages = []
# Magic python 'dunder' method
# Whenever a MessageRecorder is called as a function
# This function defined here will be called on it
# In this case, adds the message to a list of received messages
def __call__(self, msg):
self.messages.append(msg)
recorder = MessageRecorder()
# recorder can be called like a function
recorder("Hello")
listener.subscribe(recorder)
try:
while True:
pass
except KeyboardInterrupt:
client.terminate()
"""Now you can do whatever you'd like with recorder.messages,
which contains all messages received before termination,
in order of reception. If you wanted to print all of them, do:"""
for m in recorder.messages:
print(m)
我正在尝试存储回调函数的内容,以便在脚本中访问和操作数据。
就我而言,下面代码中的给定函数 .subscribe()
没有 return 任何东西 (None
)。我的函数仅作为函数的引用作为参数传递。有没有办法 return 来自调用我函数的函数的数据?
我的代码是 roslibpy 的一个简单示例(与开源机器人框架 交互的 Python 库ROS 通过 Websockets)。有人提到,每次将消息发布到主题 /turtle1/pose 时,数据都会通过 Websocket 作为流发布。我的目标是 return 将发布到主题中的数据。打印命令提供了一个很好的数据可视化效果,效果很好。
import roslibpy
client = roslibpy.Ros(host='localhost', port=9090)
client.run()
def myfunc(msg):
print(msg)
listener = roslibpy.Topic(client, '/turtle1/pose', 'turtlesim/Pose')
#my function is passed as an argument
listener.subscribe(myfunc)
try:
while True:
pass
except KeyboardInterrupt:
client.terminate()
roslibpy库中的subscribe()
方法定义如下:
def subscribe(self, callback):
"""Register a subscription to the topic.
Every time a message is published for the given topic,
the callback will be called with the message object.
Args:
callback: Function to be called when messages of this topic are published.
"""
# Avoid duplicate subscription
if self._subscribe_id:
return
self._subscribe_id = 'subscribe:%s:%d' % (
self.name, self.ros.id_counter)
self.ros.on(self.name, callback)
self._connect_topic(Message({
'op': 'subscribe',
'id': self._subscribe_id,
'type': self.message_type,
'topic': self.name,
'compression': self.compression,
'throttle_rate': self.throttle_rate,
'queue_length': self.queue_length
}))
是否有处理此类问题的通用方法?将输出存储为外部源(例如 .txt)然后通过脚本访问源是否更有意义?
您可以定义一个像函数一样运行的 Python class,通过定义神奇的 __call__
方法,它可以在调用时修改自己的状态。当 obj(whatever)
在非函数 obj
上完成时,Python 将 运行 obj.__call__(whatever)
。 subscribe
只需要它的输入是可调用的;它是实际函数还是具有 __call__
方法的对象与 subscribe
.
这是您可以执行的操作的示例:
class MessageRecorder():
def __init__(self):
self.messages = []
# Magic python 'dunder' method
# Whenever a MessageRecorder is called as a function
# This function defined here will be called on it
# In this case, adds the message to a list of received messages
def __call__(self, msg):
self.messages.append(msg)
recorder = MessageRecorder()
# recorder can be called like a function
recorder("Hello")
listener.subscribe(recorder)
try:
while True:
pass
except KeyboardInterrupt:
client.terminate()
"""Now you can do whatever you'd like with recorder.messages,
which contains all messages received before termination,
in order of reception. If you wanted to print all of them, do:"""
for m in recorder.messages:
print(m)