本文整理汇总了Python中xmlrpc.client.ServerProxy.getPid方法的典型用法代码示例。如果您正苦于以下问题:Python ServerProxy.getPid方法的具体用法?Python ServerProxy.getPid怎么用?Python ServerProxy.getPid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xmlrpc.client.ServerProxy
的用法示例。
在下文中一共展示了ServerProxy.getPid方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pingNode
# 需要导入模块: from xmlrpc.client import ServerProxy [as 别名]
# 或者: from xmlrpc.client.ServerProxy import getPid [as 别名]
def pingNode(node_name):
max_count=None
ID = '/rosnode'
master = rosgraph.Master(ID)
node_api = rosnode.get_api_uri(master,node_name)
if not node_api:
return False
timeout = 3.
socket.setdefaulttimeout(timeout)
node = ServerProxy(node_api)
lastcall = 0.
count = 0
acc = 0.
try:
while True:
try:
start = time.time()
pid = _succeed(node.getPid(ID))
end = time.time()
dur = (end-start)*1000.
acc += dur
count += 1
# 1s between pings
except socket.error as e:
# 3786: catch ValueError on unpack as socket.error is not always a tuple
try:
# #3659
errnum, msg = e
if errnum == -2: #name/service unknown
p = urlparse.urlparse(node_api)
elif errnum == errno.ECONNREFUSED:
# check if node url has changed
new_node_api = rosnode.get_api_uri(master,node_name, skip_cache=True)
if not new_node_api:
return False
if new_node_api != node_api:
node_api = new_node_api
node = ServerProxy(node_api)
continue
else:
pass
return False
except ValueError:
pass
if max_count and count >= max_count:
break
time.sleep(1.0)
except KeyboardInterrupt:
pass
return True
示例2: get_node_connection_info_description
# 需要导入模块: from xmlrpc.client import ServerProxy [as 别名]
# 或者: from xmlrpc.client.ServerProxy import getPid [as 别名]
def get_node_connection_info_description(node_api, master):
#turn down timeout on socket library
socket.setdefaulttimeout(5.0)
node = ServerProxy(node_api)
system_state = master.getSystemState()
try:
pid = _succeed(node.getPid(ID))
buff = "Pid: %s\n"%pid
#master_uri = _succeed(node.getMasterUri(ID))
businfo = _succeed(node.getBusInfo(ID))
if businfo:
buff += "Connections:\n"
for info in businfo:
dest_id = info[1]
direction = info[2]
transport = info[3]
topic = info[4]
if len(info) > 5:
connected = info[5]
else:
connected = True #backwards compatibility
if connected:
buff += " * topic: %s\n"%topic
# older ros publisher implementations don't report a URI
buff += " * to: %s\n"%lookup_uri(master, system_state, topic, dest_id)
if direction == 'i':
buff += " * direction: inbound\n"
elif direction == 'o':
buff += " * direction: outbound\n"
else:
buff += " * direction: unknown\n"
buff += " * transport: %s\n"%transport
return buff
except socket.error:
raise ROSNodeIOException("Communication with node[%s] failed!"%(node_api))
return buff
示例3: getROSNodes
# 需要导入模块: from xmlrpc.client import ServerProxy [as 别名]
# 或者: from xmlrpc.client.ServerProxy import getPid [as 别名]
def getROSNodes(self):
nodes = []
try:
nodenames = rosnode.get_node_names(None)
except Exception as inst:
print "ERROR:[getROSNodes-01] ", inst
return nodes
for nodename in nodenames:
#rosnode.rosnode_info(nodename)
api = rosnode.get_api_uri(rosgraph.Master("/rosnode"), nodename)
if api:
try:
node = ServerProxy(api)
code, msg, pid = node.getPid("/rosnode")
if code == 1:
res = re.search("^(.*)_[0-9]+$", nodename)
while res is not None:
nodename = res.group(1)
res = re.search("^(.*)_[0-9]+$", nodename)
nodes.append((nodename, pid))
except:
pass
return nodes
示例4: rosnode_ping
# 需要导入模块: from xmlrpc.client import ServerProxy [as 别名]
# 或者: from xmlrpc.client.ServerProxy import getPid [as 别名]
def rosnode_ping(node_name, max_count=None, verbose=False):
"""
Test connectivity to node by calling its XMLRPC API
@param node_name: name of node to ping
@type node_name: str
@param max_count: number of ping requests to make
@type max_count: int
@param verbose: print ping information to screen
@type verbose: bool
@return: True if node pinged
@rtype: bool
@raise ROSNodeIOException: if unable to communicate with master
"""
master = rosgraph.Master(ID)
node_api = get_api_uri(master,node_name)
if not node_api:
print("cannot ping [%s]: unknown node"%node_name, file=sys.stderr)
return False
timeout = 3.
if verbose:
print("pinging %s with a timeout of %ss"%(node_name, timeout))
socket.setdefaulttimeout(timeout)
node = ServerProxy(node_api)
lastcall = 0.
count = 0
acc = 0.
try:
while True:
try:
start = time.time()
pid = _succeed(node.getPid(ID))
end = time.time()
dur = (end-start)*1000.
acc += dur
count += 1
if verbose:
print("xmlrpc reply from %s\ttime=%fms"%(node_api, dur))
# 1s between pings
except socket.error as e:
# 3786: catch ValueError on unpack as socket.error is not always a tuple
try:
# #3659
errnum, msg = e.args
if errnum == -2: #name/service unknown
p = urlparse.urlparse(node_api)
print("ERROR: Unknown host [%s] for node [%s]"%(p.hostname, node_name), file=sys.stderr)
elif errnum == errno.ECONNREFUSED:
# check if node url has changed
new_node_api = get_api_uri(master,node_name, skip_cache=True)
if not new_node_api:
print("cannot ping [%s]: unknown node"%node_name, file=sys.stderr)
return False
if new_node_api != node_api:
if verbose:
print("node url has changed from [%s] to [%s], retrying to ping"%(node_api, new_node_api))
node_api = new_node_api
node = ServerProxy(node_api)
continue
print("ERROR: connection refused to [%s]"%(node_api), file=sys.stderr)
else:
print("connection to [%s] timed out"%node_name, file=sys.stderr)
return False
except ValueError:
print("unknown network error contacting node: %s"%(str(e)))
if max_count and count >= max_count:
break
time.sleep(1.0)
except KeyboardInterrupt:
pass
if verbose and count > 1:
print("ping average: %fms"%(acc/count))
return True
示例5: SlaveTestCase
# 需要导入模块: from xmlrpc.client import ServerProxy [as 别名]
# 或者: from xmlrpc.client.ServerProxy import getPid [as 别名]
class SlaveTestCase(TestRosClient):
def setUp(self):
super(SlaveTestCase, self).setUp()
# retrieve handle on node
self.caller_id = rospy.get_caller_id()
self.node_api = self.apiSuccess(self.master.lookupNode(self.caller_id, 'test_node'))
self.assert_(self.node_api.startswith('http'))
self.node = ServerProxy(self.node_api)
def testGetPid(self):
pid = self.apiSuccess(self.node.getPid(self.caller_id))
self.assert_(pid > 0)
def testGetPublications(self):
publications = self.apiSuccess(self.node.getPublications(self.caller_id))
self.assert_(publications is not None)
expected = [rospy.resolve_name(t) for t in _required_publications]
missing = set(expected) - set(publications)
self.failIf(len(missing), 'missing required topics: %s'%(','.join(missing)))
def _subTestSourceRequestFlow(self, testName, protocols, testEval):
master = self.master
tests = [
[['testSourceRequestFlow-%s-nodeA','testSourceRequestFlow-%s-nodeB',],
['node', 'testSourceRequestFlow-%s-nodeA.out', 'testSourceRequestFlow-%s-nodeB.in']],
[['g1.testSourceRequestFlow-%s-nodeA','g1.testSourceRequestFlow-%s-nodeB',],
['g1.node', 'testSourceRequestFlow-%s-nodeA.out', 'testSourceRequestFlow-%s-nodeB.in']],
[['g1.g2.g3.testSourceRequestFlow-%s-nodeA','g1.g2.testSourceRequestFlow-%s-nodeB',],
['g1.g2.node', 'g3.testSourceRequestFlow-%s-nodeA.out', 'testSourceRequestFlow-%s-nodeB.in']],
[['g1.g2.testSourceRequestFlow-%s-nodeA','g1.g2.g3.testSourceRequestFlow-%s-nodeB',],
['g1.g2.node', 'testSourceRequestFlow-%s-nodeA.out', 'g3.testSourceRequestFlow-%s-nodeB.in']],
]
sources = {}
#start the nodes
# - save the source as we will be making calls on it
pkg, node = testNode
for test in tests:
sourceName, sinkName = [val%testName for val in test[0]]
port = apiSuccess(master.addNode('', '', sourceName, pkg, node, TEST_MACHINE, 0))
apiSuccess(master.addNode('', '', sinkName, pkg, node, TEST_MACHINE, 0))
sourceUri = 'http://%s:%s/'%(testNodeAddr[0], port)
sources[sourceName] = ServerProxy(sourceUri)
for test in tests:
sourceName, sinkName = [val%testName for val in test[0]]
source = sources[sourceName]
callerId = test[1][0]
sourceLocator, sinkLocator = [val%testName for val in test[1][1:]]
args = source.sourceRequestFlow(callerId, sourceLocator, sinkLocator, protocols)
testEval(args)
#TODO: test locator name resolution
def testSourceRequestFlow_TCPROS1(self):
def testEval(args):
protocol = apiSuccess(args)
assert type(protocol) == list
assert string.upper(protocol[0]) == 'TCPROS', "source should have returned TCPROS as the desired protocol"
assert len(protocol) == 3, "TCPROS parameter spec should be length 3"
protocols = [['TCPROS']]
self._subTestSourceRequestFlow('TCPROS1', protocols, testEval)
def testSourceRequestFlow_TCPROS2(self):
def testEval(args):
protocol = apiSuccess(args)
assert type(protocol) == list
assert string.upper(protocol[0]) == 'TCPROS', "source should have returned TCPROS as the desired protocol"
assert len(protocol) == 3, "TCPROS parameter spec should be length 3"
protocols = [['Fake1', 123, 132], ['Fake2', 1.0], ['Fake3'], ['Fake4', 'string'], ['Fake5', ['a', 'list'], ['a', 'nother', 'list']], ['TCPROS'], ['Fakelast', 'fake'] ]
self._subTestSourceRequestFlow('TCPROS2', protocols, testEval)
def testSourceRequestFlow_Fail(self):
protocols = [['Fake1', 123, 132], ['Fake2', 1.0], ['Fake3'], ['Fake4', 'string'], ['Fake5', ['a', 'list'], ['a', 'nother', 'list']], ['Fakelast', 'fake'] ]
self._subTestSourceRequestFlow('Fail', protocols, apiFail)
def testSourceRequestFlow_Errors(self):
slave = self.slave
master = self.master
#test that malformed locators return error codes
apiError(slave.sourceRequestFlow('', '', ''))
apiError(slave.sourceRequestFlow('', 'good.locator', 'badlocator'))
apiError(slave.sourceRequestFlow('', 'badlocator', 'good.locator'))
# sourceKillFlow(callerId, sourceLocator, sinkLocator)
#
# * called by master
# * returns int
def testSourceKillFlow(self):
slave = self.slave
master = self.master
#test that malformed locators return error codes
apiError(slave.sourceKillFlow('', '', ''))
apiError(slave.sourceKillFlow('', 'good.locator', 'badlocator'))
apiError(slave.sourceKillFlow('', 'badlocator', 'good.locator'))
tests = [
[['testSourceKillFlow-nodeA','testSourceKillFlow-nodeB',],
['node', 'testSourceKillFlow-nodeA.out', 'testSourceKillFlow-nodeB.in']],
[['g1.testSourceKillFlow-nodeA','g1.testSourceKillFlow-nodeB',],
#.........这里部分代码省略.........
示例6: TestSlaveApi
# 需要导入模块: from xmlrpc.client import ServerProxy [as 别名]
# 或者: from xmlrpc.client.ServerProxy import getPid [as 别名]
class TestSlaveApi(unittest.TestCase):
def __init__(self, *args, **kwds):
super(TestSlaveApi, self).__init__(*args)
self.ns = os.environ.get(rosgraph.ROS_NAMESPACE, rosgraph.names.GLOBALNS)
# load in name of test node
self.test_node = 'test_node' #default
self.required_pubs = TopicDescriptionList([])
self.required_subs = TopicDescriptionList([])
for arg in sys.argv:
if arg.startswith("--node="):
self.test_node = arg[len("--node="):]
if arg.startswith("--profile="):
self.test_node_profile = arg[len("--profile="):]
self.load_profile(self.test_node_profile)
# resolve
self.test_node = rosgraph.names.ns_join(self.ns, self.test_node)
def load_profile(self, filename):
import yaml
with open(filename) as f:
d = yaml.load(f)
self.required_pubs = d.get('pubs', {})
self.required_subs = d.get('subs', {})
def setUp(self):
self.caller_id = CALLER_ID
# retrieve handle on node
# give ourselves 10 seconds for node to appear
timeout_t = 10.0 + time.time()
self.node_api = None
self.master = rosgraph.Master(self.caller_id)
while time.time() < timeout_t and not self.node_api:
try:
self.node_api = self.master.lookupNode(self.test_node)
except:
time.sleep(0.1)
if not self.node_api:
self.fail("master did not return XML-RPC API for [%s, %s]"%(self.caller_id, self.test_node))
print "[%s] API = %s"%(self.test_node, self.node_api)
self.assert_(self.node_api.startswith('http'))
self.node = ServerProxy(self.node_api)
# hack: sleep for a couple seconds just in case the node is
# still registering with the master.
time.sleep(2.)
def apiSuccess(self, args):
"""
unit test assertion that fails if status code is not 1 and otherwise returns the value parameter.
@param args: returnv value from ROS API call
@type args: [int, str, val]
@return: value parameter from args (arg[2] for master/slave API)
"""
self.assert_(len(args) == 3, "invalid API return value triplet: %s"%str(args))
self.last_code, self.last_msg, self.last_val = args
assert self.last_code == 1, "status code is not 1: %s"%self.last_msg
return self.last_val
def apiFail(self, args):
"""
unit test assertions that fails if status code is not 0 and otherwise returns true.
@param args: returnv value from ROS API call
@type args: [int, str, val]
@return: True if status code is 0
"""
self.assert_(len(args) == 3, "invalid API return value triplet: %s"%str(args))
self.last_code, self.last_msg, self.last_val = args
assert self.last_code == 0, "Call should have failed with status code 0: %s"%self.last_msg
def apiError(self, args, msg=None):
"""
unit test assertion that fails if status code is not -1 and otherwise returns true.
@param args: returnv value from ROS API call
@type args: [int, str, val]
@return: True if status code is -1
"""
self.assert_(len(args) == 3, "invalid API return value triplet: %s"%str(args))
self.last_code, self.last_msg, self.last_val = args
if msg:
assert self.last_code == -1, "%s (return msg was %s)"%(msg, self.last_msg)
else:
assert self.last_code == -1, "Call should have returned error -1 code: %s"%self.last_msg
def check_uri(self, uri):
"""
validates a URI as being http(s)
"""
import urlparse
parsed = urlparse.urlparse(uri)
self.assert_(parsed[0] in ['http', 'https'], 'protocol [%s] is [%s] invalid'%(parsed[0], uri))
self.assert_(parsed[1], 'host missing [%s]'%uri)
self.assert_(parsed.port, 'port missing/invalid [%s]'%uri)
def test_getPid(self):
"""
#.........这里部分代码省略.........
示例7: Master
# 需要导入模块: from xmlrpc.client import ServerProxy [as 别名]
# 或者: from xmlrpc.client.ServerProxy import getPid [as 别名]
class Master(object):
"""
API for interacting with the ROS master. Although the Master is
relatively simple to interact with using the XMLRPC API, this
abstraction layer provides protection against future updates. It
also provides a streamlined API with builtin return code checking
and caller_id passing.
"""
def __init__(self, caller_id, master_uri=None):
"""
:param caller_id: name of node to use in calls to master, ``str``
:param master_uri: (optional) override default ROS master URI, ``str``
:raises: :exc:`ValueError` If ROS master uri not set properly
"""
if master_uri is None:
master_uri = get_master_uri()
self._reinit(master_uri)
self.caller_id = make_caller_id(caller_id) #resolve
if self.caller_id[-1] == '/':
self.caller_id = self.caller_id[:-1]
def _reinit(self, master_uri):
"""
Internal API for reinitializing this handle to be a new master
:raises: :exc:`ValueError` If ROS master uri not set
"""
if master_uri is None:
raise ValueError("ROS master URI is not set")
# #1730 validate URL for better error messages
try:
parse_http_host_and_port(master_uri)
except ValueError:
raise ValueError("invalid master URI: %s"%(master_uri))
self.master_uri = master_uri
self.handle = ServerProxy(self.master_uri)
def is_online(self):
"""
Check if Master is online.
NOTE: this is not part of the actual Master API. This is a convenience function.
@param master_uri: (optional) override environment's ROS_MASTER_URI
@type master_uri: str
@return: True if Master is available
"""
try:
self.getPid()
return True
except:
return False
def _succeed(self, args):
"""
Check master return code and return the value field.
@param args: master return value
@type args: (int, str, XMLRPCLegalValue)
@return: value field of args (master return value)
@rtype: XMLRPCLegalValue
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
code, msg, val = args
if code == 1:
return val
elif code == -1:
raise Error(msg)
else:
raise Failure(msg)
################################################################################
# PARAM SERVER
def deleteParam(self, key):
"""
Parameter Server: delete parameter
@param key: parameter name
@type key: str
@return: 0
@rtype: int
"""
return self._succeed(self.handle.deleteParam(self.caller_id, key))
def setParam(self, key, value):
"""
Parameter Server: set parameter. NOTE: if value is a
dictionary it will be treated as a parameter tree, where key
is the parameter namespace. For example:::
{'x':1,'y':2,'sub':{'z':3}}
will set key/x=1, key/y=2, and key/sub/z=3. Furthermore, it
will replace all existing parameters in the key parameter
namespace with the parameters in value. You must set
parameters individually if you wish to perform a union update.
#.........这里部分代码省略.........