问题
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