Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 3 compatibility #427

Merged
merged 1 commit into from
Jun 4, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion test/test_rosbag/test/connection_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_connection_count(self):
self.assertEqual(p.returncode, 0, 'Failed to check bag\ncmd=%s\nstdout=%s\nstderr=%s'%(cmd,out,err))

conns = False
for l in out.split('\n'):
for l in out.decode().split('\n'):
f = l.strip().split(': ')
if len(f) == 2 and f[0] == 'connections':
conns = int(f[1])
Expand Down
2 changes: 1 addition & 1 deletion test/test_rosbag/test/topic_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def test_topic_count(self):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = p.communicate()
topic_count = 0
for l in out.split('\n'):
for l in out.decode().split('\n'):
f = l.strip().split(': ')
if len(f) == 2 and f[0] == '- topic':
topic_count += 1
Expand Down
29 changes: 14 additions & 15 deletions test/test_rosparam/test/test_rosparam_command_line_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
import os
import sys
import unittest
import cStringIO
import time

from subprocess import Popen, PIPE, check_call, call
Expand All @@ -57,24 +56,24 @@ def test_cmd_help(self):
sub = ['set', 'get', 'load', 'dump', 'delete', 'list']

output = Popen([cmd], stdout=PIPE).communicate()[0]
self.assert_('Commands' in output, output)
self.assert_('Commands' in output.decode(), output)
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
self.assert_('Commands' in output)
self.assert_('Commands' in output.decode())

for c in sub:
# make sure command is in usage statement
self.assert_("%s %s"%(cmd, c) in output)
self.assert_("%s %s"%(cmd, c) in output.decode())

for c in sub:
output = Popen([cmd, c, '-h'], stdout=PIPE, stderr=PIPE).communicate()
self.assert_("Usage:" in output[0], "%s\n%s"%(output, c))
self.assert_("%s %s"%(cmd, c) in output[0], "%s: %s"%(c, output[0]))
self.assert_("Usage:" in output[0].decode(), "%s\n%s" % (output, c))
self.assert_("%s %s"%(cmd, c) in output[0].decode(), "%s: %s" % (c, output[0].decode()))

# test no args on commands that require args
for c in ['set', 'get', 'load', 'dump', 'delete']:
output = Popen([cmd, c], stdout=PIPE, stderr=PIPE).communicate()
self.assert_("Usage:" in output[0] or "Usage:" in output[1], "%s\n%s"%(output, c))
self.assert_("%s %s"%(cmd, c) in output[1])
self.assert_("Usage:" in output[0].decode() or "Usage:" in output[1].decode(), "%s\n%s"%(output, c))
self.assert_("%s %s"%(cmd, c) in output[1].decode())

def test_offline(self):
cmd = 'rosparam'
Expand All @@ -87,22 +86,22 @@ def test_offline(self):
msg = "ERROR: Unable to communicate with master!\n"

output = Popen([cmd, 'list'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
output = Popen([cmd, 'set', 'foo', '1.0'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
output = Popen([cmd, 'get', 'foo'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
# have to test with actual file to avoid error
path = os.path.join(get_test_path(), 'test.yaml')
output = Popen([cmd, 'load', path], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))

# test with file that does not exist
output = Popen([cmd, 'load', 'fake.yaml'], **kwds).communicate()
self.assertEquals('ERROR: file [fake.yaml] does not exist\n', output[1])
self.assertEquals('ERROR: file [fake.yaml] does not exist\n', output[1].decode())

output = Popen([cmd, 'dump', 'foo.yaml'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
output = Popen([cmd, 'delete', 'foo'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))

19 changes: 10 additions & 9 deletions test/test_rosservice/test/test_rosservice_command_line_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import os
import sys
import unittest
import cStringIO
import time

import rostest
Expand All @@ -52,18 +51,20 @@ def test_cmd_help(self):
sub = ['args', 'info', 'list', 'call', 'type', 'uri', 'find']

output = Popen([cmd], stdout=PIPE).communicate()[0]
output = output.decode()
self.assert_('Commands' in output)
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
output = output.decode()
self.assert_('Commands' in output)
# make sure all the commands are in the usage
for c in sub:
self.assert_("%s %s"%(cmd, c) in output, output)

for c in sub:
output = Popen([cmd, c, '-h'], stdout=PIPE).communicate()
self.assert_("Usage:" in output[0], output)
self.assert_("Usage:" in output[0].decode(), output)
# make sure usage refers to the command
self.assert_("%s %s"%(cmd, c) in output[0], output)
self.assert_("%s %s" % (cmd, c) in output[0].decode(), output)

def test_offline(self):
cmd = 'rosservice'
Expand All @@ -76,18 +77,18 @@ def test_offline(self):
msg = "ERROR: Unable to communicate with master!\n"

output = Popen([cmd, 'list'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
output = Popen([cmd, 'type', 'add_two_ints'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
output = Popen([cmd, 'uri', 'add_two_ints'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
output = Popen([cmd, 'call', 'add_two_ints', '1', '2'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
# - wait should still fail if master is offline
output = Popen([cmd, 'call', '--wait', 'add_two_ints', '1', '2'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))
output = Popen([cmd, 'find', 'test_ros/AddTwoInts'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
self.assert_(output[1].decode().endswith(msg))

if __name__ == '__main__':
rostest.unitrun('test_rosservice', NAME, TestRosserviceOffline, sys.argv, coverage_packages=[])
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def __init__(self, task):

def run(self):
try:
print "STARTING TASK"
print("STARTING TASK")
self.value = self.task()
print "TASK HAS COMPLETED"
print("TASK HAS COMPLETED")
self.success = True
except:
import traceback
Expand All @@ -80,6 +80,7 @@ def test_rosservice(self):
# list
# - hard to exact match as we are still adding builtin services to nodes (e.g. set_logger_level)
output = Popen([cmd, 'list'], stdout=PIPE).communicate()[0]
output = output.decode()
l = set(output.split())
for s in services:
self.assert_(s in l)
Expand Down
5 changes: 2 additions & 3 deletions tools/rosgraph/test/test_rosgraph_command_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import os
import sys
import unittest
import cStringIO
import time

from subprocess import Popen, PIPE, check_call, call
Expand All @@ -48,7 +47,7 @@ def setUp(self):
def test_cmd_help(self):
cmd = 'rosgraph'
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
self.assert_('Usage' in output)
self.assert_('Usage' in output.decode())

def test_offline(self):
cmd = 'rosgraph'
Expand All @@ -61,4 +60,4 @@ def test_offline(self):
msg = "ERROR: Unable to communicate with master!\n"

output = Popen([cmd], **kwds).communicate()
self.assertEquals(msg, output[1])
self.assertEquals(msg, output[1].decode())
36 changes: 20 additions & 16 deletions tools/roslaunch/src/roslaunch/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,17 @@ def namespaces_of(name):
"""
if name is None:
raise ValueError('name')
if not isinstance(name, basestring):
raise TypeError('name')
try:
if not isinstance(name, basestring):
raise TypeError('name')
except NameError:
if not isinstance(name, str):
raise TypeError('name')
if not name:
return ['/']

splits = [x for x in name.split('/') if x]
return ['/'] + ['/'+'/'.join(splits[:i]) for i in xrange(1, len(splits))]
return ['/'] + ['/'+'/'.join(splits[:i]) for i in range(1, len(splits))]

def get_roscore_filename():
# precedence: look for version in /etc/ros. If it's not there, fall back to roslaunch package
Expand Down Expand Up @@ -215,7 +219,7 @@ def assign_machines(self):
# determine whether or not there are any machines we will need
# to setup remote roslaunch clients for
self._remote_nodes_present = False
if [m for m in machine_unify_dict.itervalues() if not is_machine_local(m)]:
if [m for m in machine_unify_dict.values() if not is_machine_local(m)]:
self._remote_nodes_present = True

def summary(self, local=False):
Expand Down Expand Up @@ -254,7 +258,7 @@ def strip_string(value):
namespaces[ns] = [n]
else:
namespaces[ns].append(n)
for k,v in namespaces.iteritems():
for k,v in namespaces.items():
summary += ' %s\n'%k + '\n'.join(sorted([' %s'%_summary_name(n) for n in v]))
summary += '\n'
return summary
Expand Down Expand Up @@ -298,12 +302,12 @@ def add_param(self, p, filename=None, verbose=True):

self.params[key] = p
if verbose:
print "Added parameter [%s]"%key
print("Added parameter [%s]" % key)
t = type(p.value)
if t in [str, unicode, types.InstanceType]:
self.logger.debug("add_param[%s]: type [%s]"%(p.key, t))
else:
if t in [bool, int, float]:
self.logger.debug("add_param[%s]: type [%s] value [%s]"%(p.key, t, p.value))
else:
self.logger.debug("add_param[%s]: type [%s]"%(p.key, t))

def add_machine(self, m, verbose=True):
"""
Expand All @@ -330,7 +334,7 @@ def add_machine(self, m, verbose=True):
else:
self.machines[name] = m
if verbose:
print "Added machine [%s]"%name
print("Added machine [%s]" % name)
return True

def add_test(self, test, verbose=True):
Expand Down Expand Up @@ -362,14 +366,14 @@ def add_node(self, node, core=False, verbose=True):
if not core:
self.nodes.append(node)
if verbose:
print "Added node of type [%s/%s] in namespace [%s]"%(node.package, node.type, node.namespace)
print("Added node of type [%s/%s] in namespace [%s]" % (node.package, node.type, node.namespace))
self.logger.info("Added node of type [%s/%s] in namespace [%s]", node.package, node.type, node.namespace)
else:
if not node.name:
raise RLException("ROS core nodes must have a name. [%s/%s]"%(node.package, node.type))
self.nodes_core.append(node)
if verbose:
print "Added core node of type [%s/%s] in namespace [%s]"%(node.package, node.type, node.namespace)
print("Added core node of type [%s/%s] in namespace [%s]" % (node.package, node.type, node.namespace))
self.logger.info("Added core node of type [%s/%s] in namespace [%s]", node.package, node.type, node.namespace)

def _select_machine(self, node):
Expand Down Expand Up @@ -436,9 +440,9 @@ def load_config_default(roslaunch_files, port, roslaunch_strs=None, loader=None,
try:
logger.info('loading config file %s'%f)
loader.load(f, config, verbose=verbose)
except roslaunch.xmlloader.XmlParseException, e:
except roslaunch.xmlloader.XmlParseException as e:
raise RLException(e)
except roslaunch.loader.LoadException, e:
except roslaunch.loader.LoadException as e:
raise RLException(e)

# we need this for the hardware test systems, which builds up
Expand All @@ -448,9 +452,9 @@ def load_config_default(roslaunch_files, port, roslaunch_strs=None, loader=None,
try:
logger.info('loading config file from string')
loader.load_string(launch_str, config)
except roslaunch.xmlloader.XmlParseException, e:
except roslaunch.xmlloader.XmlParseException as e:
raise RLException('Launch string: %s\nException: %s'%(launch_str, e))
except roslaunch.loader.LoadException, e:
except roslaunch.loader.LoadException as e:
raise RLException('Launch string: %s\nException: %s'%(launch_str, e))

# choose machines for the nodes
Expand Down
30 changes: 20 additions & 10 deletions tools/roslaunch/src/roslaunch/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from __future__ import print_function

"""
Core roslaunch model and lower-level utility routines.
"""
Expand All @@ -39,7 +41,10 @@

import socket
import sys
import xmlrpclib
try:
from xmlrpc.client import MultiCall, ServerProxy
except ImportError:
from xmlrpclib import MultiCall, ServerProxy

import rospkg

Expand Down Expand Up @@ -111,7 +116,7 @@ def printlog(msg):
except:
pass
try: # don't let this bomb out the actual code
print msg
print(msg)
except:
pass

Expand All @@ -127,9 +132,9 @@ def printlog_bold(msg):
pass
try: # don't let this bomb out the actual code
if sys.platform in ['win32']:
print '%s'%msg #windows console is terrifically boring
print('%s' % msg) # windows console is terrifically boring
else:
print '\033[1m%s\033[0m'%msg
print('\033[1m%s\033[0m' % msg)
except:
pass

Expand All @@ -146,7 +151,7 @@ def printerrlog(msg):
# #1003: this has raised IOError (errno 104) in robot use. Better to
# trap than let a debugging routine fault code.
try: # don't let this bomb out the actual code
print >> sys.stderr, '\033[31m%s\033[0m'%msg
print('\033[31m%s\033[0m' % msg, file=sys.stderr)
except:
pass

Expand Down Expand Up @@ -282,15 +287,15 @@ def __eq__(self, m2):

def get(self):
"""
:returns:: XMLRPC proxy for communicating with master, ``xmlrpclib.ServerProxy``
:returns:: XMLRPC proxy for communicating with master, ``xmlrpc.client.ServerProxy``
"""
return xmlrpclib.ServerProxy(self.uri)
return ServerProxy(self.uri)

def get_multi(self):
"""
:returns:: multicall XMLRPC proxy for communicating with master, ``xmlrpclib.MultiCall``
:returns:: multicall XMLRPC proxy for communicating with master, ``xmlrpc.client.MultiCall``
"""
return xmlrpclib.MultiCall(self.get())
return MultiCall(self.get())

def is_running(self):
"""
Expand Down Expand Up @@ -589,7 +594,12 @@ def __init__(self, test_name, package, node_type, name=None, \

self.retry = retry or 0
time_limit = time_limit or TEST_TIME_LIMIT_DEFAULT
if not type(time_limit) in (float, int, long):
number_types = [float, int]
try:
number_types.append(long)
except NameError:
pass
if not type(time_limit) in number_types:
raise ValueError("'time-limit' must be a number")
time_limit = float(time_limit) #force to floating point
if time_limit <= 0:
Expand Down
Loading