script to keep computer awake

Script to Keep Your Computer Awake

Sometimes you may need to keep your computer awake to execute long running scripts or other processes that require your system to be awake. A simple way to do this is to either disable sleep on your system or run a script that keeps your computer awake. The advantage of creating a script is that you can include it in a your program or application, so that your computer is awake only this particulate application is not running and not all the time. In this article, we will learn how to create a script to keep your computer awake. You can use almost any scripting language for this purpose. We will be using python to create our script.


Script to Keep Your Computer Awake

Basically, our script will accept the number of minutes to keep our computer awake (stop_time) and keep right clicking every minute until time’s up. You can always customize the script to shut down or reboot after the input time is over. It also logs current system time and takes screenshot before shut down.

In a loop, we fill first initiate a counter to 0. Then our script will first sleep for 60 seconds, then perform a right click to keep the computer awake, and increase the counter by 1, till it reaches stop_time value. Then it will save the log file, take a screenshot and shutdown/reboot depending on user configuration.

Create a blank python file.

$ vi stay_awake.py

First we will define execution environment (line 1) and then import required libraries into our file. So add the following lines of codes to it.

#!/usr/bin/python
import argparse
import pyautogui
import time
import os

Here is what these libraries are needed for:

  • argparse : pass arguments using this library
  • pyautogui : generate right clicks & take screenshot
  • time : get current system time
  • os : to shutdown or restart the system

Next, we will define a function timer which will take two inputs, stop_time, that is the number of minutes to keep computer awake, and action to be performed when time is up. We will also initiate the counter.

def timer(stop_time, action):
    counter = 0

Next, we will start the loop until counter reaches stop_time. In each iteration, we will increment the counter by 1.

while stop_time > counter:
        counter = counter + 1

Since the above code will get executed within a second, we will add the following lines to make our python interpreter sleep for 60 seconds, in each iteration, after incrementing the loop counter.

        time.sleep(60)
        pyautogui.click(button='right')

We use time.sleep() function to make the interpreter sleep for 60 seconds. We also use pyautogui to make a right click.

Next few lines of code are optional and you can skip it or customize it as per your requirement. Here we simply note the current system date & time and write it to a log file. We also take a screenshot of the system.

#Save current date and time
timestamp = time.strftime('%d-%b-%Y_%H-%M-%S', time.localtime())

#Create a text log when system shuts down
f = open('/home/ubuntu/awake_log.txt','a+')
f.write('Shutting down at {}'.format(timestamp))
f.close()

#Take screenshot
image_location = '/home/ubuntu/' + timestamp + '.jpeg'
pyautogui.screenshot(image_location)

Lastly, we issue shutdown or reboot command, depending on the action specified during function call. If the user has input ‘s’ or ‘S’, we will shut down. If they have input ‘r’ or ‘R’ we will reboot.

#Shutdown system or Restart
if action in ['s', 'S']:
    os.system("shutdown -s -f -t 0")
if action in ['r', 'R']:
    os.system("Shutdown -r -f -t 0")

Next, we call the above timer() function from main function.

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("-t", "--time", help="Enter time in minutes")
    parser.add_argument("-a", "--action", help="want to shutdown?")

    args = parser.parse_args()
        if args.time:
            timer(int(args.time), args.action)

In our main function, we define a parser to parse the arguments. We also call timer() function only if user has provided time argument.

Save and close the file. Make it executable.

$ sudo chmod +x stay_awake.py

Here is the complete code for your reference.

#!/usr/bin/python
import argparse
import pyautogui
import time
import os

def timer(stop_time, action):
    counter = 0
    while stop_time > counter:
        counter = counter + 1
        time.sleep(60)
        pyautogui.click(button='right')

    #Save current date and time
    timestamp = time.strftime('%d-%b-%Y_%H-%M-%S', time.localtime())

    #Create a text log when system shuts down
    f = open('/home/ubuntu/awake_log.txt','a+')
    f.write('Shutting down at {}'.format(timestamp))
    f.close()

    #Take screenshot
    image_location = '/home/ubuntu/' + timestamp + '.jpeg'
    pyautogui.screenshot(image_location)

    #Shutdown system or Restart
    if action in ['s', 'S']:
        os.system("shutdown -s -f -t 0")
    if action in ['r', 'R']:
        os.system("Shutdown -r -f -t 0")

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("-t", "--time", help="Enter time in minutes")
    parser.add_argument("-a", "--action", help="want to shutdown?")

    args = parser.parse_args()
        if args.time:
            timer(int(args.time), args.action)

You can call the above script as shown below.

# keep a system active for 30 minutes
$ python stay_awake.py -t 30

# keep a system active for 1 hour and then shutdown
$ python stay_awake.py -t 60 -a s

# keep a system active for 2 hours and then restart it
$ python stay_awake.py -t 120 -a r

In this article, we have learnt how to create a script to keep computer awake. You can customize it as per your requirement.

Also read:

How to Extract Database from MySQL Dump File
How to Extract Table from MySQL Dump File
How to Extract Tables from PDF in Python
Shell Script to Backup MongoDB Database
How to Terminate Python Subprocess

Leave a Reply

Your email address will not be published. Required fields are marked *