Last active
September 28, 2016 18:09
-
-
Save SergKolo/5a1f488d3f05d370ecef04401619429d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
# Author: Serg Kolo,<[email protected]> | |
# Date: September 28, 2016 | |
# Purpose: Monitoring script that shutsdown | |
# system if logout occurs or chrome exits | |
# Written for: http://askubuntu.com/q/828524/295286 | |
from gi.repository import Gdk | |
import dbus | |
import os | |
import threading | |
import subprocess | |
def get_dbus(bus_type,obj,path,interface,method,*argv): | |
if bus_type == "session": | |
bus = dbus.SessionBus() | |
if bus_type == "system": | |
bus = dbus.SystemBus() | |
proxy = bus.get_object(obj,path) | |
method = proxy.get_dbus_method(method,interface) | |
if argv: | |
return method(*argv) | |
else: | |
return method() | |
def shutdown(): | |
''' Wrapper for dbus Shutdown method ''' | |
get_dbus('session', | |
'com.canonical.Unity', | |
'/com/canonical/Unity/Session', | |
'com.canonical.Unity.Session', | |
'Shutdown',None) | |
def is_inhibited(): | |
''' wrapper for IsInhibited dbus method''' | |
return get_dbus('session', | |
'org.gnome.SessionManager', | |
'/org/gnome/SessionManager', | |
'org.gnome.SessionManager', | |
'IsInhibited', | |
1) | |
def is_chrome_running(): | |
'''checks output of pgrep for | |
any chrome processes''' | |
try: | |
null=open(os.devnull,'w') | |
subprocess.check_call(['pgrep','-f','chrome'],stdout=null,stderr=null) | |
except subprocess.CalledProcessError: | |
return False | |
else: | |
return True | |
def inhibit_logout(): | |
''' Inhibits log out temporarily so that we have | |
enough time to shutdown ''' | |
# pretend we are root window | |
# and inhibit logout on our behalf | |
root_window_xid = int(Gdk.Screen.get_default().get_root_window().get_xid()) | |
get_dbus('session', | |
'org.gnome.SessionManager', | |
'/org/gnome/SessionManager', | |
'org.gnome.SessionManager', | |
'Inhibit', | |
'root_window', | |
root_window_xid, | |
'TEST REASON', | |
1) | |
# once the inhibitor is removed, shutdown | |
while is_inhibited(): | |
pass | |
shutdown() | |
def capture_chrome(): | |
# wait for chrome to start | |
while not is_chrome_running(): | |
pass | |
# start waiting till it exits | |
while is_chrome_running(): | |
pass | |
# once chrome exits, shutdown | |
shutdown() | |
def main(): | |
''' program entry point''' | |
threading.Thread(target=inhibit_logout).start() | |
threading.Thread(target=capture_chrome).start() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment