Detect shutdown event with python

爱⌒轻易说出口 提交于 2021-02-08 02:58:14

问题


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.


回答1:


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.

EDIT: 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.



来源:https://stackoverflow.com/questions/62856197/detect-shutdown-event-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!