Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rosbag record from python node
#!/usr/bin/env python
import rospy
import subprocess
import os
import signal
class RosbagRecord:
def __init__(self):
if rospy.has_param('~record_script') and rospy.has_param('~record_folder'):
self.record_script = rospy.get_param('~record_script')
self.record_folder = rospy.get_param('~record_folder')
rospy.on_shutdown(self.stop_recording_handler)
# Start recording.
command = "source " + self.record_script
self.p = subprocess.Popen(command, stdin=subprocess.PIPE, shell=True, cwd=self.record_folder,
executable='/bin/bash')
# Wait for shutdown signal to close rosbag record
rospy.spin()
else:
rospy.signal_shutdown(rospy.get_name() + ' no record script or folder specified.')
def terminate_ros_node(self, s):
# Adapted from http://answers.ros.org/question/10714/start-and-stop-rosbag-within-a-python-script/
list_cmd = subprocess.Popen("rosnode list", shell=True, stdout=subprocess.PIPE)
list_output = list_cmd.stdout.read()
retcode = list_cmd.wait()
assert retcode == 0, "List command returned %d" % retcode
for str in list_output.split("\n"):
if (str.startswith(s)):
os.system("rosnode kill " + str)
def stop_recording_handler(self):
rospy.loginfo(rospy.get_name() + ' stop recording.')
self.terminate_ros_node("/record")
if __name__ == '__main__':
rospy.init_node('rosbag_record')
rospy.loginfo(rospy.get_name() + ' start')
# Go to class functions that do all the heavy lifting. Do error checking.
try:
rosbag_record = RosbagRecord()
except rospy.ROSInterruptException:
pass
@Pizza-Galaxy
Copy link

Pizza-Galaxy commented Nov 3, 2020

Hi, I'm pretty new to ROS and i'm trying to do exactly what this program is aiming to do, but I'm not sure to understand how to use it. Can I use this to record any topics on my ROS server or it requires a specific node? Thanks anyway.

@marco-tranzatto
Copy link
Author

marco-tranzatto commented Nov 4, 2020

Hi there,

You can use this script as a ros node (see tutorial for python nodes) to record a list of topics you are interested int.

You need to provide two parameters: record_folder which is the path where you want your rosbag to be recorded, and record_script which is the path of your record bash script (this is simply a bash script with the command rosbag record and the list of topics you want to record).

I hope this helps,
Marco

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment