I need to detect when the user pressed "quit" in the dock menu.
My application is actually just a launcher for the backend server of a web interface. I keep it in the dock menu by manually waiting for the launched process to end (with poll and sleep). The actvity monitor showed it as not responding so I added a native function to process events like "touches". Not responding flag is now gone, but the user cannot quit this application (because the native functions processes the event, I guess).
I used ctypes to access that native function.
TVB = subprocess.popen(args)
coreFoundation = cdll.LoadLibrary('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation')
CFRunLoopRunInMode = coreFoundation.CFRunLoopRunInMode # the native function
CFRunLoopRunInMode.restype = c_int32 # its return type
CFRunLoopRunInMode.argtypes = [ c_void_p, c_double, c_bool ] # its arguments types
defaultMode = c_void_p.in_dll(coreFoundation, u'kCFRunLoopDefaultMode') # the default mode to process events
sleepTime = c_double(5) # the duration to process the events
retAfterSourceHandled = c_bool(0) # do NOT return after processing
while not TVB.poll(): # keep alive as long as TVB is alive
CFRunLoopRunInMode(defaultMode, sleepTime, retAfterSourceHandled)
sleep(5)
#detect 'quit' here and stop TVB, then quit
I will also consider other solutions to CFRunLoopRunInMode... Something like processNextEvent() would be ideal.
A possible solution to this problem is to use PyObjC and a custom UIApplicationDelegate implementation.
import AppKit
import Foundation
from PyObjCTools import AppHelper
class ApplicationDelegate(Foundation.NSObject):
""" MAC OS UI specific Delegate class """
def applicationDidFinishLaunching_(self, notification):
""" Here you could register a timer to pull your sub-processes, for example. """
pass
def applicationWillTerminate_(self, notification):
""" This is the hook you get for when the user clicks QUIT in dock """
pass
app = AppKit.NSApplication.sharedApplication()
delegate = ApplicationDelegate.alloc().init()
app.setDelegate_(delegate)
AppHelper.runEventLoop()
In the end PyObjC is not much different than the ctypes loads you tried, but it has some helper methods (like AppKit.NSRunLoop.currentRunLoop(), or AppHelper.stopEventLoop()) which could make the python code clearer.
For this solution I assume to have a Python project further packed for deployment with py2app. I used pyObjc version 2.3 (installed with easy_install in Python 2.7 on Mac OS x 10.7.5).
Related
I am on Windows. I want to run a Python Script that involves keyboard activity hence my PC mustn't lock screen or go to sleep. Instead of changing my PC Sleep Setting, I want to use Python code to keep my Screen Display On for the whole duration of my Python Script.
I modified the code here Prevent sleep mode python (Wakelock on python) but it doesn't work. My screen display still offs automatically. MY modified code as below:
class WindowsInhibitor:
'''Prevent OS sleep/hibernate in windows; code from:
https://github.com/h3llrais3r/Deluge-PreventSuspendPlus/blob/master/preventsuspendplus/core.py
API documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx'''
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
ES_DISPLAY_REQUIRED= 0x00000002
def __init__(self):
pass
def inhibit(self):
import ctypes
print("Preventing Windows from going to sleep")
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS | \
WindowsInhibitor.ES_DISPLAY_REQUIRED)
def uninhibit(self):
import ctypes
print("Allowing Windows to go to sleep")
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS)
import os
osSleep = None
# in Windows, prevent the OS from sleeping while we run
if os.name == 'nt':
osSleep = WindowsInhibitor()
osSleep.inhibit()
I am writing a script intended to be used by members of a project team. As part of the script, I am launching a 3rd party proprietary application run through Citrix. I am going to use the script mostly to send keys to this application, but the first step once it launches is for the user to log in.
Because I would like the user to log in while the script is running, rather than asking for user/pass from some kind of GUI input earlier, and because the time it takes Citrix to launch varies, I would like to include some kind of logic that detects when the user has logged in and then resume the script from there, rather than including an obnoxiously long implicit wait or risking the script timing out.
Is there a way to detect user keystrokes using win32com.client (or to detect a change in state of the application itself)? See below for the relevant code to launch the app:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run('C:\Citrix\[rest of path])
EDIT:
Per Vasily's suggestion in the comments below, I attempted to adapt the "hook and listen" code to my scenario, but was unsuccessful. When I launch my file, I don't even get an exception message in my terminal, I get a Windows pop-up that says Python encountered a problem and needs to quit.
This is how I adapted it:
#[omitting import lines for brevity]
def on_timer():
"""Callback by timer out"""
win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);
def on_event(args):
"""Callback for keyboard and mouse events"""
if isinstance(args, KeyboardEvent):
for i in range(1,100):
time.sleep(1)
if args.pressed_key == 'Lcontrol':
break
def init():
hk = Hook()
hk.handler = on_event
main_thread_id = win32api.GetCurrentThreadId()
t = Timer(55.0, on_timer) # Quit after 55 seconds
t.start()
hk.hook(keyboard=True, mouse=True)
At the point when the 3rd party Citrix app begins to launch in my main script, I call hookandlisten.init().
As a reminder, my goal is to wait until the user sends a certain keystroke (here I chose Control) before proceeding with the rest of the main script.
Solved this by eliminating the timer and unhooking the keyboard upon the correct keystroke:
import win32api
import win32con
from pywinauto.win32_hooks import Hook
from pywinauto.win32_hooks import KeyboardEvent
from pywinauto.win32_hooks import MouseEvent
def on_event(args):
"""Callback for keyboard and mouse events"""
if isinstance(args, KeyboardEvent):
if args.current_key == 'Lcontrol' and args.event_type == 'key down':
print("Success")
hk.unhook_keyboard()
return
def init():
hk.handler = on_event
hk.hook(keyboard=True, mouse=False)
hk = Hook()
I try to display the current windows for each click on the system.
I do this code :
from AppKit import NSWorkspace
def getwindows():
activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']
print activeAppName
return
def main():
getwindows()
main()
But only the current windows when i setup the script is displayed.
How can i bind this script in a loop with a click event ?
I already try to use Turtle but some errors appended.
Note that the activeApplication method of NSWorkSpace is deprecated. The following can be used to actively probe the running applications for their active status:
import AppKit
import time
rl = AppKit.NSRunLoop.currentRunLoop()
ws = AppKit.NSWorkspace.sharedWorkspace()
for i in xrange(10):
for app in ws.runningApplications():
if app.isActive():
print "active app:", app.localizedName()
date = AppKit.NSDate.date()
time.sleep(1)
rl.acceptInputForMode_beforeDate_( AppKit.NSDefaultRunLoopMode, date )
Active means it is the receiving keyboard input. Clicking on an application will cause it to become active. Note that the acceptInputForMode method must be called so that property changes are reflected in the current app. Run this program then click on various other applications -- you should see the active app change.
A kind of binding can be done through observers:
import AppKit
ws = AppKit.NSWorkspace.sharedWorkspace()
appL = ws.runningApplications()
class MyClass( AppKit.NSObject ):
def observeValueForKeyPath_ofObject_change_context_(self,
kpath, objid, change, context ):
print "path change", kpath, change['new'], appL[context].localizedName()
obj = MyClass.new()
for i in xrange(len(appL)):
appL[i].addObserver_forKeyPath_options_context_( obj,
"isActive", AppKit.NSKeyValueObservingOptionNew, i )
date = AppKit.NSDate.date().dateByAddingTimeInterval_( 10 )
rl = AppKit.NSRunLoop.currentRunLoop()
rl.acceptInputForMode_beforeDate_( AppKit.NSDefaultRunLoopMode, date )
for app in appL:
app.removeObserver_forKeyPath_( obj, "isActive" )
Run this program same as the last.
There are a few other properties of NSRunningApplication that you could probe/observe (such as hidden) but the list is quite short.
I'm developing my first app on python for OS X (and also generally on python) and i faced the problem… My current script parses sounds from iTunes and prints it in to the window. It looks like this
from Cocoa import *
from Foundation import *
from ScriptingBridge import *
class SocialTunesController(NSWindowController):
testLabel = objc.IBOutlet()
def windowDidLoad(self):
NSWindowController.windowDidLoad(self)
self.updateTrack()
def updateTrack(self):
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
current_track_info = "Name: " + iTunes.currentTrack().name() + "\nArtist: " + iTunes.currentTrack().artist() + "\nAlbum: " + iTunes.currentTrack().album()
self.testLabel.setStringValue_(current_track_info)
if __name__ == "__main__":
app = NSApplication.sharedApplication()
viewController = SocialTunesController.alloc().initWithWindowNibName_("SocialTunes")
viewController.showWindow_(viewController)
from PyObjCTools import AppHelper
AppHelper.runEventLoop()
The main problem is how to fire event when track is changes that it automatically would update the track info in current window…
iTunes posts a distributed notification when a track change occurs. You need to register a controller to listen for those notifications:
noteCenter = NSDistributedNotificationCenter.defaultCenter()
noteCenter.addObserver_selector_name_object_(theController,
objc.selector(theController.updateTrack_,
signature="v#:#"),
"com.apple.iTunes.playerInfo",
None)
And your updateTrack_() method needs to take one argument (aside from self), which is the posted notification.
You can use events with PyObjC, whether or not you can receive iTunes events depends on whether of not iTunes sends events. For all I know all iTunes status widgets just regularly poll if the iTunes track has changed.
I have written this little script to show current track playing on xmms2 on a notification widget using xmms client and pynotify, so when i run it i can see the widget popup with current artist and title using xmmsclient methods.
Can anybody give some hints about how to detect track change to notify automatically without having to run the script manually?
You connect the client library to a main loop, and register as a listener via the broadcast_ playback_current_id method. If you want the currently playing id when the script starts as well you can call the playback_current_id method.
Here is a small adaptation of tutorial6 in the xmms2-tutorial.git which uses the GLib Mainloop to drive the connection:
import xmmsclient
import xmmsclient.glib
import os
import sys
import gobject
def cb(result):
if not result.is_error():
print "Current: %(artist)s - %(title)s" % result.value()
ml = gobject.MainLoop(None, False)
xc = xmmsclient.XMMS("stackoverflow")
xc.connect()
conn = xmmsclient.glib.GLibConnector(xc)
xc.broadcast_playback_current_id(lambda r: xc.medialib_get_info(r.value(), cb))
ml.run()