用python检测关机事件 [英] Detect shutdown event with python

查看:38
本文介绍了用python检测关机事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Minecraft 基岩版服务器在我们的共享电脑上运行.我想通过 python 与它接口.但是,我遇到的一个问题是我的兄弟有时会重新启动我们的电脑或 Windows 更新.我需要知道如何检测关闭事件并在重新启动之前将关闭命令发送到服务器.我正在使用子进程库.

I have a Minecraft bedrock edition server running on our shared pc. I would like to interface with it via python. However, one problem I have is that my brothers sometimes restart our pc, or Windows updates. I need to know how to detect that shutdown event and send the shutdown command to the server before restart. I am using the subprocess library.

推荐答案

所以,你需要的是 win32API 和描述的函数 此处.您可以使用此函数添加所谓的控制处理程序方法,该方法将在程序因任何原因关闭或终止时运行,包括关闭.您可以找到可以传递给处理程序的不同代码及其含义的列表 这里.理想情况下,您应该有一个处理程序方法来关闭服务器,等待它完成关闭,然后返回.

So, what you will need is the win32API and the function described here. You can use this function to add what's called a Control Handler Method that will run whenever the program is being shut down or terminated for any reason, including shutdown. You can find a list of the different codes that can be passed to the handler and their meanings here. Ideally, you should have a handler method that just shuts down the server, waits for it to finish shutting down, and then return.

我对图书馆没有任何个人经验,但应该相当简单.

I don't have any personal experience with the library, but it should be fairly straightforward.

如@ErykSun 所述,您需要创建一个隐藏窗口才能接收事件.老实说,我不确定如何创建那个隐藏的窗口.一些文档表明,将您的应用程序作为服务运行也可能有效.如果我有时间,我会更多地研究这个.

as noted by @ErykSun, you will need to create a hidden window in order to receive the events. To be quite honest I'm not sure how to create that hidden window. Some documentation suggests that running your application as a service may also work. I will look into this more if I get time.

这篇关于用python检测关机事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆