本文整理汇总了Python中sys.byteorder方法的典型用法代码示例。如果您正苦于以下问题:Python sys.byteorder方法的具体用法?Python sys.byteorder怎么用?Python sys.byteorder使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sys
的用法示例。
在下文中一共展示了sys.byteorder方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: serialize_numpy
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def serialize_numpy(m, t):
'''
serialize_numpy(m, type) converts the numpy array m into a byte stream that can be read by the
nben.util.Py4j Java class. The function assumes that the type of the array needn't be encoded
in the bytearray itself. The bytearray will begin with an integer, the number of dimensions,
followed by that number of integers (the dimension sizes themselves) then the bytes of the
array, flattened.
The argument type gives the type of the array to be transferred and must be 'i' for integer or
'd' for double (or any other string accepted by array.array()).
'''
# Start with the header: <number of dimensions> <dim1-size> <dim2-size> ...
header = array('i', [len(m.shape)] + list(m.shape))
# Now, we can do the array itself, just flattened
body = array(t, m.flatten().tolist())
# Wrap bytes if necessary...
if sys.byteorder != 'big':
header.byteswap()
body.byteswap()
# And return the result:
return bytearray(header.tostring() + body.tostring())
示例2: to_xml
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def to_xml(self):
# fix endianness to machine endianness
self.endian = gifti_endian_codes.code[sys.byteorder]
result = ""
result += self.to_xml_open()
# write metadata
if not self.meta is None:
result += self.meta.to_xml()
# write coord sys
if not self.coordsys is None:
result += self.coordsys.to_xml()
# write data array depending on the encoding
dt_kind = data_type_codes.dtype[self.datatype].kind
result += data_tag(self.data,
gifti_encoding_codes.specs[self.encoding],
KIND2FMT[dt_kind],
self.ind_ord)
result = result + self.to_xml_close()
return result
示例3: test_byteorder_check
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def test_byteorder_check():
# Byte order check should pass for native order
if sys.byteorder == 'little':
native = '<'
else:
native = '>'
for dtt in (np.float32, np.float64):
arr = np.eye(4, dtype=dtt)
n_arr = arr.newbyteorder(native)
sw_arr = arr.newbyteorder('S').byteswap()
assert_equal(arr.dtype.byteorder, '=')
for routine in (linalg.inv, linalg.det, linalg.pinv):
# Normal call
res = routine(arr)
# Native but not '='
assert_array_equal(res, routine(n_arr))
# Swapped
assert_array_equal(res, routine(sw_arr))
示例4: __init__
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def __init__(self, fname, data, convert_dates=None, write_index=True,
encoding="latin-1", byteorder=None, time_stamp=None,
data_label=None, variable_labels=None):
super(StataWriter, self).__init__()
self._convert_dates = {} if convert_dates is None else convert_dates
self._write_index = write_index
self._encoding = 'latin-1'
self._time_stamp = time_stamp
self._data_label = data_label
self._variable_labels = variable_labels
self._own_file = True
# attach nobs, nvars, data, varlist, typlist
self._prepare_pandas(data)
if byteorder is None:
byteorder = sys.byteorder
self._byteorder = _set_endianness(byteorder)
self._fname = _stringify_path(fname)
self.type_converters = {253: np.int32, 252: np.int16, 251: np.int8}
self._converted_names = {}
示例5: save_pfm
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def save_pfm(fname, image, scale=1):
file = open(fname, 'w')
color = None
if image.dtype.name != 'float32':
raise Exception('Image dtype must be float32.')
if len(image.shape) == 3 and image.shape[2] == 3: # color image
color = True
elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale
color = False
else:
raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')
file.write('PF\n' if color else 'Pf\n')
file.write('%d %d\n' % (image.shape[1], image.shape[0]))
endian = image.dtype.byteorder
if endian == '<' or endian == '=' and sys.byteorder == 'little':
scale = -scale
file.write('%f\n' % scale)
np.flipud(image).tofile(file)
示例6: writeframesraw
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def writeframesraw(self, data):
self._ensure_header_written(len(data))
nframes = len(data) // (self._sampwidth * self._nchannels)
if self._convert:
data = self._convert(data)
if self._sampwidth in (2, 4) and sys.byteorder == 'big':
import array
a = array.array(_array_fmts[self._sampwidth])
a.fromstring(data)
data = a
assert data.itemsize == self._sampwidth
data.byteswap()
data.tofile(self._file)
self._datawritten = self._datawritten + len(data) * self._sampwidth
else:
if self._sampwidth == 3 and sys.byteorder == 'big':
data = _byteswap3(data)
self._file.write(data)
self._datawritten = self._datawritten + len(data)
self._nframeswritten = self._nframeswritten + nframes
示例7: test_endian_float
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def test_endian_float(self):
if sys.byteorder == "little":
self.assertIs(c_float.__ctype_le__, c_float)
self.assertIs(c_float.__ctype_be__.__ctype_le__, c_float)
else:
self.assertIs(c_float.__ctype_be__, c_float)
self.assertIs(c_float.__ctype_le__.__ctype_be__, c_float)
s = c_float(math.pi)
self.assertEqual(bin(struct.pack("f", math.pi)), bin(s))
# Hm, what's the precision of a float compared to a double?
self.assertAlmostEqual(s.value, math.pi, 6)
s = c_float.__ctype_le__(math.pi)
self.assertAlmostEqual(s.value, math.pi, 6)
self.assertEqual(bin(struct.pack("<f", math.pi)), bin(s))
s = c_float.__ctype_be__(math.pi)
self.assertAlmostEqual(s.value, math.pi, 6)
self.assertEqual(bin(struct.pack(">f", math.pi)), bin(s))
示例8: test_endian_double
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def test_endian_double(self):
if sys.byteorder == "little":
self.assertIs(c_double.__ctype_le__, c_double)
self.assertIs(c_double.__ctype_be__.__ctype_le__, c_double)
else:
self.assertIs(c_double.__ctype_be__, c_double)
self.assertIs(c_double.__ctype_le__.__ctype_be__, c_double)
s = c_double(math.pi)
self.assertEqual(s.value, math.pi)
self.assertEqual(bin(struct.pack("d", math.pi)), bin(s))
s = c_double.__ctype_le__(math.pi)
self.assertEqual(s.value, math.pi)
self.assertEqual(bin(struct.pack("<d", math.pi)), bin(s))
s = c_double.__ctype_be__(math.pi)
self.assertEqual(s.value, math.pi)
self.assertEqual(bin(struct.pack(">d", math.pi)), bin(s))
示例9: test_struct_fields_2
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def test_struct_fields_2(self):
# standard packing in struct uses no alignment.
# So, we have to align using pad bytes.
#
# Unaligned accesses will crash Python (on those platforms that
# don't allow it, like sparc solaris).
if sys.byteorder == "little":
base = BigEndianStructure
fmt = ">bxhid"
else:
base = LittleEndianStructure
fmt = "<bxhid"
class S(base):
_fields_ = [("b", c_byte),
("h", c_short),
("i", c_int),
("d", c_double)]
s1 = S(0x12, 0x1234, 0x12345678, 3.14)
s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)
self.assertEqual(bin(s1), bin(s2))
示例10: get_user_data
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def get_user_data(host_key=None, commands=None, packages=None, rootfs_skel_dirs=None, storage=frozenset(),
mime_multipart_archive=False, ssh_ca_keys=None, provision_users=None, **kwargs):
cloud_config_data = OrderedDict()
for i, (mountpoint, size_gb) in enumerate(storage):
cloud_config_data.setdefault("fs_setup", [])
cloud_config_data.setdefault("mounts", [])
device = "/dev/xvd" + chr(ord("z") - i)
fs_spec = dict(device=device, filesystem="ext4", partition="none")
cloud_config_data["fs_setup"].append(fs_spec)
cloud_config_data["mounts"].append([device, mountpoint, "auto", "defaults", "0", "2"])
cloud_config_data["packages"] = packages or []
cloud_config_data["runcmd"] = commands or []
cloud_config_data["write_files"] = get_bootstrap_files(rootfs_skel_dirs or [])
if ssh_ca_keys:
cloud_config_data["write_files"] += [dict(path="/etc/ssh/sshd_ca.pem", permissions='0644', content=ssh_ca_keys)]
cloud_config_data["runcmd"].append("grep -q TrustedUserCAKeys /etc/ssh/sshd_config || "
"(echo 'TrustedUserCAKeys /etc/ssh/sshd_ca.pem' >> /etc/ssh/sshd_config;"
" service sshd reload)")
if provision_users:
# TODO: UIDs should be deterministic
# uid_bytes = hashlib.sha256(username.encode()).digest()[-2:]
# uid = 2000 + (int.from_bytes(uid_bytes, byteorder=sys.byteorder) // 2)
cloud_config_data["users"] = [dict(name=u, gecos="", sudo="ALL=(ALL) NOPASSWD:ALL") for u in provision_users]
for key in sorted(kwargs):
cloud_config_data[key] = kwargs[key]
if host_key is not None:
buf = StringIO()
host_key.write_private_key(buf)
cloud_config_data["ssh_keys"] = dict(rsa_private=buf.getvalue(),
rsa_public=get_public_key_from_pair(host_key))
payload = encode_cloud_config_payload(cloud_config_data, mime_multipart_archive=mime_multipart_archive)
if len(payload) >= 16384:
logger.warn("Cloud-init payload is too large to be passed in user data, extracting rootfs.skel")
upload_bootstrap_asset(cloud_config_data, rootfs_skel_dirs)
payload = encode_cloud_config_payload(cloud_config_data, mime_multipart_archive=mime_multipart_archive)
return payload
示例11: bytes_to_int
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def bytes_to_int(bytesHash):
return int.from_bytes(bytesHash, byteorder=byteorder)
示例12: __init__
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def __init__(self, arch=None, bits=None, endian=None, mode=0):
if arch is None:
arch = self._DEFAULT_ARCH.get(platform.machine(), Target.Arch.unknown)
if bits is None:
bits = Target.Bits(64 if platform.architecture()[0] == '64bit' else 32)
if endian is None:
endian = Target.Endian.__members__[sys.byteorder]
self.arch = arch
self.bits = bits
self.endian = endian
self.mode = mode
示例13: read_data_block
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def read_data_block(encoding, endian, ordering, datatype, shape, data):
""" Tries to unzip, decode, parse the funny string data """
ord = array_index_order_codes.npcode[ordering]
enclabel = gifti_encoding_codes.label[encoding]
if enclabel == 'ASCII':
# GIFTI_ENCODING_ASCII
c = StringIO(data)
da = np.loadtxt(c)
da = da.astype(data_type_codes.type[datatype])
# independent of the endianness
return da
elif enclabel == 'B64BIN':
# GIFTI_ENCODING_B64BIN
dec = base64.decodestring(data.encode('ascii'))
dt = data_type_codes.type[datatype]
sh = tuple(shape)
newarr = np.fromstring(dec, dtype = dt)
if len(newarr.shape) != len(sh):
newarr = newarr.reshape(sh, order = ord)
elif enclabel == 'B64GZ':
# GIFTI_ENCODING_B64GZ
# convert to bytes array for python 3.2
# http://diveintopython3.org/strings.html#byte-arrays
dec = base64.decodestring(data.encode('ascii'))
zdec = zlib.decompress(dec)
dt = data_type_codes.type[datatype]
sh = tuple(shape)
newarr = np.fromstring(zdec, dtype = dt)
if len(newarr.shape) != len(sh):
newarr = newarr.reshape(sh, order = ord)
elif enclabel == 'External':
# GIFTI_ENCODING_EXTBIN
raise NotImplementedError("In what format are the external files?")
else:
return 0
# check if we need to byteswap
required_byteorder = gifti_endian_codes.byteorder[endian]
if (required_byteorder in ('big', 'little') and
required_byteorder != sys.byteorder):
newarr = newarr.byteswap()
return newarr
示例14: flush_chardata
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def flush_chardata(self):
""" Collate and process collected character data
"""
if self._char_blocks is None:
return
# Just join the strings to get the data. Maybe there are some memory
# optimizations we could do by passing the list of strings to the
# read_data_block function.
data = ''.join(self._char_blocks)
# Reset the char collector
self._char_blocks = None
# Process data
if self.write_to == 'Name':
data = data.strip()
self.nvpair.name = data
elif self.write_to == 'Value':
data = data.strip()
self.nvpair.value = data
elif self.write_to == 'DataSpace':
data = data.strip()
self.coordsys.dataspace = xform_codes.code[data]
elif self.write_to == 'TransformedSpace':
data = data.strip()
self.coordsys.xformspace = xform_codes.code[data]
elif self.write_to == 'MatrixData':
# conversion to numpy array
c = StringIO(data)
self.coordsys.xform = np.loadtxt(c)
c.close()
elif self.write_to == 'Data':
da_tmp = self.img.darrays[-1]
da_tmp.data = read_data_block(da_tmp.encoding, da_tmp.endian, \
da_tmp.ind_ord, da_tmp.datatype, \
da_tmp.dims, data)
# update the endianness according to the
# current machine setting
self.endian = gifti_endian_codes.code[sys.byteorder]
elif self.write_to == 'Label':
self.label.label = data.strip()
示例15: test_to_numpy
# 需要导入模块: import sys [as 别名]
# 或者: from sys import byteorder [as 别名]
def test_to_numpy():
if sys.byteorder == 'little':
yield assert_true, endian_codes['native'] == '<'
yield assert_true, endian_codes['swapped'] == '>'
else:
yield assert_true, endian_codes['native'] == '>'
yield assert_true, endian_codes['swapped'] == '<'
yield assert_true, endian_codes['native'] == endian_codes['=']
yield assert_true, endian_codes['big'] == '>'
for code in ('little', '<', 'l', 'L', 'le'):
yield assert_true, endian_codes[code] == '<'
for code in ('big', '>', 'b', 'B', 'be'):
yield assert_true, endian_codes[code] == '>'