def pause(): """pause youtube videos""" code = """ on function() tell application "Google Chrome" repeat with w in every window repeat with t in every tab of w if "youtube" is in (get URL of t) then tell t set is_playing to execute javascript "!!Array.prototype.find.call(document.querySelectorAll('audio,video'),function(elem){return elem.duration > 0 && !elem.paused})" if is_playing is true then execute javascript "document.getElementsByClassName('ytp-play-button ytp-button')[0].click();" end if end tell end if end repeat end repeat end tell end function try function() on error errorMessage number errorNumber if errorNumber is equal to -1719 then return end if error errorMessage number errorNumber end try """ return applescript.run(code)
def playing_urls(): """return a list of playing urls""" code = """ on function() tell application "Google Chrome" repeat with w in every window repeat with t in every tab of w if "youtube" is in (get URL of t) then tell t set is_playing to execute javascript "!!Array.prototype.find.call(document.querySelectorAll('audio,video'),function(elem){return elem.duration > 0 && !elem.paused})" if is_playing is true then log (get URL of t) end if end tell end if end repeat end repeat end tell end function try function() on error errorMessage number errorNumber if errorNumber is equal to -1719 then return end if error errorMessage number errorNumber end try """ return applescript.run(code).err.splitlines()
def location(): cmdfile = "./click.scpt" r = applescript.run(cmdfile) if r.out == 'false': print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "xcode location failed") return False else: return True
def focus(name: str): if sys.platform == 'darwin': # applescript hangs if target app not running for proc in psutil.process_iter(): if proc.name() == name: applescript.run(f'tell application "{name}" to activate') return raise Exception(f'Could not find application {name}') elif sys.platform == 'win32': # https://stackoverflow.com/questions/1888863/how-to-get-main-window-handle-from-process-id wmgr = WindowMgr() wmgr.find_window_wildcard(f'.*{name}.*') wmgr.set_foreground() else: raise Exception('Unsupported platform')
def _run_script(self, script): rtn = applescript.run(script) if rtn.out == 'true': return True elif rtn.out == 'false': return False else: raise SpotifyControllerException( "Error: unrecognised spotify OSA response")
def get_info(app: str) -> Optional[MediaInformation]: """Get media information with apple script. Parameters ---------- app : str The name of the application Returns ------- Optional[MediaInformation] MediaInformation object Examples -------- >>> ans = get_info("Spotify") >>> assert ans is None or isinstance(ans, MediaInformation) """ script: str = f""" on run if application "{app}" is running then tell application "{app}" set currentInfo to {{name of current track, "|", artist of current track, "|", player position, "|", player state, "|", duration of current track}} end tell else set currentInfo to "Empty" end if return currentInfo end run """ r = applescript.run(script) logger.debug(r.out) ans: Optional[MediaInformation] = None if r.code == 0 and r.out != "Empty": segments = r.out.split(", ") ans = MediaInformation( segments[0], segments[2], float(segments[4]), { "playing": 2, "paused": 1, "stopped": 0 }.get(segments[6], 0), float(segments[8]) // 1000 if "." not in segments[8] else float(segments[8]), ) logger.debug(ans) return ans
def giveCredit(self, credit, speak=False, pauseSecs=0, voice=None, closeImage=True): if voice == None: voice = self.voice # Show a picture imagePath = os.path.expanduser('{}/{}'.format(self.imageDir, credit['imageFile'])) script = 'set x to open POSIX file "{}"'.format(imagePath) if self.debug: print(script) r= applescript.tell.app("Preview", script) # show some text print(credit['textCredit']) for k in ['Work Stream','Driver Project']: if k in credit: print('{}:{}'.format(k, credit[k])) # show some text if 'Driver Project' in credit: script = 'set value of cell 2 of row 1 of sheet 1 of workbook "DemoBanner.xlsx" to "{}"'.format(credit['Driver Project']) r= applescript.tell.app("Microsoft Excel", script) if 'Work Stream' in credit: script = 'set value of cell 2 of row 2 of sheet 1 of workbook "DemoBanner.xlsx" to "{}"'.format(credit['Work Stream']) r= applescript.tell.app("Microsoft Excel", script) if 'Implementation' in credit: script = 'set value of cell 2 of row 3 of sheet 1 of workbook "DemoBanner.xlsx" to "{}"'.format(credit['Implementation']) r= applescript.tell.app("Microsoft Excel", script) if credit['g4ghStd']: self.formatCells('GA4GHStd') else: self.formatCells('GeneralAPI') # speak the credit if asked if speak: #command = '/usr/bin/say "{}"'.format(credit) #os.system(command) script = 'say "{}" using "{}"'.format(credit['phoneticCredit'], voice) if self.debug: print (script) r= applescript.run(script) self.runAppleScript(script) # hold as requested if pauseSecs == 0: input ( "press any key to continue" ) else: time.sleep(pauseSecs) # move on if closeImage: r= applescript.tell.app("Preview", 'close window 1') r= applescript.tell.app("Microsoft Excel", 'set value of range "B1:B3" of sheet 1 of workbook "DemoBanner.xlsx" to ""') self.formatCells('gaPlain')
def track_info(self): rtn = applescript.run(self.scripts.get_info).out.split(',') info = dict() if rtn != None: if len(rtn) != 4: rtn = [""] * 4 info = { 'name': rtn[0], 'artist': rtn[1], 'album': rtn[2], 'artwork_url': rtn[3] } return info
def list_library_photos_applescript(photos_library, verbose=False, case_sensitive=False): """Returns a dict of all the photo-file-names in the MacOS Photos library by querying Photos using applescript. This should work for all versions of Photos, however it can be slow (up to 5 mins for a library of 20,000 media items. The key is the photo filename and the value just True.""" list_library_alias = create_macos_alias(photos_library) if verbose: print("Using AppleScript to query library {}".format(list_library_alias), flush=True) list_script = """-- generated file - do not edit tell application "Photos" activate delay 2 open "{}" delay 2 set mediaItems to every media item repeat with mediaItem in mediaItems set mediaItemFileName to filename of mediaItem log (mediaItemFileName as string) end repeat end tell """.format(list_library_alias) list_process = applescript.run(list_script, background=True) while list_process.running: if verbose: print("Waiting for Photos to list all media items...", flush=True) sleep(process_wait_sleep_time) photos = dict() for line in list_process.text.splitlines(): if case_sensitive: photos[line] = True else: photos[line.lower()] = True return photos
#!/usr/bin/env python3 import applescript import time # test cmd = """tell application "System Events" keystroke "c" using command down delay 0.25 end tell""" t1 = time.perf_counter() applescript.run(cmd) applescript.run(cmd) t2 = time.perf_counter() print(f"Python ran code in {t2 - t1:0.4f} seconds") t1 = time.perf_counter() cmd = """tell application "System Events" keystroke "v" using command down end tell""" t1 = time.perf_counter() r = applescript.run(cmd) t2 = time.perf_counter() print(f"Python ran code in {t2 - t1:0.4f} seconds")
print(colored('[' + str(datetime.datetime.now()) + ']', 'green'), colored('Download done', 'green')) print(colored('[' + str(datetime.datetime.now()) + ']', 'green'), colored('Save wallpaper as file...', 'green')) open(imagedir + image_name, 'wb').write(r.content) print(colored('[' + str(datetime.datetime.now()) + ']', 'green'), colored('Save wallpaper as file done', 'green')) else: print(colored('[' + str(datetime.datetime.now()) + ']', 'red'), colored('Error download file!', 'red')) import applescript script = str('tell application "Finder" to set desktop picture to POSIX file ') + \ '"' + imagedir + image_name + '"' print(colored('[' + str(datetime.datetime.now()) + ']', 'green'), colored('Setup wallpaper...', 'green')) r = applescript.run(script) if r.code == 0: print(colored('[' + str(datetime.datetime.now()) + ']', 'green'), colored('Setup wallpaper done', 'green')) else: print(colored('[' + str(datetime.datetime.now()) + ']', 'red'), colored('Setup wallpaper error!', 'red')) print(colored('[' + str(datetime.datetime.now()) + ']', 'green'), colored('Remove xml file...', 'green')) if os.path.isfile(imagedir + 'bing.xml'): os.remove(imagedir + 'bing.xml') print(colored('[' + str(datetime.datetime.now()) + ']', 'green'), colored('Remove xml file done', 'green')) else: print(colored('[' + str(datetime.datetime.now()) + ']', 'red'), colored('Remove xml file eror!', 'red'))
def notification(title, text, icon=None): command = 'display notification ' + '\"' + text + '\"' applescript.run(command, background=True)
def pauseMusic(path): applescript.run(f"{path}appleScripts/pauseMusicScript.applescript")
import applescript import time from pathlib import Path list_script = """ tell application "Photos" set mediaItems to every media item repeat with mediaItem in mediaItems set mediaItemFileName to filename of mediaItem log (mediaItemFileName as string) end repeat end tell """ print("Starting") start_time = time.time() list_process = applescript.run(list_script) while list_process.running: print("waiting...") time.sleep(2) end_time = time.time() total_time = end_time - start_time line_count = list_process.text.count('\n') print("took {} seconds, contains {} lines".format(total_time, line_count)) with Path('./photos_list_out.txt').open('w') as stream: stream.write(list_process.text)
import applescript import os import time current_path = os.getcwd() while True: message = applescript.run( os.path.join(current_path, "receiveMessage.applescript"), True) if message.code != 0 or message.code != "None": print("Code: " + str(message.code)) print("Out: " + str(message.out)) print("Error: " + str(message.err))
caffeinate = subprocess.Popen('caffeinate') def exit_handler(): caffeinate.terminate() caffeinate.kill() atexit.register(exit_handler) while True: url = "https://www.redbus.in/next-date/130/134/Pune/Vijayawada/20%20Dec%202019/EN" seatThreshold = 12 operatorName = 'nh safari' # Set the headers like we are a browser. headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36' } responseJson = requests.get(url, headers=headers).json() for row in responseJson['srpRow']: if operatorName in row['operator'].lower(): seats = list(map(int, re.findall('\d+', row['seats']))) if min(seats) <= seatThreshold: applescript.run("set volume output volume 100") while True: applescript.run('say "Book Tickets."') time.sleep(0.2) time.sleep(10)
def sendSms(sms,number): script = f"""tell application "Messages" send "{sms}" to buddy "{number}" of service "E:[email protected]" end tell""" applescript.run(script)
def _execute(code): return applescript.run(code).out
#!/usr/bin/env python import applescript r = applescript.run('["hello", "world"].join(" ");', javascript=True) print(r.out)
def playMusic(path): applescript.run(f"{path}appleScripts/playMusicScript.applescript")
#!/usr/bin/env python import applescript r = applescript.run('return 1') print(r.out)
def sleepSchedule(inTime,path): time.sleep(int(inTime)) applescript.run(f"{path}appleScripts/delaySleep.applescript")
#!/usr/bin/env python import applescript r = applescript.run('log "hello world"') print(r.err)
import applescript code = "set volume input volume 100" r = applescript.run(code)
def change_background(img): applescript.run( 'tell application "System Events" to tell every desktop to set picture to "{}"' .format(os.path.realpath(img)))