def alias_from_whatever(self, whatever): """ Takes any object whatsoever and returns an alias, which Applescript needs to work properly This way self can use file objects, written out paths, or any object with a path attribute """ verbose = False verbose and output("Returning the following from alias_from_whatever:") if isinstance(whatever, file): verbose and output("Alias(whatever.name)") return mactypes.Alias(whatever.name) elif isinstance(whatever, mactypes.Alias): verbose and output("whatever") return whatever elif hasattr(whatever, 'path'): if isinstance(whatever.path, collections.Callable): verbose and output("Alias(whatever.path())") return mactypes.Alias(whatever.path()) else: verbose and output("Alias(whatever.path)", whatever.path) return mactypes.Alias(whatever.path) elif not isinstance(whatever, str) and 'path' in whatever: verbose and output("whatever['path']", whatever['path']) return mactypes.Alias(whatever['path']) elif isinstance(whatever, list): # recurively derive list return [self.alias_from_whatever(item) for item in whatever] else: verbose and output("Alias(whatever)") return mactypes.Alias(whatever)
def test_1(self): sa = osax.OSAX('Standardadditions') self.assertEqual(65, sa.ASCII_number('A')) self.assertEqual(mactypes.Alias("/Applications/"), sa.path_to(osax.k.applications_folder)) self.assertEqual( mactypes.Alias("/Library/Scripts/"), sa.path_to(osax.k.scripts_folder, from_=osax.k.local_domain)) self.assertRaises(AttributeError, getattr, sa, 'non_existent_command')
def action_import_playlist(path, *files): "import-playlist <playlist> <files> - import files to named playlist" # turn the playlist path into folder and name parts = path.rpartition(SEP) (folder, name) = (parts[0], parts[2]) app = itunes_connect() # create a playlist with the chosen name print("Creating iTunes playlist: %s" % name) playlist = app.make(new=appscript.k.playlist) playlist.name.set(name) # if there is a parent folder, find it (creating if necessary) if folder: parent = create_folder(app, folder) app.move(playlist, to=parent) # add the files to the playlist if files: # turn the files into a list of aliases files = [mactypes.Alias(file) for file in files] track = app.add(files, to=playlist) # show the playlist app.reveal(playlist)
def LoadPresentation(self, file): """ This method opens a file and starts the viewing of it. """ print '---------- load presentation' # Close existing presentation try: if self.presentation: self.ppt.close(self.presentation) except: print 'can not close previous presentation...continue anyway' self.log.exception('can not close presentation....continue anyway') # Open a new presentation and keep a reference to it in self.presentation file.replace("%20", " ") self.ppt.open(mactypes.Alias(file)) self.presentation = self.ppt.active_presentation self.lastSlide = len(self.presentation.slides.get()) print '================== set open file to ', file self.openFile = file # Start viewing the slides in a window self.presentation.slide_show_settings.show_type.set( k.slide_show_type_window) self.ppt.run_slide_show(self.presentation.slide_show_settings) self.win = self.ppt.slide_show_windows[1]
def test_alias(self): # make alias self.f = mactypes.Alias(self.path1) path1 = self.path1 if not path1.startswith('/private/'): path1 = '/private' + path1 # KLUDGE: allow for altered temp path self.assertEqual("mactypes.Alias(u%r)" % path1, repr(self.f)) #print "alias path 1: %s" % f.path # e.g. /private/tmp/py-mactypes-test.VLrUW7 self.assertEqual(path1, self.f.path) # get desc #print `f.desc.type, f.desc.data` # alis, [binary data] self.assertEqual('alis', self.f.desc.type) # check alias keeps track of moved file os.rename(path1, self.path2) # print "alias path 2: %r" % f.path # /private/tmp/moved-py-mactypes-test.VLrUW7 self.assertEqual(self.path2, self.f.path) self.assertEqual("mactypes.Alias(u%r)" % self.path2, repr(self.f)) # check a FileNotFoundError is raised if getting path/FileURL for a filesystem object that no longer exists os.remove(self.path2) self.assertRaises(MacOSError, lambda:self.f.path) # File not found. self.assertRaises(MacOSError, lambda:self.f.file) # File not found.
def test_6(self): sa = osax.OSAX( 'Standardadditions', aemapp=aem.Application("/System/Library/CoreServices/Finder.app/")) self.assertEqual(65, sa.ASCII_number('A')) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None))
def test_5(self): pid = int( commands.getoutput("top -l1 | grep Finder | awk '{ print $1 }'")) sa = osax.OSAX('Standardadditions', pid=pid) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None)) self.assertEqual(65, sa.ASCII_number('A'))
def test_file(self): path = '/Applications/TextEdit.app' d = self.c.pack(mactypes.Alias(path)) self.assertEqual(path, self.c.unpack(d).path) path = '/Applications/TextEdit.app' d = self.c.pack(mactypes.File(path)) self.assertEqual(path, self.c.unpack(d).path)
def __init__(self, path, **kwargs): """ path : path to InDesign file :Keywords: copy_from : path to template file (only used if path doesn't exist) """ self.path = os.path.abspath(compose(path)) if 'copy_from' in kwargs \ and os.path.exists(os.path.abspath(compose(kwargs['copy_from']))) \ and not os.path.exists(self.path): shutil.copy(os.path.abspath(compose(kwargs['copy_from'])), self.path) # Finder.copy? if os.path.exists(self.path): self.document = InDesign.open(mactypes.Alias(self.path)) else: self.document = InDesign.make(new=k.document).save(to=mactypes.File(self.path)) # not chainable! self.alias = mactypes.Alias(self.path) pref = self.document.pages[1].margin_preference self.defaults['rect'] = [ pref.top()[0], pref.left()[0], pref.bottom()[0], pref.right()[0] ]
def test_4(self): sa = osax.OSAX('Standardadditions', id='com.apple.finder') sa.activate() self.assertEqual({ osax.k.button_returned: '', osax.k.gave_up: True }, sa.display_dialog('test', giving_up_after=1)) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None))
def add(self, files): """Add files to playlist Add provided files to the playlist """ if not isinstance(files, list): files = [files] self.client.add([mactypes.Alias(entry) for entry in files], to=self.playlist) self.__update_len__()
def comment(path): if not appscript: return False finder = appscript.app('Finder') alias = mactypes.Alias(path) try: return finder.files[alias].comment.get() except: return ""
def test_5(self): pid = int( commands.getoutput("top -l1 | grep Finder | awk '{ print $1 }'")) sa = osax.OSAX('Standardadditions', pid=pid) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None)) sa.activate() self.assertEqual({ osax.k.button_returned: '', osax.k.gave_up: True }, sa.display_dialog('test', giving_up_after=1))
def test_5(self): p = subprocess.Popen("top -l1 | grep Finder | awk '{ print $1 }'", shell=True, stdout=subprocess.PIPE) p.wait() pid = int(p.stdout.read()) sa = osax.OSAX('Standardadditions', pid=pid) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None)) sa.activate() self.assertEqual({ osax.k.button_returned: '', osax.k.gave_up: True }, sa.display_dialog('test', giving_up_after=1))
def move(self, paths, to=None, to_idiom=None): """ to_idiom ['trash'] """ if not to and not to_idiom: return # raise error? if not isinstance(paths, list): paths = [path] else: paths = [self.reference_from_path(p) for p in paths] if not to_idiom and to: the_to = mactypes.Alias(to) elif to_idiom: the_to = getattr(self._app_ref, to_idiom.lower()) self.application.move(paths, to=the_to)
def deltags(path, *tags): if not appscript: return False finder = appscript.app('Finder') alias = mactypes.Alias(path) comment = "" try: comment = finder.files[alias].comment.get() except: pass for tag in tags: comment = re.sub("\\s*%s" % tag, "", comment) try: finder.files[alias].comment.set(comment) except: pass
def addtags(path, *tags): if not appscript: return False finder = appscript.app('Finder') alias = mactypes.Alias(path) comment = "" try: comment = finder.files[alias].comment.get() except: return False for tag in tags: try: if tag not in comment: if comment: finder.files[alias].comment.set(comment + ' ' + tag) else: finder.files[alias].comment.set(tag) except: pass
template = Template(render_template, html) ####### def write(path, txt): f = open(path, 'w') f.write(txt) f.close() def listPeopleWithPhones(): p = app('Address Book').people[its.phones != []] people = zip(p.last_name.get(), p.first_name.get(), p.phones.label.get(), p.phones.value.get()) result = [] for person in people: last, first, locations, numbers = person name = ', '.join([s for s in [last, first] if s != k.missing_value]) result.append((name, zip(numbers, locations))) result.sort(lambda i, j: cmp(i[0].lower(), j[0].lower())) return result page = template.render(listPeopleWithPhones()) path = os.tmpnam() + '.html' write(path, page) app('Safari').open(mactypes.Alias('/private' + path))
def test_3(self): sa = osax.ScriptingAddition('Standardadditions', creator='MACS') self.assertEqual(65, sa.ASCII_number('A')) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None))
def ComposedAlias(path): """`mactypes.Alias` of unicode POSIX `path`. (existing files only!)""" return mactypes.Alias(compose(path))
#!/usr/bin/env python # Opens a file in TextEdit. from appscript import * import mactypes app('TextEdit').open(mactypes.Alias('/Users/JSmith/ReadMe.txt'))
def relocate_track(lib, track_id, new_location): matching_tracks = lib.tracks[appscript.its.database_ID == track_id].get() if len(matching_tracks) != 1: raise Exception('QQ') track_meta = matching_tracks[0] track_meta.location.set(mactypes.Alias(new_location))
def test_4(self): sa = osax.OSAX('Standardadditions', id='com.apple.finder') self.assertEqual(65, sa.ASCII_number('A')) self.assertEqual( mactypes.Alias("/System/Library/CoreServices/Finder.app/"), sa.path_to(None))
def reference_from_path(self, path): """ Returns a Finder reference form ... not quite the same as alias reference form! """ return self.application.items[mactypes.Alias(path)]