def _read_plist(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') raise salt.exceptions.SaltInvocationError( 'Error decoding Property List : {}'.format(error)) else: return dataObject
def read_file(self, path): """Replace internal XML dict with data from plist at path. Args: path: String path to a plist file. Raises: PlistParseError: Error in reading plist file. """ # pylint: disable=unused-variable try: info, pformat, error = ( NSPropertyListSerialization. propertyListWithData_options_format_error_( NSData.dataWithContentsOfFile_(os.path.expanduser(path)), NSPropertyListMutableContainersAndLeaves, None, None)) # pylint: enable=unused-variable if info is None: if error is None: error = "Invalid plist file." raise PlistParseError("Can't read %s: %s" % (path, error)) except ValueError: print(("Can't read %s" % (path))) sys.exit() return info
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
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
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
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)
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)
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
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)
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
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" #pylint: disable=no-self-use plistpath = os.path.join(path, "Contents", "Info.plist") info, _, 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
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
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.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
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
def readPlist(filepath): plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" errmsg = "{0} in file {1}".format(error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
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
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
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)
def load_favservers(sfl_path): if os.path.isfile(sfl_path): # File exists, use it sfl_decoded = NSKeyedUnarchiver.unarchiveObjectWithData_( NSData.dataWithContentsOfFile_(sfl_path)) else: # File doesn't exist, make a blank template sfl_decoded = { u'items': [], u'version': 1L, u'properties': { "com.apple.LSSharedFileList.ForceTemplateIcons": False, }, } mutable_favs = dict(sfl_decoded) mutable_favs['items'] = list(mutable_favs['items']) return mutable_favs
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" plistpath = os.path.join(path, "Contents", "Info.plist") if not (os.path.isfile(plistpath)): raise ProcessorError("File does not exist: %s" % plistpath) 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
def pdf2tiff(pdfPath, pageNum=0, resolution=72.0): "Convert one page of a PDF to TIFF at a specific res. in DPI." tiffPath = "%s-%d.tiff" % (splitext(pdfPath)[0], pageNum) pdfData = NSData.dataWithContentsOfFile_(pdfPath) pdfRep = NSPDFImageRep.imageRepWithData_(pdfData) pageCount = pdfRep.pageCount() if pageNum > pageCount-1: return pdfRep.setCurrentPage_(pageNum) pdfImage = NSImage.alloc().init() pdfImage.addRepresentation_(pdfRep) originalSize = pdfImage.size() width, height = originalSize pdfImage.setScalesWhenResized_(YES) rf = resolution / 72.0 pdfImage.setSize_((width*rf, height*rf)) tiffData = pdfImage.TIFFRepresentation() tiffData.writeToFile_atomically_(tiffPath, YES)
def pdf2tiff(pdfPath, pageNum=0, resolution=72.0): "Convert one page of a PDF to TIFF at a specific res. in DPI." tiffPath = "%s-%d.tiff" % (splitext(pdfPath)[0], pageNum) pdfData = NSData.dataWithContentsOfFile_(pdfPath) pdfRep = NSPDFImageRep.imageRepWithData_(pdfData) pageCount = pdfRep.pageCount() if pageNum > pageCount - 1: return pdfRep.setCurrentPage_(pageNum) pdfImage = NSImage.alloc().init() pdfImage.addRepresentation_(pdfRep) originalSize = pdfImage.size() width, height = originalSize pdfImage.setScalesWhenResized_(YES) rf = resolution / 72.0 pdfImage.setSize_((width * rf, height * rf)) tiffData = pdfImage.TIFFRepresentation() tiffData.writeToFile_atomically_(tiffPath, YES)
def read_plist(filepath): ''' Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). ''' plist_data = NSData.dataWithContentsOfFile_(filepath) data_object, dummy_plist_format, error = ( NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plist_data, NSPropertyListMutableContainers, None, None)) if data_object is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) # pylint: disable=E0602 else: return data_object
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" # pylint: disable=no-self-use plistpath = os.path.join(path, "Contents", "Info.plist") # pylint: disable=line-too-long info, _, error = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( NSData.dataWithContentsOfFile_(plistpath), NSPropertyListMutableContainers, None, None, ) # pylint: enable=line-too-long if error: raise ProcessorError("Can't read %s: %s" % (plistpath, error)) return info
def convertIconToPNG(icon_path, destination_path, desired_pixel_height=350): '''Converts an icns file to a png file, choosing the representation closest to (but >= if possible) the desired_pixel_height. Returns True if successful, False otherwise''' if os.path.exists(icon_path): image_data = NSData.dataWithContentsOfFile_(icon_path) bitmap_reps = NSBitmapImageRep.imageRepsWithData_(image_data) chosen_rep = None for bitmap_rep in bitmap_reps: if not chosen_rep: chosen_rep = bitmap_rep elif (bitmap_rep.pixelsHigh() >= desired_pixel_height and bitmap_rep.pixelsHigh() < chosen_rep.pixelsHigh()): chosen_rep = bitmap_rep if chosen_rep: png_data = chosen_rep.representationUsingType_properties_( NSPNGFileType, None) png_data.writeToFile_atomically_(destination_path, False) return True return False
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, dummy_plistFormat, error, ) = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if dataObject is None: if error: error = error.encode("ascii", "ignore") else: error = "Unknown error" errmsg = "%s in file %s" % (error, filepath) raise ProcessorError(errmsg) else: return dataObject
def retrieve_account_identifiers(): path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, True).firstObject() path = os.path.join(path, 'Group Containers', 'Q8B696Y8U4.com.ddeville.spillo', 'Library', 'Preferences', 'Q8B696Y8U4.com.ddeville.spillo.plist') data = NSData.dataWithContentsOfFile_(path) if data is None: return None defaults = NSPropertyListSerialization.propertyListWithData_options_format_error_( data, 0, None, None)[0] if defaults is None: return None accounts = defaults.get("accounts") if accounts is None: return None return accounts.valueForKey_("identifier")
def read_file(self, path): """Replace internal XML dict with data from plist at path. Args: path: String path to a plist file. Raises: PlistParseError: Error in reading plist file. """ # pylint: disable=unused-variable info, pformat, error = ( NSPropertyListSerialization.propertyListWithData_options_format_error_( NSData.dataWithContentsOfFile_(os.path.expanduser(path)), NSPropertyListMutableContainersAndLeaves, None, None )) # pylint: enable=unused-variable if info is None: if error is None: error = "Invalid plist file." raise PlistParseError("Can't read %s: %s" % (path, error)) return info
def load(cls): ''' Load the all paths from setting file :return An array which contain all the directory model ''' settingPath = cls.settingPath() fm = NSFileManager.defaultManager() paths = NSMutableArray.array() settings = NSMutableDictionary.dictionary() if fm.fileExistsAtPath_isDirectory_(settingPath, None)[0]: settingFile = NSData.dataWithContentsOfFile_(settingPath) jsonData = NSJSONSerialization.JSONObjectWithData_options_error_( settingFile, 0, None)[0] settings['startup'] = jsonData['startup'] settings['api_key'] = jsonData['api_key'] for item in jsonData['paths']: directory = Directory.alloc().initWithDict_(item) paths.addObject_(directory) settings['paths'] = paths else: settings['startup'] = True settings['api_key'] = '' settings['paths'] = paths return settings
def _read_plist(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') raise salt.exceptions.SaltInvocationError( 'Error decoding Property List : {}'.format(error) ) else: return dataObject
#!/usr/bin/python # -*- coding: utf-8 -*- # モジュールのimport import sys import os # モジュール os.pathのクラスsplitextを初期化 from os.path import splitext from objc import YES, NO from Foundation import NSData from AppKit import * NSApp = NSApplication.sharedApplication() pdf_file = sys.argv[1].decode('utf-8') fileData = NSData.dataWithContentsOfFile_(pdf_file) refer = NSPDFImageRep.imageRepWithData_(fileData) numOfPages = refer.pageCount() print pdf_file print numOfPages #if __name__ == '__main__': # 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
def pageCount(pdfPath): "Return the number of pages for some PDF file." data = NSData.dataWithContentsOfFile_(pdfPath) img = NSPDFImageRep.imageRepWithData_(data) return img.pageCount()