1.说明
我自己写了个基于service通信的server和client,以下是srv文件:
song_list_node/srv路径下的SongList.srv
string album
---
string[] song_list
client发送一个string类型的专辑名,server以列表形式返回该专辑下的所有歌曲。
2.song_list_server.py
#!/usr/bin/env python
import os
import rospy
from song_list_node.srv import SongList
def song_list_server():
rospy.init_node('song_list_server_node') # define the node name
# define the service name, the type of srv and the callback
s = rospy.Service('song_list', SongList, callback)
rospy.spin()
def callback(req):
print 'request for song list of the album: %s' % req.album
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../document/', req.album)
# print file_path
with open(file_path, 'r') as f:
content = f.readlines()
# print content
return SongListResponse(content)
if __name__ == '__main__':
song_list_server()
3.song_list_client.py
#!/usr/bin/env python
import sys
import rospy
from song_list_node.srv import *
def song_list_client(param):
rospy.wait_for_service('song_list')
try:
get_song_list = rospy.ServiceProxy('song_list', SongList) # connect with the server
resp = get_song_list(param)
songs = resp.song_list
for song in songs:
print song
except rospy.ServiceException,e:
print 'service call failed: %s' % e
if __name__ == '__main__':
if len(sys.argv) == 2:
song_list_client(sys.argv[1])
else:
print sys.argv
4.运行出错
server端一片飘红:NameError: global name ‘SongListResponse’ is not defined
5.解决方案
其实我也不知道为什么会报这个错,自己找了半天没发现有什么问题,最后求助于
https://answers.ros.org/questions/
找到相似问题:
https://answers.ros.org/question/259488/the-terminator-report-name-error-global-name-addtwointsresponse-is-not-defined/
把song_list_server.py中的
from song_list_node.srv import SongList
改成了
from song_list_node.srv import *
结果成功运行。。。
不知道为啥