Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python script which can logoff, shutdown, and restart a computer?

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

like image 630
xxmbabanexx Avatar asked Feb 08 '13 01:02

xxmbabanexx


People also ask

Can Python shut down PC?

To shut down the computer/PC/laptop by using a Python script, you have to use the os. system() function with the code “ shutdown /s /t 1 ” . Note: For this to work, you have to import os library in the ide. If you don't have it, then ' pip install os ' through the Command Prompt.

How do I put Python to sleep on my computer?

Python sleep() The sleep() function suspends (waits) execution of the current thread for a given number of seconds.

How do you end a program in Python?

Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.


2 Answers

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", "/s", "/t", "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.

like image 103
Johan Avatar answered Sep 23 '22 06:09

Johan


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"])
like image 23
ben_frankly Avatar answered Sep 23 '22 06:09

ben_frankly