The publisher in the rospy publisher and subscriber tutorial demonstrates how to do this: your infinite loop needs to check rospy.is_shutdown():
while not rospy.is_shutdown():