本文整理汇总了Python中Foundation.NSData.dataWithBytes_length_方法的典型用法代码示例。如果您正苦于以下问题:Python NSData.dataWithBytes_length_方法的具体用法?Python NSData.dataWithBytes_length_怎么用?Python NSData.dataWithBytes_length_使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Foundation.NSData
的用法示例。
在下文中一共展示了NSData.dataWithBytes_length_方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: value
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
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)
示例2: nsdata
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
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))
示例3: __ns_data_from_array
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
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)
示例4: start
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def start(self):
'''Start the connection'''
if not self.destination_path:
self.log('No output file specified.')
self.done = True
return
url = NSURL.URLWithString_(self.url)
request = (
NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
url, NSURLRequestReloadIgnoringLocalCacheData,
self.connection_timeout))
if self.post_data:
request.setHTTPMethod_('POST')
data_unicode = unicode(self.post_data)
data = NSData.dataWithBytes_length_(NSString.stringWithString_(data_unicode).UTF8String(), len(data_unicode.encode('utf-8')))
request.setHTTPBody_(data)
if self.additional_headers:
for header, value in self.additional_headers.items():
request.setValue_forHTTPHeaderField_(value, header)
# does the file already exist? See if we can resume a partial download
if os.path.isfile(self.destination_path):
stored_data = self.get_stored_headers()
if (self.can_resume and 'expected-length' in stored_data and
('last-modified' in stored_data or 'etag' in stored_data)):
# we have a partial file and we're allowed to resume
self.resume = True
local_filesize = os.path.getsize(self.destination_path)
byte_range = 'bytes=%s-' % local_filesize
request.setValue_forHTTPHeaderField_(byte_range, 'Range')
if self.download_only_if_changed and not self.resume:
stored_data = self.cache_data or self.get_stored_headers()
if 'last-modified' in stored_data:
request.setValue_forHTTPHeaderField_(
stored_data['last-modified'], 'if-modified-since')
if 'etag' in stored_data:
request.setValue_forHTTPHeaderField_(
stored_data['etag'], 'if-none-match')
self.connection = NSURLConnection.alloc().initWithRequest_delegate_(
request, self)
示例5: get_input
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def get_input():
try:
while True:
line = sys.stdin.readline()
if not line:
break
if line == '':
continue
print "info:Read %s" % line
sys.stdout.flush()
cfg = None
try:
cfg = json.loads(line)
except:
pass
if cfg == None:
print "info:Unable to parse line"
sys.stdout.flush()
continue
if cfg.has_key("Action"):
print "info:Running %s" % cfg["Action"]
sys.stdout.flush()
if cfg["Action"] == "setmenu":
menu = cfg["Menu"]
if lookup.has_key(menu["Key"]):
lookup[menu["Key"]].title = menu["Text"]
if menu.has_key("Enabled") and not menu["Enabled"]:
lookup[menu["Key"]].set_callback(None)
else:
lookup[menu["Key"]].set_callback(item_clicked)
app.menu.update([])
else:
print "warn:Key not found %s" % cfg["Action"]
sys.stdout.flush()
elif cfg["Action"] == "setmenus":
app.menu.clear()
app.menu = parsemenus(cfg)
print "info:Updated menus"
sys.stdout.flush()
elif cfg["Action"] == "seticon":
try:
raw = base64.b64decode(cfg["Image"])
data = NSData.dataWithBytes_length_(raw, len(raw))
img = NSImage.alloc().initWithData_(data)
img.setScalesWhenResized_(True)
img.setSize_((18, 18))
img.setTemplate_(True)
app.icon = img
print "info:Image updated"
sys.stdout.flush()
except:
print "warn:Failed to set image"
sys.stdout.flush()
elif cfg["Action"] == "setappicon":
try:
raw = base64.b64decode(cfg["Image"])
data = NSData.dataWithBytes_length_(raw, len(raw))
img = NSImage.alloc().initWithData_(data)
#img.setScalesWhenResized_(True)
#img.setSize_((21, 21))
NSApplication.sharedApplication().setApplicationIconImage_(img)
print "info:AppImage updated"
sys.stdout.flush()
except:
print "warn:Failed to set image"
sys.stdout.flush()
elif cfg["Action"] == "shutdown":
break
elif cfg["Action"] == "foreground":
transform_app_type(True)
elif cfg["Action"] == "background":
transform_app_type(False)
elif cfg["Action"] == "notification":
if rumps._NOTIFICATIONS:
title = cfg["Title"]
message = cfg["Message"]
subtitle = ''
playSound = True
image = None
#.........这里部分代码省略.........
示例6: set_clipboard
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def set_clipboard(self, data):
ns_data = NSData.dataWithBytes_length_(data, len(data))
pb = self._ns_pasteboard
pb.clearContents()
pb.setData_forType_(ns_data, NSStringPboardType)
示例7: get_input
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def get_input():
try:
while True:
line = sys.stdin.readline()
if not line:
break
if line == '':
continue
print "info:Read %s" % line
sys.stdout.flush()
cfg = None
try:
cfg = json.loads(line)
except:
pass
if cfg == None:
print "info:Unable to parse line"
sys.stdout.flush()
continue
if cfg.has_key("Action"):
print "info:Running %s" % cfg["Action"]
sys.stdout.flush()
if cfg["Action"] == "setmenu":
menu = cfg["Menu"]
if lookup.has_key(menu["Key"]):
lookup[menu["Key"]].title = menu["Text"]
if menu.has_key("Enabled") and not menu["Enabled"]:
lookup[menu["Key"]].set_callback(None)
else:
lookup[menu["Key"]].set_callback(item_clicked)
app.menu.update([])
else:
print "warn:Key not found %s" % cfg["Action"]
sys.stdout.flush()
elif cfg["Action"] == "setmenus":
app.menu.clear()
app.menu = parsemenus(cfg)
print "info:Updated menus"
sys.stdout.flush()
elif cfg["Action"] == "seticon":
try:
raw = base64.b64decode(cfg["Image"])
data = NSData.dataWithBytes_length_(raw, len(raw))
img = NSImage.alloc().initWithData_(data)
img.setScalesWhenResized_(True)
img.setSize_((21, 21))
app.icon = img
print "info:Image updated"
sys.stdout.flush()
except:
print "warn:Failed to set image"
sys.stdout.flush()
elif cfg["Action"] == "shutdown":
break
elif cfg["Action"] == "notification":
if rumps_NOTIFICATIONS:
rumps.notification(cfg["Title"], '', cfg["Message"])
finally:
rumps.quit_application()
print "info:Shutdown"
sys.stdout.flush()
print "info:Stdin close"
sys.stdout.flush()
sys.stdin.close()
示例8: parse_plist
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def parse_plist(info_plist_string):
# Use PyObjC, pre-installed in Apple's Python dist.
data = NSData.dataWithBytes_length_(info_plist_string, len(info_plist_string))
return NSPropertyListSerialization.propertyListWithData_options_format_error_(data, 0, None, None)
示例9: main
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def main():
parser = argparse.ArgumentParser(description='Sign or encrypt mobileconfig profiles, using either a cert + key file, or a keychain certificate.')
parser.add_argument('sign', choices=('sign', 'encrypt', 'both'), help='Choose to sign, encrypt, or do both on a profile.')
key_group = parser.add_argument_group('Keychain arguments', description='Use these if you wish to sign with a Keychain certificate.')
key_group.add_argument('-k', '--keychain', help='Name of keychain to search for cert. Defaults to login.keychain',
default='login.keychain')
key_group.add_argument('-n', '--name', help='Common name of certificate to use from keychain.', required=True)
parser.add_argument('infile', help='Path to input .mobileconfig file')
parser.add_argument('outfile', help='Path to output .mobileconfig file. Defaults to outputting into the same directory.')
args = parser.parse_args()
print "fuck yeah"
if args.sign == 'encrypt' or args.sign == 'both':
# encrypt the profile only, do not sign
# Encrypting a profile:
# 1. Extract payload content into its own file
# 2. Serial that file as its own plist
# 3. CMS-envelope that content (using openssl for now)
# 4. Remove "PayloadContent" key and replace with "EncryptedPayloadContent" key
# 5. Replace the PayloadContent <array> with <data> tags instead
# Step 1: Extract payload content into its own file
myProfile = plistlib.readPlist(args.infile)
payloadContent = myProfile['PayloadContent']
# Step 2: Serialize that file into its own plist
(pContentFile, pContentPath) = tempfile.mkstemp()
plistlib.writePlist(payloadContent, pContentPath)
# Step 3: Use openssl to encrypt that content
# First, we need to extract the certificate we want to use from the keychain
security_cmd = ['/usr/bin/security', 'find-certificate', '-c', args.name, '-p' ]
if args.keychain:
security_cmd += [args.keychain]
print security_cmd
proc = subprocess.Popen(security_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(sout, serr) = proc.communicate()
if serr:
print >> sys.stderr, "Error: %s" % serr
sys.exit(1)
# Now write the certificate to a temp file
(certfile, certpath) = tempfile.mkstemp('.pem')
try:
with open(certpath, 'wb') as f:
f.write(sout)
except IOError:
print >> sys.stderr, "Could not write to file!"
sys.exit(1)
# Now use openssl to encrypt the payload content using that certificate
(encPContentfile, encPContentPath) = tempfile.mkstemp('.plist')
enc_cmd = ['/usr/bin/openssl', 'smime', '-encrypt', '-aes256', '-outform', 'pem',
'-in', pContentPath, '-out', encPContentPath]
enc_cmd += [certpath]
proc = subprocess.Popen(enc_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(encout, encerr) = proc.communicate()
if encerr:
print >> sys.stderr, "Error: %s" % encerr
sys.exit(1)
# openssl smime -encrypt produces no output if successful
# Step 4: Add the new encrypted payload content back into the plist
with open(encPContentPath, 'rb') as f:
content = f.readlines()
content = content[1:-1] #this is to skip the ---BEGIN PKCS7--- and ----END PKCS7---- lines
encPayload = ""
for line in content:
encPayload += ''.join(line.rstrip()) # to get rid of Python's \n everywhere
del myProfile['PayloadContent']
binaryEncPayload = base64.b64decode(encPayload)
wrapped_data = NSData.dataWithBytes_length_(binaryEncPayload, len(binaryEncPayload))
myProfile['EncryptedPayloadContent'] = wrapped_data
plistData, error = NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(myProfile, NSPropertyListXMLFormat_v1_0, None)
plistData.writeToFile_atomically_(args.outfile, True)
# Step 5: Use plistlib.Data to properly encode the content
# myProfile['EncryptedPayloadContent'] = plistlib.Data(encPayload)
# now save the profile
# plistlib.writePlist(myProfile, args.outfile)
# Now clean up after ourselves
if args.sign == 'sign' or args.sign == 'both':
# sign the profile only
# Keychain check:
if not args.name:
print >> sys.stderr, 'Error: A certificate common name is required to sign profiles with the Keychain.'
sys.exit(22)
cmd = ['/usr/bin/security', 'cms', '-S', '-N', args.name, '-i', args.infile, '-o', args.outfile ]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(sout, serr) = proc.communicate()
if serr:
print >> sys.stderr, 'Error: %s' % serr
sys.exit(1)
示例10: main
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def main():
parser = argparse.ArgumentParser(description='Sign or encrypt mobileconfig profiles, using either a cert + key file, or a keychain certificate.')
parser.add_argument('sign', choices=('sign', 'encrypt', 'both'), help='Choose to sign, encrypt, or do both on a profile.')
key_group = parser.add_argument_group('Keychain arguments', description='Use these if you wish to sign with a Keychain certificate.')
key_group.add_argument('-k', '--keychain', help='Name of keychain to search for cert. Defaults to login.keychain',
default='login.keychain')
key_group.add_argument('-n', '--name', help='Common name of certificate to use from keychain.', required=True)
parser.add_argument('infile', help='Path to input .mobileconfig file')
parser.add_argument('outfile', help='Path to output .mobileconfig file. Defaults to outputting into the same directory.')
args = parser.parse_args()
if args.sign == 'encrypt' or args.sign == 'both':
if args.sign == 'both':
outputFile = args.outfile + '_unsigned'
else:
outputFile = args.outfile
# encrypt the profile only, do not sign
# Encrypting a profile:
# 1. Extract payload content into its own file
# 2. Serial that file as its own plist
# 3. CMS-envelope that content (using openssl for now)
# 4. Remove "PayloadContent" key and replace with "EncryptedPayloadContent" key
# 5. Replace the PayloadContent <array> with <data> tags instead
# Step 1: Extract payload content into its own file
myProfile = readPlist(args.infile)
payloadContent = myProfile['PayloadContent']
# Step 2: Serialize that file into its own plist
(pContentFile, pContentPath) = tempfile.mkstemp()
#print "pContentPath: %s" % pContentPath
writePlist(payloadContent, pContentPath)
# Step 3: Use openssl to encrypt that content
# First, we need to extract the certificate we want to use from the keychain
security_cmd = ['/usr/bin/security', 'find-certificate', '-c', args.name, '-p' ]
if args.keychain:
security_cmd += [args.keychain]
proc = subprocess.Popen(security_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(sout, serr) = proc.communicate()
if serr:
print >> sys.stderr, "Error: %s" % serr
sys.exit(1)
# Now write the certificate to a temp file
(certfile, certpath) = tempfile.mkstemp('.der')
#print "Certpath: %s" % certpath
try:
with open(certpath, 'wb') as f:
f.write(sout)
except IOError:
print >> sys.stderr, "Could not write to file!"
sys.exit(1)
# Now use openssl to encrypt the payload content using that certificate
(encPContentfile, encPContentPath) = tempfile.mkstemp('.plist')
#print "encPContentPath: %s" % encPContentPath
enc_cmd = ['/usr/bin/openssl', 'smime', '-encrypt', '-aes256', '-outform', 'der',
'-in', pContentPath, '-out', encPContentPath]
enc_cmd += [certpath]
proc = subprocess.Popen(enc_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(encout, encerr) = proc.communicate()
if encerr:
print >> sys.stderr, "Error: %s" % encerr
sys.exit(1)
# openssl smime -encrypt produces no output if successful
# Step 4: Add the new encrypted payload content back into the plist
with open(encPContentPath, 'rb') as f:
binaryEncPayload = f.read()
del myProfile['PayloadContent']
wrapped_data = NSData.dataWithBytes_length_(binaryEncPayload, len(binaryEncPayload))
myProfile['EncryptedPayloadContent'] = wrapped_data
# Step 5: Replace the plist with the new content
plistData, error = NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(myProfile, NSPropertyListXMLFormat_v1_0, None)
plistData.writeToFile_atomically_(outputFile, True)
# Now clean up after ourselves
os.remove(pContentPath)
os.remove(certpath)
os.remove(encPContentPath)
if args.sign == 'sign' or args.sign == 'both':
# Keychain check:
if not args.name:
print >> sys.stderr, 'Error: A certificate common name is required to sign profiles with the Keychain.'
sys.exit(22)
if args.sign == 'both':
# If we already encrypted it, then the correct file is already in outputFile
inputFile = outputFile
else:
inputFile = args.infile
cmd = ['/usr/bin/security', 'cms', '-S', '-N', args.name, '-i', inputFile, '-o', args.outfile ]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(sout, serr) = proc.communicate()
if serr:
print >> sys.stderr, 'Error: %s' % serr
sys.exit(1)
if args.sign == 'both':
os.remove(outputFile)
示例11: unplist
# 需要导入模块: from Foundation import NSData [as 别名]
# 或者: from Foundation.NSData import dataWithBytes_length_ [as 别名]
def unplist(s):
from Foundation import NSData, NSPropertyListSerialization
d = NSData.dataWithBytes_length_(s, len(s))
return NSPropertyListSerialization.propertyListWithData_options_format_error_(d, 0, None, None)