def setVolume(self, volume): osascript.run("set volume output volume " + str(volume)) code, out, err = osascript.run("output volume of (get volume settings)") if (err): return False else: return out
def presentationMode(self, sender): if (sender.title == "on"): self.presentation.on.set_callback(None) self.presentation.off.set_callback(self.presentationMode) setPresentationMode(True) osascript.run(''' tell application "System Events" set listOfProcesses to (name of every process where (background only is false) and (name ≠ "finder")) tell me to set selectedProcesses to choose from list listOfProcesses with prompt "Close windows before presenting?" default items "None" OK button name {"Close Selcted"} cancel button name {"Cancel"} with multiple selections allowed end tell --The variable `selectedProcesses` will contain the list of selected items. repeat with processName in selectedProcesses do shell script "Killall " & quoted form of processName end repeat ''') rumps.notification(title="Presentation Mode: Enabled", subtitle=f"", message='', sound=False) else: self.presentation.off.set_callback(None) self.presentation.on.set_callback(self.presentationMode) setPresentationMode(False) rumps.notification(title="Presentation Mode: Disabled", subtitle=f"", message='', sound=False)
def setSoundLevelDarwin(self, soundLevel: int): self.label_percent.config(text=str(int(20 * soundLevel)) + "%") osascript.run("set volume output volume " + str(int(20 * soundLevel))) if (soundLevel == 0): self.soundStateOn = False else: self.soundStateOn = True
def _iterm_exec(cmd): apple_script = '''tell application "iTerm2" tell current session of current window select split vertically with default profile write text "{}" end tell end tell '''.format(_apple_script_string_escape(cmd)) osascript.run(apple_script)
def main(): # For webcam input: cap = cv2.VideoCapture(0) detector = HandDetection() while cap.isOpened(): success, image = cap.read() if not success: print("Ignoring empty camera frame.") # If loading a video, use 'break' instead of 'continue'. continue image = detector.findHands(image) image, handList = detector.findPosition(image) if len(handList) > 1: cv2.line(image, handList[0], handList[1], (255, 0, 255), 1) cx, cy = tuple( map(operator.floordiv, tuple(map(operator.add, handList[0], handList[1])), (2, 2))) cv2.circle(image, (cx, cy), 5, (0, 0, 255), 5) length = math.hypot(handList[0][0] - handList[1][0], handList[0][1] - handList[1][1]) # A number between 0 to 100 normelizeLen = normelizeLength(length) osascript.run("set volume output volume " + str(normelizeLen)) _, out, _ = osascript.run("output volume of (get volume settings)") print(str(normelizeLen) + "---" + str(out)) # # Flip the image horizontally for a later selfie-view display, and convert # # the BGR image to RGB. # image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB) # # To improve performance, optionally mark the image as not writeable to # # pass by reference. # image.flags.writeable = False # results = hands.process(image) # # Draw the hand annotations on the image. # image.flags.writeable = True # image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # if results.multi_hand_landmarks: # for hand_landmarks in results.multi_hand_landmarks: # mp_drawing.draw_landmarks( # image, hand_landmarks, mp_hands.HAND_CONNECTIONS) cv2.imshow('Volume controlled by Hands', image) if cv2.waitKey(5) & 0xFF == 27: break cap.release()
def getBrowserAndPlayerData(): applescript = ''' on run if application "Spotify" is running then tell application "Spotify" set playerData to {"Spotify", artist of current track, name of current track, player state} end tell else if application "Music" is running then tell application "Music" set playerData to {"Music", artist of current track, name of current track, player state} end tell else set playerData to {"none", "none", "none", "none"} end if if (application "Google Chrome" is running) and (exists (front window of application "Google Chrome")) then tell application "Google Chrome" set browserData to {"Chrome", title of active tab of front window} end tell else if (application "Safari" is running) and (exists (front window of application "Safari")) then tell application "Safari" set browserData to {"Safari", name of current tab of front window} end tell else set browserData to {"none", "none"} end if set currentData to {playerData, browserData} return currentData end run ''' return osascript.run(applescript, background=False)
def __run_osa(cmd): code, out, err = osascript.run('' 'tell application "Tunnelblick"\n' f'{cmd}\n' 'end tell') if code == 0: return out else: raise err
def openSearchScript(self): ret, result, err = osascript.run( "return display dialog \"\" default answer \"\"") if (ret): return None entry = result.split(":")[2] if (len(entry.strip()) == 0): return None return entry
def getInfo() -> str: #cmd = ["osascript", os.path.join(os.path.dirname(os.path.realpath(__file__)), "printAppTitle.scpt")] #p = subprocess.run(cmd, stdout=PIPE) info = [] code, out, err = osascript.run(''' global frontApp, frontAppName, windowTitle set windowTitle to "" tell application "System Events" set frontApp to first application process whose frontmost is true set frontAppName to name of frontApp tell process frontAppName try tell (1st window whose value of attribute "AXMain" is true) set windowTitle to value of attribute "AXTitle" end tell end try end tell end tell return frontAppName ''') info.append(out.strip()) code, out, err = osascript.run(''' global frontApp, frontAppName, windowTitle set windowTitle to "" tell application "System Events" set frontApp to first application process whose frontmost is true set frontAppName to name of frontApp tell process frontAppName try tell (1st window whose value of attribute "AXMain" is true) set windowTitle to value of attribute "AXTitle" end tell end try end tell end tell return windowTitle ''') info.append(out.strip()) return info
def get_info(app: str = "Spotify") -> Tuple[str, str, float, str, float]: """ Get information about the track in play. Parameters ---------- app : str, optional Name of the app, by default "Spotify" Returns ------- Tuple[str, str, float, str, float] Title, artists, position, status, duration of the track Examples -------- >>> title, artists, position, status, duration = get_info("Spotify") >>> status in [None, "playing", "paused"] True """ template = 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 end if return currentInfo end run """ code, res, error = osascript.run(template, background=False) title = artists = position = status = duration = None if code == 0: segments = res.split("|") title, artists, position, status, duration = map( lambda x: x.strip(' ,"'), segments) if all(x is not None for x in [title, artists, position, status, duration]): position = float(position) duration = float(duration) if duration <= 1200: duration = duration else: duration /= 1000 title = HanziConv.toSimplified(title) title = re.sub(r"[[《<((【「{].*?[]】)」}>)》]", "", title) title = title.rsplit("-", 1)[0] else: logger.debug(error) return title, artists, position, status, duration
def change(self, path): '''sets the background if the path is to a file ''' if isfile(path): script = f'''tell application "System Events" to set picture of every desktop to "{path}" END''' res = osascript.run(script) if res[2] != '': return Exception sleep(1) self._PREVIOUS = self._CURRENT self._CURRENT = path else: return Exception
def operate_powerpoint(action): if action == "move-next": osascript.run( """ tell application "Microsoft PowerPoint" activate tell application "System Events" keystroke (ASCII character 28) end tell end tell """ ) elif action == "move-prev": osascript.run( """ tell application "Microsoft PowerPoint" activate tell application "System Events" keystroke (ASCII character 29) end tell end tell """ )
def notify(message, title, subtitle, sound): """ Posts macOS X notification Args: message (str): The message title (str): The title subtitle (str): The subtitle sound (str): The macOS X sound """ code, out, err = osascript.run( 'display notification "{0}" with title "{1}" subtitle "{2}" sound name "{3}"' .format(message, title, subtitle, sound))
def toggleMuteButton(platform): """ Returns True if successful or False if error """ if platform == "darwin": code, out, err = osascript.run("""tell application "Firefox" activate tell application "System Events" to keystroke "d" using command down end tell""") if code == 0: return (True, "") else: return (False, err) # TODO Implement for linux using xdotool if platform in ['linux', 'linux2']: pass
def _setupKeybinds(self): self.ctrlDown = False self.shiftDown = False if (self.prevKeyHook): keyboard.unhook(self.prevKeyHook) # threading.Thread(target=lambda:keyboard.hook(self.keyEvent, suppress=True), daemon=True).start() self.prevKeyHook = keyboard.hook(self.keyEvent, suppress=True) self.keybinds["f"] = self.doSearch self.keybinds["space"] = self.togglePlaying self.keybinds[","] = self.playPrev self.keybinds["."] = self.playNext self.keybinds["z"] = self.playPrev self.keybinds["x"] = self.playNext self.keybinds["-"] = self.decrementVolume self.keybinds["="] = self.incrementVolume self.keybinds["["] = self.decrementTime self.keybinds["]"] = self.incrementTime self.keybinds["0"] = lambda: self.seekPercent(0) self.keybinds["1"] = lambda: self.seekPercent(10) self.keybinds["2"] = lambda: self.seekPercent(20) self.keybinds["3"] = lambda: self.seekPercent(30) self.keybinds["4"] = lambda: self.seekPercent(40) self.keybinds["5"] = lambda: self.seekPercent(50) self.keybinds["6"] = lambda: self.seekPercent(60) self.keybinds["7"] = lambda: self.seekPercent(70) self.keybinds["8"] = lambda: self.seekPercent(80) self.keybinds["9"] = lambda: self.seekPercent(90) self.keybinds["a"] = self.toggleAutoplay self.keybinds["l"] = self.toggleLooping self.keybinds["c"] = self.clearQueue self.keybinds["q"] = self.doQuit self.keybinds["r"] = self.reboot self.keybinds["t"] = lambda: threading.Thread( target=lambda: osascript.run( f"return display alert \"Threads: {threading.active_count()}\"" ), daemon=True).start()
def getInfoWindowsDarwin(self): # on cherche sur les anciennes version de spotify le titre Spotify options = kCGWindowListOptionAll windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) #result = osascript.run("""set appName to "Spotify" \n if application appName is running then \n tell application "Spotify" \n set c to current track \n return {(artist of c), (album of c)} \n end tell \n else \n return "not running" \n end if""") for window in windowList: if window["kCGWindowOwnerName"] == "Spotify": (error_code, current_track, other) = osascript.run( """tell application "Spotify" \n set c to current track \n return {(artist of c), (album of c)} \n end tell""" ) if current_track == ",": return ("Error", "Nothing playing") else: try: artist, track = current_track.split(",", 1) return (artist.strip(), track.strip()) except Exception as e: return ("Error", "Nothing playing")
def get_info(debug=False): code, res, error = osascript.run(''' on run if application "Spotify" is running then tell application "Spotify" set currentInfo to {"Spotify", artist of current track, "###", name of current track, player position, player state, duration of current track} end tell else if application "Music" is running then tell application "Music" set currentInfo to {"Music", artist of current track, "###", name of current track, player position, player state, duration of current track} end tell end if return currentInfo end run ''', background=False) if debug: print(res, error, code) if res: info = res.split('###') application, *artists = map(lambda x: x.strip(), info[0].strip(' ,').split(',')) artists = ','.join(artists) *title, position, status, duration = map( lambda x: x.strip(), info[1].strip(' ,').split(',')) title = ','.join(title) if float(duration) <= 1200: duration = float(duration) position = float(position) else: duration = float(duration) / 3600 position = float(position) title = HanziConv.toSimplified(title) return application, artists, title, position, status, duration else: return None
def TuneVol(self, perc): osa.run("set volume output volume " + str(perc))
def extract_votes(soup_body): return 123 def get_feed(): response = requests.get(URL) return response.content if __name__ == '__main__': LINKS_FETCHED = 0 LINKS_STACK = [] result = feedparser.parse(get_feed()) for e in result.entries: url, votes, tags = get_link_data(e.link) data = { 'url': url, 'title': e.title, 'tags': tags, } LINKS_STACK.append(data) output_filename = dump_to_file(LINKS_STACK) osascript.run( f'display notification "Dumped to file: {output_filename}" with title "wyko.py" subtitle "Fetched OK"' )
def mute(self ): code, out, err = osascript.run('set volume output muted TRUE') return out
def getPath(self): return osascript.run('tell application "Finder" to get posix path of (get desktop picture as alias)')[1]
# VIDEO FILE PATH case if path.is_file(): if '.mp4' in clipboard_value or '.mov' in clipboard_value: files = [clipboard_value] path_case = 'file' print(' path_case:', path_case) else: colored_error_message = colored('Invalid video file path...', 'red', attrs=['reverse', 'blink']) print(' ❌ ERROR! ' + colored_error_message) # Posting macOS X notification notify(title='video_compressor.py', subtitle='Video compression failed :-(', message='Invalid video file path...', sound_path='/System/Library/Sounds/Sosumi.aiff') # Exiting the Terminal window osascript.run('tell application "iTerm2" to close first window') # Exiting the program exit(1) # DIRECTORY PATH case elif path.is_dir(): path_case = 'folder' print(' path_case:', path_case) # Getting all the ".mp4" and ".mov" files of the TARGET_DIRECTORY print(' Getting all the ".mp4" and ".mov" files of the TARGET_DIRECTORY') # (Cf.: "Python glob multiple filetypes" (https://www.xspdf.com/help/50822753.html)) files = [] for ext in ('*.mp4', '*.mov'): files.extend(glob(join(clipboard_value, ext))) print(' Video files in TARGET_DIRECTORY:\n', files) if len(files) == 0:
def ReceiveVol(self): return osa.run("get output volume of (get volume settings)")[1]
def openSafari(self ): code, out, err = osascript.run('tell app "Safari" to activate') return out
def emptyTrash(self ): code, out, err = osascript.run('tell application "Finder" to empty trash') return out
def volumeUp(self, by=10): code, out, err = osascript.run("output volume of (get volume settings)") return self.setVolume(int(out) + by)
callInfo['endminute'] = endDate.minute callInfo['endsecond'] = endDate.second if (datetime.datetime.now() - endDate).total_seconds() < 60: if debug: print("skipping call, call has not ended yet") continue # update last processed id currentprocessed = max(currentprocessed, call.id) # fill AppleScript template if debug: print("Executing AppleScript") script = appleScript(callInfo) code, out, err = osascript.run(script) if code != 0: print("osascript return code = " + str(code)) print(out) print(err) hadError = True # finally write new lastprocessed into config if not hadError: config['main']['lastprocessed'] = str(currentprocessed) with open(cfgname, 'w') as configfile: config.write(configfile) if firstRun: print( r'\o/ - everything seems to work. The latest call on your call list has the Id '
def shutDown(self ): code, out, err = osascript.run('tell app "System Events" to shut down') return out
#! /usr/bin/python import osascript, random # List of nice quotes. morningMessages = [ "The two most powerful warriors are patience and time.", "Lost time is never found again.", "Time is the most valuable thing a man can spend.", "You can't have a better tomorrow if you are thinking about yesterday all the time.", "All we have to decide is what to do with the time that is given us.", "Your time is limited, so don't waste it living someone else's life." ] randomVal = int(random.uniform(0, len(morningMessages) - 1)) osascript.run('display notification "' + morningMessages[randomVal] + '" with title "Good Morning" sound name "Submarine"')
total = pd.read_csv(f'{domain}_confirmed_US.csv').drop( [ 'UID', 'iso2', 'iso3', 'code3', 'FIPS', 'Admin2', 'Country_Region', 'Lat', 'Long_', 'Combined_Key' ], axis=1).groupby('Province_State').sum() return CV( 'time_series_us', total, ) domain = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19' mplstyle.use('seaborn-pastel') gap = 7 days = 365 top = 1000 days2 = 50 if __name__ == '__main__': os.chdir(os.path.dirname(os.path.abspath(__file__))) notify = False for cv in getWorld(['Hong Kong', 'Macau', 'Hubei', 'Guangdong']), getUS(): if cv.compareDate(): cv.writeExcel() cv.plotTop() notify = True if notify: osascript.run('display notification "Coronavirus Updated"')