How to make a python script which can logoff, shut

2019-01-23 20:14发布

问题:

Background

I am currently in the process of teaching myself python, and I thought that it would be a very cool project to have a sort of "control center" in which I could shutdown, restart, and log off of my computer. I also want to use the subprocess module, as I have heard that the import OS module is outdated.

Current Code

def shutdown(self):
    import subprocess
    subprocess.call(["shutdown", "-f", "-s", "-t", "60"])

Question

What I am really asking is, is there a way (using the subprocess module) to logoff of and restart my computer?

Tech Specs

Python 2.7.3

Windows 7, 32 bit

回答1:

To restart:

shutdown /r

To log off:

shutdown /l

The final code block(as requested):

Log off:

def shutdown(self):
    import subprocess
    subprocess.call(["shutdown", "-f", "-s", "-t", "60"])

Restart:

def shutdown(self):
    import subprocess
    subprocess.call(["shutdown", "-f", "-r", "-t", "60"])


回答2:

First you have to:

import subprocess

To shutdown your Windows PC:

subprocess.call(["shutdown", "/s"])

To restart your windows PC

subprocess.call(["shutdown", "/r"])

To logout your Windows PC:

subprocess.call(["shutdown", "/l "])

To shutdown your Windows PC after 900s:

subprocess.call(["shutdown", "/r", "/s", "900"])

To abort shutting down because there is no good reason to shutdown your pc with a python script, you were just copy-pasting code from stackoverflow:

subprocess.call(["shutdown", "/a "])

I only tried these function calls in Python 3.5. First of all, I do not think this has changed since python 2.7, and second: it is 2016, so I guess you have made the switch already since asking this question.



回答3:

If you can't get shutdown to work somehow, you can always just call the function it calls out of the USER library. You could do this via ctypes or win32api, but you can also just do this:

subprocess.call(['rundll32', 'user.exe,ExitWindowsExec')

Or you could call the higher-level shell function that the start menu uses:

subprocess.call(['rundll32', 'shell32.dll,SHExitWindowsEx 2')

(See MSDN documentation on these functions.)

I think this is probably the worst way to do it. If you want to run a command, run shutdown; if you want to use the API, use win32api. But if you've got a bizarrely screwed-up system where shutdown /r just doesn't work, it's an option.