简体   繁体   English

如何在Python中捕获系统挂起事件?

[英]How can I catch a system suspend event in Python?

I'm using ubuntu 12.04. 我正在使用ubuntu 12.04。 Is there a way to catch a suspend event in Python, ie if the laptop is going to suspend, do this...? 有没有办法在Python中捕获暂停事件,即如果笔记本电脑暂停,请执行此操作......? The same question for catching shutdown event. 捕获关闭事件的问题相同。

我认为最简单的方法是使用DBUS python接口并在'org.freedesktop.UPower'界面上监听'AboutToSleep'和/或'Sleeping'事件

If some one stumbles on the same problem, here's the code: 如果有人遇到同样的问题,这里是代码:

#!/usr/bin/env python

import dbus      # for dbus communication (obviously)
import gobject   # main loop
from dbus.mainloop.glib import DBusGMainLoop # integration into the main loop

def handle_resume_callback():
    print "System just resumed from hibernate or suspend"

def handle_suspend_callback():
    print "System about to hibernate or suspend"

DBusGMainLoop(set_as_default=True) # integrate into main loob
bus = dbus.SystemBus()             # connect to dbus system wide
bus.add_signal_receiver(           # defince the signal to listen to
    handle_resume_callback,            # name of callback function
    'Resuming',                        # singal name
    'org.freedesktop.UPower',          # interface
    'org.freedesktop.UPower'           # bus name
)

bus.add_signal_receiver(           # defince the signal to listen to
    handle_suspend_callback,            # name of callback function
    'Sleeping',                        # singal name
    'org.freedesktop.UPower',          # interface
    'org.freedesktop.UPower'           # bus name
)

loop = gobject.MainLoop()          # define mainloop
loop.run()                         # run main loop

You can extend this code, it listens for events from acpid, try to just print the string it receives and generate the event you want and see what the string looks like. 您可以扩展此代码,它从acpid侦听事件,尝试只打印它接收的字符串并生成您想要的事件并查看字符串的外观。

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/var/run/acpid.socket")
print "Connected to acpid"
while 1:
    for event in s.recv(4096).split('\n'):
        event=event.split(' ')
        if len(event)<2: continue
        print event
        if event[0]=='ac_adapter':
            if event[3]=='00000001': #plugged
                plugged() #Power plugged event
            else: #unplugged
                unplugged() #Power unplugged event
        elif event[0]=='button/power':
            power_button() #Power button pressed
        elif event[0]=='button/lid':
            if event[2]=='open':
                lid_open() #Laptop lid opened
            elif event[2]=='close':
                lid_close() #Laptop lid closed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM