1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
#!/usr/bin/env python
# systemd-inhibit-delay
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import argparse
import dbus
import os
import subprocess
import sys
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
class Inhibitor:
def __init__(self, bus, what, cmd):
if what == 'sleep':
self.signal_name = 'PrepareForSleep'
elif what == 'shutdown':
self.signal_name = 'PrepareForShutdown'
else:
raise Exception('for what, only sleep and shutdown supported')
if cmd == '':
raise Exception('command cannot be empty')
self.bus = bus
self.what = what
self.cmd = cmd
def start(self):
self.bus.add_signal_receiver(
self.sleep_handler,
dbus_interface='org.freedesktop.login1.Manager',
signal_name=self.signal_name
)
self.take_lock()
def sleep_handler(self, active):
if active:
subprocess.call(self.cmd)
if self.fd != -1:
os.close(self.fd)
self.fd = -1
else:
self.take_lock()
def take_lock(self):
login1 = self.bus.get_object('org.freedesktop.login1', '/org/freedesktop/login1')
self.fd = login1.Inhibit(self.what, 'systemd-inhibit-delay', '', 'delay',
dbus_interface='org.freedesktop.login1.Manager').take()
DBusGMainLoop(set_as_default=True)
parser = argparse.ArgumentParser(description='systemd inhibit delay')
parser.add_argument('cmd', help='the command to run (MUST EXIT WHEN READY)')
parser.add_argument('args', nargs=argparse.REMAINDER,
help='the command arguments')
parser.add_argument('--what', default='sleep',
help='what to delay, sleep or shutdown (default: sleep)')
args = parser.parse_args()
system_bus = dbus.SystemBus()
inhibitor = Inhibitor(system_bus, args.what, [args.cmd] + args.args)
inhibitor.start()
loop = GLib.MainLoop()
loop.run()
|