在Python中存储回调函数的值 [英] Store value of a callback function in Python

查看:107
本文介绍了在Python中存储回调函数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试存储回调函数的内容,以便访问和操作脚本中的数据.就我而言,下面我的代码中给定的函数 .subscribe()不会返回任何内容( None ).我的函数仅作为对函数的引用作为参数传递.有没有办法从调用我的函数的函数中返回数据?

I am trying to store the content of a callback function, in order to access and manipulate the data within the script. As far as I am concerned, the given function .subscribe() in my code below does not return anything (None). My function is only passed as a reference to the function as an argument. Is there a way to return the data from the function that calls my function?

我的代码是一个带有 roslibpy 的简单示例(用于Python的库,可通过Websockets与开放源代码机器人框架 ROS 进行交互).提到每次将消息发布到主题/turtle1/pose 中时,数据都会通过Websocket作为流发布.我的目标是返回正在发布到主题中的数据.print命令提供了很好的数据可视化效果,效果很好.

My code is a simple example with roslibpy (a library for Python that interacts with the open-source robotics framework ROS through Websockets). It is mentioned, that the data is published as a stream via a Websocket each time a message is published into the topic /turtle1/pose. My goal here is to return the data that is being published into the topic. The print command provides a nice visualization of the data, which just works fine.

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()方法定义如下:

The subscribe() method in the roslibpy library is defined as follows:

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 ),然后通过脚本访问源是否更有意义?

Is there common way to deal with such problems? Does it make more sense to store the output as an external source (e.g. .txt) and then access the source trough the script?

推荐答案

您可以定义一个类似于函数的Python类,通过定义魔术 __ call __ 可以在调用时修改其自身状态.方法.当对非功能性 obj 执行 obj(whatever)时,Python将运行 obj .__ call __(whatever). subscribe 仅需要其输入可调用;不管是实际函数还是具有 __ call __ 方法的对象,对于 subscribe 而言都无关紧要.

You can define a Python class that acts like a function, that can modify its own state when called, by defining the magic __call__ method. When obj(whatever) is done on a non-function obj, Python will run obj.__call__(whatever). subscribe only needs its input to be callable; whether it is an actual function or an object with a __call__ method does not matter to subscribe.

这是您可以做什么的一个示例:

Here's an example of what you could do:

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)

这篇关于在Python中存储回调函数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆