本文整理匯總了Python中krpc.types.Types.coerce_to方法的典型用法代碼示例。如果您正苦於以下問題:Python Types.coerce_to方法的具體用法?Python Types.coerce_to怎麽用?Python Types.coerce_to使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類krpc.types.Types
的用法示例。
在下文中一共展示了Types.coerce_to方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_coerce_to
# 需要導入模塊: from krpc.types import Types [as 別名]
# 或者: from krpc.types.Types import coerce_to [as 別名]
def test_coerce_to(self):
types = Types()
cases = [
(42.0, 42, 'double'),
(42.0, 42, 'float'),
(42, 42.0, 'int32'),
(42, 42L, 'int32'),
(42L, 42.0, 'int64'),
(42L, 42, 'int64'),
(42, 42.0, 'uint32'),
(42, 42L, 'uint32'),
(42L, 42.0, 'uint64'),
(42L, 42, 'uint64'),
(list(), tuple(), 'List(string)'),
((0,1,2), [0,1,2], 'Tuple(int32,int32,int32)'),
([0,1,2], (0,1,2), 'List(int32)'),
]
for expected, value, typ in cases:
coerced_value = types.coerce_to(value, types.as_type(typ))
self.assertEqual(expected, coerced_value)
self.assertEqual(type(expected), type(coerced_value))
self.assertEqual(['foo','bar'], types.coerce_to(['foo','bar'], types.as_type('List(string)')))
self.assertRaises(ValueError, types.coerce_to, None, types.as_type('float'))
self.assertRaises(ValueError, types.coerce_to, '', types.as_type('float'))
self.assertRaises(ValueError, types.coerce_to, True, types.as_type('float'))
self.assertRaises(ValueError, types.coerce_to, list(), types.as_type('Tuple(int32)'))
self.assertRaises(ValueError, types.coerce_to, ["foo",2], types.as_type('Tuple(string)'))
self.assertRaises(ValueError, types.coerce_to, [1], types.as_type('Tuple(string)'))
示例2: test_coerce_to
# 需要導入模塊: from krpc.types import Types [as 別名]
# 或者: from krpc.types.Types import coerce_to [as 別名]
def test_coerce_to(self):
types = Types()
cases = [
(42.0, 42, types.double_type),
(42.0, 42, types.float_type),
(42, 42.0, types.sint32_type),
(42, 42L, types.sint32_type),
(42L, 42.0, types.sint64_type),
(42L, 42, types.sint64_type),
(42, 42.0, types.uint32_type),
(42, 42L, types.uint32_type),
(42L, 42.0, types.uint64_type),
(42L, 42, types.uint64_type),
(list(), tuple(), types.list_type(types.string_type)),
((0, 1, 2), [0, 1, 2],
types.tuple_type(types.sint32_type,
types.sint32_type,
types.sint32_type)),
([0, 1, 2], (0, 1, 2),
types.list_type(types.sint32_type)),
(['foo', 'bar'], ['foo', 'bar'],
types.list_type(types.string_type))
]
for expected, value, typ in cases:
coerced_value = types.coerce_to(value, typ)
self.assertEqual(expected, coerced_value)
self.assertEqual(type(expected), type(coerced_value))
strings = [
u'foo',
u'\xe2\x84\xa2',
u'Mystery Goo\xe2\x84\xa2 Containment Unit'
]
for string in strings:
self.assertEqual(
string, types.coerce_to(string, types.string_type))
self.assertRaises(ValueError, types.coerce_to,
None, types.float_type)
self.assertRaises(ValueError, types.coerce_to,
'', types.float_type)
self.assertRaises(ValueError, types.coerce_to,
True, types.float_type)
self.assertRaises(ValueError, types.coerce_to,
list(), types.tuple_type(types.uint32_type))
self.assertRaises(ValueError, types.coerce_to,
['foo', 2], types.tuple_type(types.string_type))
self.assertRaises(ValueError, types.coerce_to,
[1], types.tuple_type(types.string_type))
示例3: test_coerce_to
# 需要導入模塊: from krpc.types import Types [as 別名]
# 或者: from krpc.types.Types import coerce_to [as 別名]
def test_coerce_to(self):
types = Types()
cases = [
(42.0, 42, 'double'),
(42.0, 42, 'float'),
(42, 42.0, 'int32'),
(42, 42L, 'int32'),
(42L, 42.0, 'int64'),
(42L, 42, 'int64'),
(42, 42.0, 'uint32'),
(42, 42L, 'uint32'),
(42L, 42.0, 'uint64'),
(42L, 42, 'uint64'),
(list(), tuple(), 'List(string)'),
((0, 1, 2), [0, 1, 2], 'Tuple(int32,int32,int32)'),
([0, 1, 2], (0, 1, 2), 'List(int32)'),
]
for expected, value, typ in cases:
coerced_value = types.coerce_to(value, types.as_type(typ))
self.assertEqual(expected, coerced_value)
self.assertEqual(type(expected), type(coerced_value))
strings = [
u'foo',
u'\xe2\x84\xa2',
u'Mystery Goo\xe2\x84\xa2 Containment Unit'
]
for string in strings:
self.assertEqual(string, types.coerce_to(string, types.as_type('string')))
self.assertEqual(['foo', 'bar'], types.coerce_to(['foo', 'bar'], types.as_type('List(string)')))
self.assertRaises(ValueError, types.coerce_to, None, types.as_type('float'))
self.assertRaises(ValueError, types.coerce_to, '', types.as_type('float'))
self.assertRaises(ValueError, types.coerce_to, True, types.as_type('float'))
self.assertRaises(ValueError, types.coerce_to, list(), types.as_type('Tuple(int32)'))
self.assertRaises(ValueError, types.coerce_to, ['foo', 2], types.as_type('Tuple(string)'))
self.assertRaises(ValueError, types.coerce_to, [1], types.as_type('Tuple(string)'))
示例4: Client
# 需要導入模塊: from krpc.types import Types [as 別名]
# 或者: from krpc.types.Types import coerce_to [as 別名]
class Client(object):
"""
A kRPC client, through which all Remote Procedure Calls are made.
Services provided by the server that the client connects to are automatically added.
RPCs can be made using client.ServiceName.ProcedureName(parameter)
"""
def __init__(self, rpc_connection, stream_connection):
self._types = Types()
self._rpc_connection = rpc_connection
self._rpc_connection_lock = threading.Lock()
self._stream_connection = stream_connection
self._request_type = self._types.as_type("KRPC.Request")
self._response_type = self._types.as_type("KRPC.Response")
# Set up the main KRPC service
self.krpc = KRPC(self)
services = self.krpc.get_services().services
# Create class types
# TODO: is this needed?!?
for service in services:
for procedure in service.procedures:
try:
name = Attributes.get_class_name(procedure.attributes)
self._types.as_type("Class(" + service.name + "." + name + ")")
except ValueError:
pass
# Set up services
for service in services:
if service.name != "KRPC":
setattr(self, _to_snake_case(service.name), create_service(self, service))
# Set up stream update thread
if stream_connection is not None:
self._stream_thread = threading.Thread(target=krpc.stream.update_thread, args=(stream_connection,))
self._stream_thread.daemon = True
self._stream_thread.start()
else:
self._stream_thread = None
def close(self):
self._rpc_connection.close()
if self._stream_connection is not None:
self._stream_connection.close()
def __enter__(self):
return self
def __exit__(self, typ, value, traceback):
self.close()
def add_stream(self, func, *args, **kwargs):
if self._stream_connection is None:
raise RuntimeError("Not connected to stream server")
return krpc.stream.add_stream(self, func, *args, **kwargs)
@contextmanager
def stream(self, func, *args, **kwargs):
""" 'with' support """
s = self.add_stream(func, *args, **kwargs)
try:
yield s
finally:
s.remove()
def _invoke(self, service, procedure, args=[], kwargs={}, param_names=[], param_types=[], return_type=None):
""" Execute an RPC """
# Build the request
request = self._build_request(service, procedure, args, kwargs, param_names, param_types, return_type)
# Send the request
with self._rpc_connection_lock:
self._send_request(request)
response = self._receive_response()
# Check for an error response
if response.HasField("error"):
raise RPCError(response.error)
# Decode the response and return the (optional) result
result = None
if return_type is not None:
result = Decoder.decode(response.return_value, return_type)
return result
def _build_request(self, service, procedure, args=[], kwargs={}, param_names=[], param_types=[], return_type=None):
""" Build a KRPC.Request object """
def encode_argument(i, value):
typ = param_types[i]
if type(value) != typ.python_type:
# Try coercing to the correct type
try:
value = self._types.coerce_to(value, typ)
except ValueError:
raise TypeError(
#.........這裏部分代碼省略.........
示例5: Client
# 需要導入模塊: from krpc.types import Types [as 別名]
# 或者: from krpc.types.Types import coerce_to [as 別名]
class Client(object):
"""
A kRPC client, through which all Remote Procedure Calls are made.
Services provided by the server that the client connects to are automatically added.
RPCs can be made using client.ServiceName.ProcedureName(parameter)
"""
def __init__(self, rpc_connection, stream_connection):
self._types = Types()
self._rpc_connection = rpc_connection
self._rpc_connection_lock = threading.Lock()
self._stream_connection = stream_connection
self._stream_cache = {}
self._stream_cache_lock = threading.Lock()
self._request_type = self._types.as_type('KRPC.Request')
self._response_type = self._types.as_type('KRPC.Response')
# Get the services
services = self._invoke('KRPC', 'GetServices', [], [], [], self._types.as_type('KRPC.Services')).services
# Set up services
for service in services:
setattr(self, snake_case(service.name), create_service(self, service))
# Set up stream update thread
if stream_connection is not None:
self._stream_thread_stop = threading.Event()
self._stream_thread = threading.Thread(target=krpc.stream.update_thread,
args=(stream_connection, self._stream_thread_stop,
self._stream_cache, self._stream_cache_lock))
self._stream_thread.daemon = True
self._stream_thread.start()
else:
self._stream_thread = None
def close(self):
self._rpc_connection.close()
if self._stream_thread is not None:
self._stream_thread_stop.set()
self._stream_thread.join()
def __enter__(self):
return self
def __exit__(self, typ, value, traceback):
self.close()
def add_stream(self, func, *args, **kwargs):
if self._stream_connection is None:
raise RuntimeError('Not connected to stream server')
return krpc.stream.add_stream(self, func, *args, **kwargs)
@contextmanager
def stream(self, func, *args, **kwargs):
""" 'with' support """
stream = self.add_stream(func, *args, **kwargs)
try:
yield stream
finally:
stream.remove()
def _invoke(self, service, procedure, args, param_names, param_types, return_type):
""" Execute an RPC """
# Build the request
request = self._build_request(service, procedure, args, param_names, param_types, return_type)
# Send the request
with self._rpc_connection_lock:
self._send_request(request)
response = self._receive_response()
# Check for an error response
if response.has_error:
raise RPCError(response.error)
# Decode the response and return the (optional) result
result = None
if return_type is not None:
result = Decoder.decode(response.return_value, return_type)
return result
def _build_request(self, service, procedure, args,
param_names, param_types, return_type): #pylint: disable=unused-argument
""" Build a KRPC.Request object """
request = krpc.schema.KRPC.Request(service=service, procedure=procedure)
for i, (value, typ) in enumerate(itertools.izip(args, param_types)):
if isinstance(value, DefaultArgument):
continue
if not isinstance(value, typ.python_type):
try:
value = self._types.coerce_to(value, typ)
except ValueError:
raise TypeError('%s.%s() argument %d must be a %s, got a %s' % \
(service, procedure, i, typ.python_type, type(value)))
request.arguments.add(position=i, value=Encoder.encode(value, typ))
return request
#.........這裏部分代碼省略.........