How to make a python script that can exit the system, shut down and restart the computer?

Background

I am currently participating in python, and I thought that it would be a very cool project to have a kind of "control center" in which I could turn off, restart and exit my computer. I also want to use the subprocess module, since I heard that the import operating system module is out of date.

Current code

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

Question

I'm really asking if there is a way (using the subprocess module) to log out and restart the computer?

Specifications

Python 2.7.3

Windows 7 32 bit

+6
source share
3 answers

To restart:

 shutdown /r 

To log out:

 shutdown /l 

End code block (on request):

Sign Out:

 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"]) 
+7
source

First you must:

 import subprocess 

To turn off your Windows computer:

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

To restart a Windows computer

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

To exit a Windows PC:

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

To turn off a Windows computer after 900 s:

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

To abort the shutdown, because there is no good reason to shut down the computer using a Python script, you simply copied the code from stackoverflow:

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

I just tried these function calls in Python 3.5. Firstly, I donโ€™t think that this has changed since Python 2.7, and secondly: this is 2016, so I think you made the transition after you asked this question.

+10
source

If you cannot get shutdown to work somehow, you can always just call the function that it calls from the USER library. You can do this with ctypes or win32api , but you can also just do this:

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

Or you can call a higher-level shell function that the launch menu uses:

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

(See the documentation for these features on MSDN.)

I think this is probably the worst way to do this. If you want to run the command, run shutdown ; if you want to use the API use win32api . But if you have a fancy system where shutdown /r just doesn't work, this is an option.

+2
source

All Articles