ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Referencing constants in .srv from Python

asked 2016-04-14 02:14:16 -0600

KenYN gravatar image

Given the file:

  • foo.srv

    string service_name = foo_service
    string in
    string out

In my C++ code, my_project::foo::Request::service_name works as expected, but how do I do this in Python? I do:

from my_project.srv import foo

at the head of the file, but in the code foo.service_name, fooRequest.service_name, foo.fooRequest.service_name all fail. I can see service_name = 'foo_service' in the generated file, so I think it's a problem in my code, not my build process.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2016-04-14 08:00:20 -0600

lucasw gravatar image

I looked on my system for some example services with constants:

/opt/ros/jade/share$ grep -r "=" * | grep \\.srv
gazebo_msgs/srv/GetJointProperties.srv:uint8 FIXED       = 3                # 0 DOF


$ rossrv show GetJointProperties
string joint_name
uint8 REVOLUTE=0
uint8 FIXED=3
uint8 BALL=4

So it was in the response.

In python:

from gazebo_msgs.srv import GetJointPropertiesResponse
print GetJointPropertiesResponse.FIXED


from gazebo_msgs.srv import GetJointProperties
print GetJointProperties._response_class.FIXED

And the output is 3 as expected. I didn't find an existing example with a string constant so tried adding my own, and it also worked the same.

This shows what is in the class:

print GetJointPropertiesResponse.__dict__.keys()
['_type', 'BALL', '_has_header', 'PRISMATIC', '_slot_types', 'CONTINUOUS', '__module__', 'rate', 'serialize', 'FIXED', '__init__', 'deserialize_numpy', 'success', 'deserialize', 'type', 'UNIVERSAL', '_full_text', '_md5sum', '__doc__', '_get_types', '__slots__', 'damping', 'REVOLUTE', 'position', 'status_message', 'serialize_numpy']
edit flag offensive delete link more


Thank you; _response_class was the magic I was missing.

KenYN gravatar image KenYN  ( 2016-04-14 19:20:55 -0600 )edit

answered 2018-07-14 11:22:35 -0600

CoffeeKangaroo gravatar image

Even if this is an old question I wanted to answer it since I came across the same problem.

According to the PyStyleGuide is a protected member of the class, thus accessing this is not the way it is meant to be.

A cleaner way to access the constants (IMHO) is to include the classes which are accessed with the _request_class and _response_class members.

In the example given above this would be:

from my_package.srv include MySrv
from my_package.srv include MySrvRequest
from my_package.srv include MySrvResponse

# Do something with:
edit flag offensive delete link more

Question Tools

1 follower


Asked: 2016-04-14 02:14:16 -0600

Seen: 2,107 times

Last updated: Jul 14 '18