由于Python的GIL(全局解释器锁)限制,无法直接阻塞Windows关机过程。但是我们可以通过创建一个Windows服务来实现阻塞关机,并在服务中发送网络请求。

以下是实现步骤:

  1. 创建一个Windows服务,具体方法可以参考Microsoft官方文档:https://docs.microsoft.com/en-us/windows/win32/services/creating-a-simple-service-in-python

  2. 在服务的OnShutdown()方法中,发送网络请求告知电脑已关机,可以使用Python的requests库发送POST请求。

  3. 在发送成功后,继续执行服务的OnShutdown()方法,使计算机继续关机。

代码示例:

import requests
import win32serviceutil
import servicemanager
import win32event
import win32service

class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = "MyService"
    _svc_display_name_ = "My Service"
    _svc_description_ = "My Service Description"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcShutdown(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.send_shutdown_notification()
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        win32event.SetEvent(self.hWaitStop)

    def send_shutdown_notification(self):
        url = "http://example.com/shutdown"
        data = {"message": "shutdown"}
        response = requests.post(url, data=data)
        if response.status_code == 200:
            servicemanager.LogInfoMsg("Shutdown notification sent successfully")
        else:
            servicemanager.LogErrorMsg("Failed to send shutdown notification")

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 
                              servicemanager.PYS_SERVICE_STARTED, 
                              (self._svc_name_, ''))
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(MyService)

注意:以上代码仅为示例,需要根据实际需求进行修改。另外,创建Windows服务需要管理员权限

我想使用Python阻塞Windows关机过程并发送网络请求告知电脑已关机发送成功后继续关机。注意:不是取消关机而是阻止计算机关闭

原文地址: https://www.cveoy.top/t/topic/eUmm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录