本文整理汇总了Python中Foundation.NSData类的典型用法代码示例。如果您正苦于以下问题:Python NSData类的具体用法?Python NSData怎么用?Python NSData使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NSData类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(argv):
p = optparse.OptionParser()
p.set_usage("""Usage: %prog [options] userdata.plist [password]""")
p.add_option("-v", "--verbose", action="store_true",
help="Verbose output.")
options, argv = p.parse_args(argv)
if len(argv) not in (2, 3):
print >>sys.stderr, p.get_usage()
return 1
# Read the userdata.plist.
plist = argv[1]
plist_data = NSData.dataWithContentsOfFile_(plist)
if not plist_data:
print >>sys.stderr, "Couldn't read %s" % plist
return 1
user_plist, plist_format, error = \
NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(
plist_data, NSPropertyListMutableContainers, None, None)
if error:
print >>sys.stderr, "Can't read %s: %s" % (plist, error)
return 1
# Use password on commandline, or ask if one isn't provided.
try:
password = argv[2]
except IndexError:
while True:
password = getpass.getpass()
verify_password = getpass.getpass("Password again: ")
if password == verify_password:
break
else:
print "Passwords don't match!"
# Hash password with all available methods.
hashed_passwords = dict()
for k, m in hash_methods.items():
hashed_pwd = m(password)
pwd_data = NSData.alloc().initWithBytes_length_(hashed_pwd, len(hashed_pwd))
hashed_passwords[k] = pwd_data
# Serialize hashed passwords to a binary plist.
serialized_passwords = serialize_hash_dict(hashed_passwords)
if not serialized_passwords:
return 2
# Write back userdata.plist with ShadowHashData.
user_plist["ShadowHashData"] = list()
user_plist["ShadowHashData"].append(serialized_passwords)
plist_data, error = \
NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(
user_plist, plist_format, None)
plist_data.writeToFile_atomically_(argv[1], True)
return 0
示例2: _readPlist
def _readPlist(filepath):
"""
Read a .plist file from filepath. Return the unpacked root object
(which is usually a dictionary).
If the file doesn't exist, this returns None
"""
if not os.path.isfile(filepath):
log.debug('Tried to read non-existent property list at path: {0}'.format(filepath))
return None
plistData = NSData.dataWithContentsOfFile_(filepath)
dataObject, plistFormat, error = \
NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(
plistData, NSPropertyListMutableContainers, None, None)
if error:
error = error.encode('ascii', 'ignore')
errmsg = "%s in file %s" % (error, filepath)
import traceback
log.debug(errmsg)
log.debug(traceback.format_exc())
raise NSPropertyListSerializationException(errmsg)
else:
return dataObject
示例3: nsdata
def nsdata(obj):
"""Convert ``object`` to `NSData`."""
if isinstance(obj, unicode):
s = obj.encode('utf-8')
else:
s = str(obj)
return NSData.dataWithBytes_length_(s, len(s))
示例4: value
def value(self, data):
if not self.properties["write"]:
return
# data needs to be byte array
if not isinstance(data, bytearray):
raise TypeError("data needs to be a bytearray")
rawdata = NSData.dataWithBytes_length_(data, len(data))
self.service.peripheral.writeValueForCharacteristic(rawdata, self.instance)
示例5: readPlist
def readPlist(filepath):
"""Read a .plist file from filepath. Return the unpacked root object
(which is usually a dictionary)."""
try:
data = NSData.dataWithContentsOfFile_(filepath)
except NSPropertyListSerializationException, error:
# insert filepath info into error message
errmsg = u"%s in %s" % (error, filepath)
raise NSPropertyListSerializationException(errmsg)
示例6: _valueToNSObject
def _valueToNSObject(value, nstype):
'''Convert a string with a type specifier to a native Objective-C NSObject (serializable).'''
return {
'string': lambda v: NSString.stringWithUTF8String_(v),
'int': lambda v: NSNumber.numberWithInt_(v),
'float': lambda v: NSNumber.numberWithFloat_(v),
'bool': lambda v: True if v == 'true' else False,
'data': lambda v: NSData.initWithBytes_length_(v, len(v))
}[nstype](value)
示例7: readPlist
def readPlist(path):
plistData = NSData.dataWithContentsOfFile_(path)
dataObject, plistFormat, error = \
NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(
plistData, NSPropertyListMutableContainers, None, None)
if error:
errmsg = "%s in file %s" % (repr(error), repr(path))
raise NSPropertyListSerializationException(errmsg)
else:
return dataObject
示例8: _init_from_file
def _init_from_file(self, file):
#ns_image = NSImage.alloc().initWithContentsOfFile_(file)
#if not ns_image:
ns_data = NSData.dataWithContentsOfFile_(file)
if not ns_data:
raise EnvironmentError("Unable to read image file: %s" % file)
ns_rep = NSBitmapImageRep.imageRepWithData_(ns_data)
if not ns_rep:
raise ValueError("Unrecognised image file type: %s" % file)
ns_rep.setSize_((ns_rep.pixelsWide(), ns_rep.pixelsHigh()))
self._init_from_ns_rep(ns_rep)
示例9: readPlist
def readPlist(filepath):
'''Read a .plist file from filepath. Return the unpacked root object
(which is usually a dictionary).'''
plistData = NSData.dataWithContentsOfFile_(filepath)
(dataObject, plistFormat, error) = (
NSPropertyListSerialization.propertyListWithData_options_format_error_(
plistData, NSPropertyListMutableContainersAndLeaves, None, None))
if error:
errmsg = u"%s in file %s" % (error, filepath)
raise NSPropertyListSerializationException(errmsg)
else:
return dataObject
示例10: readPlist
def readPlist(self, filepath):
"""
Read a .plist file from filepath. Return the unpacked root object
(which is usually a dictionary).
"""
plistData = NSData.dataWithContentsOfFile_(filepath)
dataObject, plistFormat, error = \
NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(
plistData, NSPropertyListMutableContainers, None, None)
if error:
errmsg = "%s in file %s" % (error, filepath)
raise ProcessorError(errmsg)
else:
return dataObject
示例11: read_bundle_info
def read_bundle_info(self, path):
"""Read Contents/Info.plist inside a bundle."""
plistpath = os.path.join(path, "Contents", "Info.plist")
info, format, error = \
NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(
NSData.dataWithContentsOfFile_(plistpath),
NSPropertyListMutableContainers,
None,
None
)
if error:
raise ProcessorError("Can't read %s: %s" % (plistpath, error))
return info
示例12: readPlist
def readPlist(filepath):
"""
Read a .plist file from filepath. Return the unpacked root object
(which is usually a dictionary).
"""
plistData = NSData.dataWithContentsOfFile_(filepath)
dataObject, dummy_plistFormat, error = (
NSPropertyListSerialization.
propertyListFromData_mutabilityOption_format_errorDescription_(
plistData, NSPropertyListMutableContainers, None, None))
if error:
error = error.encode('ascii', 'ignore')
errmsg = "%s in file %s" % (error, filepath)
raise NSPropertyListSerializationException(errmsg)
else:
return dataObject
示例13: read_recipe
def read_recipe(self, path):
"""Read a recipe into a dict."""
path = os.path.expanduser(path)
if not (os.path.isfile(path)):
raise Exception("File does not exist: %s" % path)
info, pformat, error = \
NSPropertyListSerialization.propertyListWithData_options_format_error_(
NSData.dataWithContentsOfFile_(path),
NSPropertyListMutableContainers,
None,
None
)
if error:
raise Exception("Can't read %s: %s" % (path, error))
self._xml = info
示例14: addToWf
def addToWf(wf, buffer, icon):
for filename in buffer:
filename = filename.strip(u"\r\n")
plist_data = NSData.dataWithContentsOfFile_(filename)
(dataObject, plistFormat, error) = (
NSPropertyListSerialization.
propertyListWithData_options_format_error_(
plist_data,
NSPropertyListMutableContainersAndLeaves,
None,
None))
wf.add_item(title=dataObject["Name"],
subtitle=dataObject["URL"],
arg=dataObject["URL"],
valid=True,
icon=icon)
示例15: __ns_data_from_array
def __ns_data_from_array(a):
from Foundation import NSData
a = np.asarray(a).flatten()
if a.dtype == np.uint8 or a.dtype == np.int8:
datasize = 1
elif a.dtype == np.uint16 or a.dtype == np.int16:
datasize = 2
elif a.dtype == np.float32:
datasize = 4
else:
assert 0, "unhandled data type %s" % (a.dtype)
buf = buffer(a)
return datasize, NSData.dataWithBytes_length_(buf, len(buf) * datasize)